统一全系统资源加载、轻量趋势与缓存恢复
This commit is contained in:
@@ -4,6 +4,7 @@ import { Alert, App, Button, Form, Input, Modal, Select, Spin, Switch, Tag } fro
|
||||
import { SettingOutlined } from '@ant-design/icons';
|
||||
import { api } from './api';
|
||||
import { effectiveThinkingEffort, supportsThinkingEffort } from './analysisThinking';
|
||||
import { useDelayedIndicator } from './useDelayedBusy';
|
||||
|
||||
export type AnalysisModelProfile = { id: string; name: string; baseUrl: string; model: string; hasApiKey: boolean; thinkingEnabled: boolean; thinkingEffort: string };
|
||||
export type AnalysisModelSettings = { baseUrl: string; model: string; hasApiKey: boolean; revision: string; activeProfileId: string; thinkingEnabled: boolean; thinkingEffort: string; profiles: AnalysisModelProfile[] };
|
||||
@@ -19,6 +20,7 @@ export function AnalysisApiSettings({ onUnauthorized }: { onUnauthorized: (error
|
||||
useEffect(() => { if (!effortSupported) form.setFieldValue('thinkingEffort', 'auto'); }, [effortSupported, form]);
|
||||
const [open, setOpen] = useState(false);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const showLoading = useDelayedIndicator(loading, 150);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [testing, setTesting] = useState(false);
|
||||
const [settings, setSettings] = useState<AnalysisModelSettings>();
|
||||
@@ -26,10 +28,11 @@ export function AnalysisApiSettings({ onUnauthorized }: { onUnauthorized: (error
|
||||
const selectedProfile = settings?.profiles.find(profile => profile.id === profileId);
|
||||
const [notice, setNotice] = useState<{ type: 'success' | 'error'; text: string }>();
|
||||
const sequence = useRef(0);
|
||||
const submitLock = useRef(false);
|
||||
const close = () => { if (saving) return; sequence.current += 1; setOpen(false); form.resetFields(); setNotice(undefined); setTesting(false); };
|
||||
const load = async () => {
|
||||
const current = ++sequence.current;
|
||||
setOpen(true); setLoading(true); setSettings(undefined); setProfileId(undefined); setNotice(undefined); form.resetFields();
|
||||
setOpen(true); setLoading(true); setNotice(undefined);
|
||||
try {
|
||||
const value = await api.analysisSettings();
|
||||
if (sequence.current !== current) return;
|
||||
@@ -39,9 +42,10 @@ export function AnalysisApiSettings({ onUnauthorized }: { onUnauthorized: (error
|
||||
} finally { if (sequence.current === current) setLoading(false); }
|
||||
};
|
||||
const submit = async (test: boolean) => {
|
||||
if (!settings) return;
|
||||
if (!settings || submitLock.current) return;
|
||||
let values: AnalysisModelSettingsInput;
|
||||
try { values = await form.validateFields(); } catch { return; }
|
||||
submitLock.current = true;
|
||||
const current = sequence.current;
|
||||
setNotice(undefined); test ? setTesting(true) : setSaving(true);
|
||||
try {
|
||||
@@ -57,7 +61,7 @@ export function AnalysisApiSettings({ onUnauthorized }: { onUnauthorized: (error
|
||||
}
|
||||
} catch (error) {
|
||||
if (sequence.current === current && !onUnauthorized(error)) setNotice({ type: 'error', text: error instanceof Error ? error.message : '操作失败,请重试' });
|
||||
} finally { if (sequence.current === current) { setTesting(false); setSaving(false); } }
|
||||
} finally { submitLock.current = false; if (sequence.current === current) { setTesting(false); setSaving(false); } }
|
||||
};
|
||||
return <>
|
||||
<Button type="text" size="small" icon={<SettingOutlined />} onClick={() => void load()}>API 配置</Button>
|
||||
@@ -66,7 +70,7 @@ export function AnalysisApiSettings({ onUnauthorized }: { onUnauthorized: (error
|
||||
<Button loading={testing} disabled={loading || saving || !settings} onClick={() => void submit(true)}>测试连接</Button>
|
||||
<Button type="primary" loading={saving} disabled={loading || testing || !settings} onClick={() => void submit(false)}>保存并使用</Button>
|
||||
</>}>
|
||||
{loading ? <div style={{ padding: 32, textAlign: 'center' }}><Spin /></div> : <>
|
||||
{showLoading && !settings ? <div style={{ padding: 32, textAlign: 'center' }}><Spin /></div> : <>
|
||||
{settings && <div style={{ marginBottom: 20 }}>
|
||||
<div style={{ marginBottom: 8 }}>选择配置 <Tag color="blue">当前使用:{settings.profiles.find(profile => profile.id === settings.activeProfileId)?.name || settings.model}</Tag></div>
|
||||
<div style={{ display: 'flex', gap: 8 }}>
|
||||
|
||||
@@ -18,6 +18,7 @@ import { resolveAnalysisReportTitle, stripDuplicateFirstMarkdownH1 } from './ana
|
||||
import { useReportVisualImages, type ReportVisualImage } from './AnalysisReportVisuals';
|
||||
import { analysisMemberListFullyRead, analysisMemberListPeriod, parseAnalysisMemberList } from './analysisMembersModel';
|
||||
import { AnalysisRecordListReport, appendAnalysisRecordReportHtml } from './AnalysisRecordList';
|
||||
import { useDelayedIndicator } from './useDelayedBusy';
|
||||
|
||||
type Row = Record<string, unknown>;
|
||||
const record = (value: unknown): Row => value && typeof value === 'object' && !Array.isArray(value) ? value as Row : {};
|
||||
@@ -219,6 +220,7 @@ function ReportExportDialog({ turn, reportMarkdown, reportHtml, native = false }
|
||||
}) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const [exporting, setExporting] = useState(false);
|
||||
const showExporting = useDelayedIndicator(exporting, 150);
|
||||
const [progress, setProgress] = useState('');
|
||||
const [error, setError] = useState('');
|
||||
const [stamp, setStamp] = useState('');
|
||||
@@ -239,6 +241,7 @@ function ReportExportDialog({ turn, reportMarkdown, reportHtml, native = false }
|
||||
const currentExport = useRef({ open, turnId, snapshot, reportHtml, reportMarkdown });
|
||||
currentExport.current = { open, turnId, snapshot, reportHtml, reportMarkdown };
|
||||
const visualReport = useReportVisualImages(turn, open);
|
||||
const showVisualLoading = useDelayedIndicator(visualReport.loading, 150);
|
||||
const safeHtml = useMemo(() => {
|
||||
if (parseServerReadingSummary(reportTurn)) return '';
|
||||
if (!reportHtml?.trim()) return '';
|
||||
@@ -358,10 +361,10 @@ function ReportExportDialog({ turn, reportMarkdown, reportHtml, native = false }
|
||||
: <Button disabled={disabled} onClick={() => void saveHtml()}>下载 HTML</Button>}
|
||||
{prepared
|
||||
? <Button type="primary" disabled={disabled} onClick={() => void downloadPrepared(prepared, 'image')}>下载长图</Button>
|
||||
: <Button type="primary" loading={exporting} disabled={disabled} onClick={() => void prepareImages()}>下载长图</Button>}
|
||||
: <Button type="primary" loading={showExporting} disabled={disabled} onClick={() => void prepareImages()}>下载长图</Button>}
|
||||
</>}>
|
||||
{visualReport.loading && <p role="status">{visualReport.progress || '正在准备报告图表…'}</p>}
|
||||
{progress && <p className="analysis-report-export-status" role="status" aria-live="polite">{progress}</p>}
|
||||
{showVisualLoading && <p role="status">{visualReport.progress || '正在准备报告图表…'}</p>}
|
||||
{progress && (!exporting || showExporting) && <p className="analysis-report-export-status" role="status" aria-live="polite">{progress}</p>}
|
||||
{error && <Alert className="analysis-report-export-error" type="error" showIcon title={error} closable onClose={() => setError('')} />}
|
||||
{visualReport.failed && <Alert type="warning" showIcon title="部分图表未生成,报告保留相应数据表。" />}
|
||||
{visualReport.authorizationError && visualReport.authorizationError !== error && <Alert type="error" showIcon title={visualReport.authorizationError} />}
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { Alert, Button, Select, Switch, Tag } from 'antd';
|
||||
import { api } from './api';
|
||||
import { usePageCache, useMaintenanceRefresh } from './pageCache';
|
||||
import { useDelayedBusy } from './useDelayedBusy';
|
||||
|
||||
const labels: Record<string, string> = { MONTH: '月报', QUARTER: '季报', YEAR: '年报' };
|
||||
export function AnalysisReportsPanel({ periodType, periodKey, disabled, onOpen }: {
|
||||
@@ -10,15 +12,26 @@ export function AnalysisReportsPanel({ periodType, periodKey, disabled, onOpen }
|
||||
const [plans, setPlans] = useState<Record<string, unknown>[]>([]);
|
||||
const [error, setError] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [reportsLoaded, setReportsLoaded] = useState(false);
|
||||
const [plansLoaded, setPlansLoaded] = useState(false);
|
||||
const [expanded, setExpanded] = useState(false);
|
||||
const { active } = usePageCache();
|
||||
const read = useDelayedBusy();
|
||||
const actionInFlight = useRef(false);
|
||||
const [runDay, setRunDay] = useState(1);
|
||||
const load = async () => {
|
||||
try {
|
||||
const [history, savedPlans] = await Promise.all([api.analysisReports(), api.analysisReportPlans()]);
|
||||
setReports(history.items || []); setPlans(savedPlans.items || []);
|
||||
} catch (value) { setError(value instanceof Error ? value.message : '报告读取失败'); }
|
||||
};
|
||||
useEffect(() => { void load(); }, []);
|
||||
const load = useCallback(() => read.run(async () => {
|
||||
const [history, savedPlans] = await Promise.allSettled([api.analysisReports(), api.analysisReportPlans()]);
|
||||
const errors: string[] = [];
|
||||
if (history.status === 'fulfilled') { setReports(history.value.items || []); setReportsLoaded(true); }
|
||||
else errors.push(`报告列表:${history.reason instanceof Error ? history.reason.message : '读取失败'}`);
|
||||
if (savedPlans.status === 'fulfilled') { setPlans(savedPlans.value.items || []); setPlansLoaded(true); }
|
||||
else errors.push(`自动计划:${savedPlans.reason instanceof Error ? savedPlans.reason.message : '读取失败'}`);
|
||||
setError(errors.join(';'));
|
||||
}), [read.run]);
|
||||
useEffect(() => { if (active && expanded && (!reportsLoaded || !plansLoaded)) void load(); }, [active, expanded, reportsLoaded, plansLoaded, load]);
|
||||
useMaintenanceRefresh(() => { if (expanded) void load(); });
|
||||
const generate = async () => {
|
||||
if (actionInFlight.current) return; actionInFlight.current = true;
|
||||
setBusy(true); setError('');
|
||||
try {
|
||||
const response = await api.createAnalysisReport({ periodType, periodKey });
|
||||
@@ -27,9 +40,10 @@ export function AnalysisReportsPanel({ periodType, periodKey, disabled, onOpen }
|
||||
if (typeof sessionId === 'string' && typeof turnId === 'string') onOpen(sessionId, turnId);
|
||||
else setError('报告已登记,正在准备分析任务,请稍后刷新列表。');
|
||||
} catch (value) { setError(value instanceof Error ? value.message : '报告生成失败'); }
|
||||
finally { setBusy(false); }
|
||||
finally { actionInFlight.current = false; setBusy(false); }
|
||||
};
|
||||
const toggle = async (type: string, enabled: boolean) => {
|
||||
if (actionInFlight.current) return; actionInFlight.current = true;
|
||||
setBusy(true); setError('');
|
||||
try {
|
||||
const found = plans.find(plan => plan.periodType === type || plan.reportType === type);
|
||||
@@ -38,24 +52,27 @@ export function AnalysisReportsPanel({ periodType, periodKey, disabled, onOpen }
|
||||
else await api.createAnalysisReportPlan(body);
|
||||
await load();
|
||||
} catch (value) { setError(value instanceof Error ? value.message : '报告计划保存失败'); }
|
||||
finally { setBusy(false); }
|
||||
finally { actionInFlight.current = false; setBusy(false); }
|
||||
};
|
||||
const saveDay = async () => {
|
||||
if (actionInFlight.current) return; actionInFlight.current = true;
|
||||
setBusy(true); setError('');
|
||||
try {
|
||||
await Promise.all(plans.map(plan => api.updateAnalysisReportPlan(String(plan.id), { runDay, runHour: 9 })));
|
||||
await load();
|
||||
} catch (value) { setError(value instanceof Error ? value.message : '执行日期保存失败'); }
|
||||
finally { setBusy(false); }
|
||||
finally { actionInFlight.current = false; setBusy(false); }
|
||||
};
|
||||
return <details className="analysis-reports"><summary>月报、季报与年报</summary>
|
||||
return <details className="analysis-reports" onToggle={event => setExpanded(event.currentTarget.open)}><summary>月报、季报与年报</summary>
|
||||
<p>报告使用统一指标与同一分析任务,包含期间比较、趋势和异常追查。自动计划在本机服务运行时执行。</p>
|
||||
{error && <Alert type="warning" showIcon message={error} />}
|
||||
{error && <Alert type="error" showIcon message="报告信息读取失败" description={reportsLoaded || plansLoaded ? `${error};成功读取的内容仍保留。` : error} action={!reportsLoaded || !plansLoaded ? <Button size="small" onClick={() => void load()}>重试</Button> : undefined} />}
|
||||
{read.busy && !reportsLoaded && !plansLoaded && <div className="loading-panel">正在读取报告与自动计划…</div>}
|
||||
<div className="ai-actions"><span>{periodKey} · {labels[periodType]} · 总体范围</span><Button disabled={disabled || busy} loading={busy} onClick={() => void generate()}>生成本期{labels[periodType]}</Button><Button disabled={busy} onClick={() => void load()}>刷新报告</Button></div>
|
||||
<div className="analysis-report-plans"><span>自动生成上一完整周期:每个适用周期首月</span><Select aria-label="自动报告执行日" value={runDay} onChange={setRunDay} options={Array.from({ length: 28 }, (_, i) => ({ label: `${i + 1}日 09:00`, value: i + 1 }))} />
|
||||
{plansLoaded && <div className="analysis-report-plans"><span>自动生成上一完整周期:每个适用周期首月</span><Select aria-label="自动报告执行日" value={runDay} onChange={setRunDay} options={Array.from({ length: 28 }, (_, i) => ({ label: `${i + 1}日 09:00`, value: i + 1 }))} />
|
||||
{Object.entries(labels).map(([type, label]) => { const plan = plans.find(item => item.periodType === type || item.reportType === type); return <label key={type}>{label} <Switch aria-label={`自动${label}`} disabled={busy} checked={plan?.enabled === true} onChange={value => void toggle(type, value)} /></label>; })}
|
||||
<Button size="small" disabled={busy || !plans.length} onClick={() => void saveDay()}>保存执行日期</Button>
|
||||
</div>
|
||||
{reports.length > 0 && <ul>{reports.slice(0, 8).map(report => <li key={String(report.id)}><span>{String(report.periodKey)} {labels[String(report.periodType)] || ''}</span> <Tag>{String(report.status)}</Tag><Button type="link" disabled={disabled || !report.sessionId || !report.turnId} onClick={() => onOpen(String(report.sessionId), String(report.turnId))}>查看分析</Button></li>)}</ul>}
|
||||
</div>}
|
||||
{reportsLoaded && reports.length > 0 && <ul>{reports.slice(0, 8).map(report => <li key={String(report.id)}><span>{String(report.periodKey)} {labels[String(report.periodType)] || ''}</span> <Tag>{String(report.status)}</Tag><Button type="link" disabled={disabled || !report.sessionId || !report.turnId} onClick={() => onOpen(String(report.sessionId), String(report.turnId))}>查看分析</Button></li>)}</ul>}
|
||||
{reportsLoaded && !reports.length && <p className="completion-note">当前没有已生成的报告。</p>}
|
||||
</details>;
|
||||
}
|
||||
|
||||
@@ -16,6 +16,7 @@ import {
|
||||
visualUnitLabel,
|
||||
} from './analysisVisualsModel';
|
||||
import type { AnalysisVisual } from './analysisVisualsModel';
|
||||
import { useDelayedIndicator } from './useDelayedBusy';
|
||||
import { analysisVisualCumulativeShares, analysisVisualShares, analysisVisualTypeLabel } from './analysisVisualPresentation';
|
||||
import './analysis-visuals.css';
|
||||
|
||||
@@ -126,9 +127,11 @@ export function AnalysisVisualCard({ visual, beforeExport, loadRuntime = loadAna
|
||||
const [nearViewport, setNearViewport] = useState(false);
|
||||
const [chartReady, setChartReady] = useState(false);
|
||||
const [chartLoading, setChartLoading] = useState(false);
|
||||
const showChartLoading = useDelayedIndicator(chartLoading, 150);
|
||||
const [chartError, setChartError] = useState('');
|
||||
const [dataOpen, setDataOpen] = useState(false);
|
||||
const [exporting, setExporting] = useState(false);
|
||||
const showExporting = useDelayedIndicator(exporting, 150);
|
||||
const [exportError, setExportError] = useState('');
|
||||
const [themeRevision, setThemeRevision] = useState(0);
|
||||
const [renderAttempt, setRenderAttempt] = useState(0);
|
||||
@@ -312,9 +315,9 @@ export function AnalysisVisualCard({ visual, beforeExport, loadRuntime = loadAna
|
||||
<Button size="small" icon={<TableOutlined />} onClick={openData}>查看数据</Button>
|
||||
<Dropdown
|
||||
trigger={['click']}
|
||||
menu={{ items: [{ key: 'png', icon: <DownloadOutlined />, label: exporting ? '正在导出…' : '下载 PNG', disabled: !visual.chartable || exporting, onClick: () => { void download(); } }] }}
|
||||
menu={{ items: [{ key: 'png', icon: <DownloadOutlined />, label: showExporting ? '正在导出…' : '下载 PNG', disabled: !visual.chartable || exporting, onClick: () => { void download(); } }] }}
|
||||
>
|
||||
<Button size="small" aria-label="更多图表操作" icon={exporting ? <span className="analysis-visual-spinner" aria-hidden="true" /> : <MoreOutlined />} />
|
||||
<Button size="small" aria-label="更多图表操作" icon={showExporting ? <span className="analysis-visual-spinner" aria-hidden="true" /> : <MoreOutlined />} />
|
||||
</Dropdown>
|
||||
</div>
|
||||
</header>
|
||||
@@ -337,7 +340,7 @@ export function AnalysisVisualCard({ visual, beforeExport, loadRuntime = loadAna
|
||||
style={visual.type === 'heatmap' ? { minWidth: Math.max(380, visual.categories.length * 62 + 160) }
|
||||
: visual.type === 'pareto' ? { minWidth: Math.max(600, visual.categories.length * 90 + 180) } : undefined} />
|
||||
{!nearViewport && <div className="analysis-visual-placeholder">图表将在进入视口时加载</div>}
|
||||
{nearViewport && chartLoading && <div className="analysis-visual-placeholder" role="status">正在加载图表…</div>}
|
||||
{nearViewport && showChartLoading && <div className="analysis-visual-placeholder" role="status">正在加载图表…</div>}
|
||||
{chartError && <div className="analysis-visual-chart-error" role="status">{chartError}
|
||||
<Button size="small" loading={retrying || chartLoading} onKeyDown={event => event.stopPropagation()}
|
||||
onClick={event => { event.stopPropagation(); void retryChart(); }}>重试图表</Button>
|
||||
|
||||
@@ -1,19 +1,29 @@
|
||||
import { readQueryLocation } from './queryLoadingScope';
|
||||
import { flushSync } from 'react-dom';
|
||||
import { createWorkspaceTransition, waitForWorkspaceContent } from './workspaceTransition';
|
||||
import { forwardRef, lazy, Suspense, useEffect, useImperativeHandle, useLayoutEffect, useRef, useState } from 'react';
|
||||
import { Alert, Button, Spin } from 'antd';
|
||||
import { api } from './api';
|
||||
import { api, configureRequestScope, resetRequestScope } from './api';
|
||||
import { pageUsesResources } from './resourceInvalidation';
|
||||
import type { AuthUser, QueryParams } from './types';
|
||||
import type { PageKey } from './QualityWorkspace';
|
||||
import { PageCacheContext, WORKSPACE_INVALIDATED } from './pageCache';
|
||||
|
||||
const QueryPage = lazy(() => import('./QueryPage'));
|
||||
const StageProductPage = lazy(() => import('./StageProductPage'));
|
||||
const ManagementPages = lazy(() => import('./ManagementPages'));
|
||||
const loadQueryPage = () => import('./QueryPage');
|
||||
const loadStageProductPage = () => import('./StageProductPage');
|
||||
const loadManagementPages = () => import('./ManagementPages');
|
||||
const QueryPage = lazy(loadQueryPage);
|
||||
const StageProductPage = lazy(loadStageProductPage);
|
||||
const ManagementPages = lazy(loadManagementPages);
|
||||
|
||||
export function preloadWorkspacePage(page: PageKey): Promise<unknown> {
|
||||
return page === 'blackProduct' || page === 'brightProduct' ? loadStageProductPage()
|
||||
: QUERY_PAGES.includes(page) ? loadQueryPage() : loadManagementPages();
|
||||
}
|
||||
const QUERY_PAGES: PageKey[] = ['overall', 'department', 'group', 'product', 'blackProduct', 'brightProduct'];
|
||||
const retained = (_page: PageKey) => true;
|
||||
type ResultRef = { kind: 'TOP'; resultId: string; releaseId: string };
|
||||
type Entry = { initialSearch: string; search: string; key: number; scroll: number };
|
||||
type Entry = { initialSearch: string; search: string; key: number; scroll: number; revision?: number };
|
||||
export type WorkspaceNavigation = { navigate: (page: PageKey, query?: QueryParams, resultRef?: ResultRef) => void; syncLocation: () => void };
|
||||
function encode(value: unknown) {
|
||||
const bytes = new TextEncoder().encode(JSON.stringify(value));
|
||||
@@ -23,10 +33,12 @@ function encode(value: unknown) {
|
||||
export const CachedWorkspacePages = forwardRef<WorkspaceNavigation, {
|
||||
page: PageKey; user: AuthUser; onPageChange: (page: PageKey) => void; onUserChange: (user: AuthUser) => void; onUnauthorized: (error: unknown) => boolean;
|
||||
}>(function CachedWorkspacePages({ page, user, onPageChange, onUserChange, onUnauthorized }, ref) {
|
||||
const userRef = useRef(user);
|
||||
userRef.current = user;
|
||||
const entries = useRef(new Map<PageKey, Entry>([[page, { initialSearch: location.search, search: location.search, key: 0, scroll: 0 }]]));
|
||||
const requested = useRef(page);
|
||||
const current = useRef(page), generation = useRef(0), key = useRef(0);
|
||||
const revisions = useRef<{ authRevision: string; dataRevision: string } | null>(null);
|
||||
const revisions = useRef<{ authRevision: string; dataRevision: string; currentReleaseId: string | null } | null>(null);
|
||||
const validation = useRef<Promise<boolean> | null>(null);
|
||||
const [refreshKey, setRefreshKey] = useState(0), [, render] = useState(0);
|
||||
const [ready, setReady] = useState(false), [error, setError] = useState('');
|
||||
@@ -38,28 +50,47 @@ export const CachedWorkspacePages = forwardRef<WorkspaceNavigation, {
|
||||
() => window.matchMedia('(prefers-reduced-motion: reduce)').matches,
|
||||
busy => { if (alive.current) setNavigationBusy(busy); },
|
||||
);
|
||||
const validate = () => {
|
||||
const validate = (warmVisibleOptions = false) => {
|
||||
if (validation.current) return validation.current;
|
||||
const epoch = generation.current;
|
||||
const request = (async () => {
|
||||
try {
|
||||
const state = await api.workspaceState();
|
||||
if (!alive.current || generation.current !== epoch) return false;
|
||||
if (revisions.current && state.authRevision !== revisions.current.authRevision) {
|
||||
configureRequestScope({ userId: userRef.current.id, ...state });
|
||||
if ((revisions.current && state.authRevision !== revisions.current.authRevision) || entries.current.size === 0) {
|
||||
// 已知授权变化时立即撤下旧结果,不能等待身份读取成功才清除。
|
||||
setReady(false);
|
||||
entries.current.clear();
|
||||
render(value => value + 1);
|
||||
const latest = await api.me();
|
||||
if (!alive.current || generation.current !== epoch) return false;
|
||||
// 权限改变时清除全部旧缓存,重建此刻正在查看的页面;校验不负责切换路由。
|
||||
transitions.current?.cancel(); requested.current = current.current;
|
||||
userRef.current = latest;
|
||||
configureRequestScope({ userId: latest.id, ...state });
|
||||
onUserChange(latest); entries.current.clear();
|
||||
entries.current.set(current.current, { initialSearch: location.search, search: location.search, key: ++key.current, scroll: 0 });
|
||||
render(value => value + 1);
|
||||
}
|
||||
if (revisions.current && state.dataRevision !== revisions.current.dataRevision) setRefreshKey(value => value + 1);
|
||||
revisions.current = state;
|
||||
render(value => value + 1);
|
||||
setError('');
|
||||
// The visible query needs these options; start their shared read before its code mounts.
|
||||
if (warmVisibleOptions && QUERY_PAGES.includes(requested.current)) {
|
||||
void api.options().catch(() => {});
|
||||
if (requested.current === 'blackProduct' || requested.current === 'brightProduct') {
|
||||
const explicitRelease = readQueryLocation(entries.current.get(requested.current)?.initialSearch || '').releaseId;
|
||||
void api.sourceColumnCatalog(explicitRelease || state.currentReleaseId || undefined).catch(() => {});
|
||||
}
|
||||
}
|
||||
setReady(true);
|
||||
return true;
|
||||
} catch (value) {
|
||||
if (alive.current && generation.current === epoch && value && typeof value === 'object' && 'status' in value && value.status === 403) {
|
||||
setReady(false); entries.current.clear(); resetRequestScope();
|
||||
}
|
||||
if (alive.current && generation.current === epoch && !onUnauthorized(value)) setError(value instanceof Error ? value.message : '页面状态校验失败,请重试');
|
||||
return false;
|
||||
}
|
||||
@@ -79,6 +110,11 @@ export const CachedWorkspacePages = forwardRef<WorkspaceNavigation, {
|
||||
const entry = entries.current.get(next)!;
|
||||
requested.current = next;
|
||||
transitions.current!.run(async signal => {
|
||||
// 先核实权限与版本,再让已保留页面重新订阅,避免旧版本内容先闪出。
|
||||
if (!await validate(true) || signal.aborted) {
|
||||
if (!signal.aborted && requested.current === next) requested.current = current.current;
|
||||
return;
|
||||
}
|
||||
if (!alive.current || entries.current.get(next) !== entry) return;
|
||||
// 与浏览器快照同步提交页面及滚动位置,避免转场结束后再补一次定位。
|
||||
flushSync(() => {
|
||||
@@ -86,8 +122,8 @@ export const CachedWorkspacePages = forwardRef<WorkspaceNavigation, {
|
||||
current.current = next; onPageChange(next); render(value => value + 1);
|
||||
});
|
||||
window.scrollTo(0, entry.scroll);
|
||||
void validate();
|
||||
await waitForWorkspaceContent(() => document.querySelector(`.page-view[data-page="${next}"]`), signal);
|
||||
if (!signal.aborted && current.current === next && entries.current.get(next) === entry) window.scrollTo(0, entry.scroll);
|
||||
});
|
||||
};
|
||||
const navigate = (next: PageKey, query?: QueryParams, resultRef?: ResultRef) => {
|
||||
@@ -105,10 +141,22 @@ export const CachedWorkspacePages = forwardRef<WorkspaceNavigation, {
|
||||
} }));
|
||||
useEffect(() => {
|
||||
alive.current = true;
|
||||
void validate();
|
||||
const invalidate = () => setRefreshKey(value => value + 1);
|
||||
configureRequestScope({ userId: userRef.current.id, authRevision: null, dataRevision: null, currentReleaseId: null });
|
||||
void validate(true);
|
||||
const invalidate = (event: Event) => {
|
||||
const resources = (event as CustomEvent<{ resources?: string[] }>).detail?.resources;
|
||||
for (const [name, entry] of entries.current) {
|
||||
if (pageUsesResources(name, resources)) entry.revision = (entry.revision || 0) + 1;
|
||||
}
|
||||
render(value => value + 1);
|
||||
void validate();
|
||||
};
|
||||
const foreground = () => { if (document.visibilityState === 'visible') void validate(); };
|
||||
window.addEventListener(WORKSPACE_INVALIDATED, invalidate);
|
||||
return () => { alive.current = false; transitions.current?.cancel(); generation.current++; validation.current = null; window.removeEventListener(WORKSPACE_INVALIDATED, invalidate); };
|
||||
window.addEventListener('quality-permission-recheck', foreground);
|
||||
window.addEventListener('focus', foreground);
|
||||
document.addEventListener('visibilitychange', foreground);
|
||||
return () => { alive.current = false; transitions.current?.cancel(); generation.current++; validation.current = null; resetRequestScope(); window.removeEventListener(WORKSPACE_INVALIDATED, invalidate); window.removeEventListener('quality-permission-recheck', foreground); window.removeEventListener('focus', foreground); document.removeEventListener('visibilitychange', foreground); };
|
||||
}, []);
|
||||
const activeEntryKey = entries.current.get(page)?.key;
|
||||
useLayoutEffect(() => {
|
||||
@@ -121,7 +169,7 @@ export const CachedWorkspacePages = forwardRef<WorkspaceNavigation, {
|
||||
return <>{connectionNotice}{Array.from(entries.current.entries()).filter(([name]) => retained(name) || name === page).map(([name, entry]) => {
|
||||
const active = name === page;
|
||||
return <div key={`${name}-${entry.key}`} className="page-view" data-page={name} hidden={!active} inert={active && navigationBusy} style={!active ? { display: 'none' } : undefined}>
|
||||
<PageCacheContext.Provider value={{ active, initialSearch: entry.initialSearch, refreshKey, onLocationChange: search => { entry.search = search; } }}>
|
||||
<PageCacheContext.Provider value={{ active, initialSearch: entry.initialSearch, refreshKey: refreshKey + (entry.revision || 0), currentReleaseId: revisions.current?.currentReleaseId, authRevision: revisions.current?.authRevision, dataRevision: revisions.current?.dataRevision, onLocationChange: search => { entry.search = search; } }}>
|
||||
<Suspense fallback={<div className="loading-panel"><Spin />正在打开页面…</div>}>
|
||||
{name === 'blackProduct' || name === 'brightProduct' ? <StageProductPage stage={name === 'blackProduct' ? 'black' : 'bright'} onUnauthorized={onUnauthorized} /> : QUERY_PAGES.includes(name) ? <QueryPage page={name} onUnauthorized={onUnauthorized} onNavigate={navigate} /> : <ManagementPages page={name} user={user} onUnauthorized={onUnauthorized} onNavigate={navigate} />}
|
||||
</Suspense>
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { usePageCache } from './pageCache';
|
||||
import { useDelayedIndicator } from './useDelayedBusy';
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { Alert, Button, Select, Spin } from 'antd';
|
||||
import { DownOutlined, UpOutlined } from '@ant-design/icons';
|
||||
@@ -6,6 +8,7 @@ import type { FilterField } from './types';
|
||||
import { readableSelectPopup } from './readableSelectPopup';
|
||||
|
||||
function FieldSelect({ field, value, onChange, onUnauthorized }: { field: FilterField; value: string[]; onChange: (values: string[]) => void; onUnauthorized: (error: unknown) => boolean }) {
|
||||
const { active } = usePageCache();
|
||||
const [search, setSearch] = useState('');
|
||||
const [choices, setChoices] = useState<string[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
@@ -13,23 +16,25 @@ function FieldSelect({ field, value, onChange, onUnauthorized }: { field: Filter
|
||||
const [error, setError] = useState('');
|
||||
const [revision, setRevision] = useState(0);
|
||||
const generation = useRef(0);
|
||||
const showLoading = useDelayedIndicator(loading);
|
||||
useEffect(() => {
|
||||
const current = ++generation.current;
|
||||
if (!active) return;
|
||||
const current = ++generation.current, controller = new AbortController();
|
||||
setLoading(true); setChoices([]); setError('');
|
||||
const timer = window.setTimeout(() => {
|
||||
api.filterFieldOptions(field.key, search).then(result => {
|
||||
api.filterFieldOptions(field.key, search, controller.signal).then(result => {
|
||||
if (generation.current !== current) return;
|
||||
setChoices(result.values); setHasMore(result.hasMore);
|
||||
}).catch(e => { if (generation.current === current && !onUnauthorized(e)) setError(e.message || '选项加载失败'); })
|
||||
.finally(() => { if (generation.current === current) setLoading(false); });
|
||||
}, search ? 250 : 0);
|
||||
return () => { window.clearTimeout(timer); generation.current++; };
|
||||
}, [field.key, search, revision, onUnauthorized]);
|
||||
return () => { window.clearTimeout(timer); controller.abort(); generation.current++; };
|
||||
}, [active, field.key, search, revision, onUnauthorized]);
|
||||
return <label className="query-field query-extra-field"><span>{field.label}</span><Select mode="multiple" allowClear showSearch aria-label={field.label}
|
||||
{...readableSelectPopup} maxTagCount="responsive" value={value} loading={loading} filterOption={false} searchValue={search} onSearch={setSearch}
|
||||
{...readableSelectPopup} maxTagCount="responsive" value={value} loading={showLoading} filterOption={false} searchValue={search} onSearch={setSearch}
|
||||
onChange={values => { onChange(values); setSearch(''); }} placeholder="全部"
|
||||
options={[...new Set([...choices, ...value.filter(v => v !== '__EMPTY__')])].map(v => ({ label: v, value: v })).concat(field.allowEmpty ? [{ label: '空值', value: '__EMPTY__' }] : [])}
|
||||
notFoundContent={loading ? <Spin size="small" /> : error ? <Button size="small" onClick={() => setRevision(n => n + 1)}>加载失败,重试</Button> : '暂无匹配项'}
|
||||
notFoundContent={showLoading ? <Spin size="small" /> : error ? <Button size="small" onClick={() => setRevision(n => n + 1)}>加载失败,重试</Button> : '暂无匹配项'}
|
||||
popupRender={menu => <>{menu}{hasMore && <div className="query-options-hint">选项较多,请输入关键字查找</div>}{error && <div role="alert" className="query-options-hint">{error}</div>}</>}
|
||||
/></label>;
|
||||
}
|
||||
@@ -38,22 +43,25 @@ export function ExtraQueryFilters({ projectGroup, projectGroups, onProjectGroup,
|
||||
projectGroup: string[]; projectGroups?: string[]; onProjectGroup: (values: string[]) => void;
|
||||
value: Record<string, string[]>; onChange: (value: Record<string, string[]>) => void; onUnauthorized: (error: unknown) => boolean;
|
||||
}) {
|
||||
const { active } = usePageCache();
|
||||
const [open, setOpen] = useState(false);
|
||||
const [fields, setFields] = useState<FilterField[]>([]);
|
||||
const [error, setError] = useState('');
|
||||
const [revision, setRevision] = useState(0);
|
||||
useEffect(() => {
|
||||
if (!active || !open) return;
|
||||
let alive = true;
|
||||
api.filterFields().then(result => { if (alive) { setFields(result); setError(''); } }).catch(e => { if (alive && !onUnauthorized(e)) setError(e.message || '筛选字段加载失败'); });
|
||||
return () => { alive = false; };
|
||||
}, [revision, onUnauthorized]);
|
||||
const controller = new AbortController();
|
||||
api.filterFields(false, controller.signal).then(result => { if (alive) { setFields(result); setError(''); } }).catch(e => { if (alive && !onUnauthorized(e)) setError(e.message || '筛选字段加载失败'); });
|
||||
return () => { alive = false; controller.abort(); };
|
||||
}, [active, open, revision, onUnauthorized]);
|
||||
const count = (projectGroup.length ? 1 : 0) + Object.values(value).filter(v => v.length).length;
|
||||
const summary = [projectGroup.length ? `项目组:${projectGroup.map(v => v === '__UNASSIGNED__' ? '未分类' : v).join('、')}` : '', ...Object.entries(value).filter(([, values]) => values.length).map(([key, values]) => `${fields.find(f => f.key === key)?.label || key}:${values.map(v => v === '__EMPTY__' ? '空值' : v).join('、')}`)].filter(Boolean).join(';');
|
||||
return <>
|
||||
<div className="query-more-toggle" title={summary || undefined}><Button type="text" size="small" icon={open ? <UpOutlined /> : <DownOutlined />} aria-expanded={open} onClick={() => setOpen(v => !v)}>更多筛选{count ? `(已选 ${count} 项)` : ''}</Button>
|
||||
{count > 0 && <Button type="link" size="small" onClick={() => { onProjectGroup([]); onChange({}); }}>清除</Button>}
|
||||
</div>
|
||||
{error && <Alert className="query-extra-error" type="error" showIcon message={error} action={<Button onClick={() => setRevision(n => n + 1)}>重试</Button>} />}
|
||||
{open && error && <Alert className="query-extra-error" type="error" showIcon message={error} action={<Button onClick={() => setRevision(n => n + 1)}>重试</Button>} />}
|
||||
{open && <div className="query-extra-fields">
|
||||
{projectGroups && <label className="query-field query-extra-field"><span>项目组</span><Select aria-label="项目组" mode="multiple" maxTagCount="responsive" allowClear showSearch optionFilterProp="label" {...readableSelectPopup} value={projectGroup} onChange={onProjectGroup} placeholder="全部" options={[...projectGroups.map(v => ({ label: v, value: v })), { label: '未分类', value: '__UNASSIGNED__' }]} /></label>}
|
||||
{fields.map(field => <FieldSelect key={field.key} field={field} value={value[field.key] || []} onUnauthorized={onUnauthorized} onChange={values => { const next = { ...value }; if (values.length) next[field.key] = values; else delete next[field.key]; onChange(next); }} />)}
|
||||
|
||||
+289
-139
File diff suppressed because one or more lines are too long
+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>;
|
||||
}
|
||||
|
||||
@@ -4,7 +4,9 @@ import { PageCacheContext, usePageCache } from './pageCache';
|
||||
|
||||
export function ManagementSections({ items, initialKey, onSelect }: { items: { key: string; label: ReactNode; children: ReactNode }[]; initialKey?: string; onSelect?: (key: string) => void }) {
|
||||
const cache = usePageCache();
|
||||
const [selected, setSelected] = useState(initialKey ?? items[0]?.key);
|
||||
const initialSelected = initialKey && items.some(item => item.key === initialKey) ? initialKey : items[0]?.key;
|
||||
const [selected, setSelected] = useState(initialSelected);
|
||||
const activeKey = items.some(item => item.key === selected) ? selected : items[0]?.key;
|
||||
return <Tabs className="management-sections" activeKey={activeKey} destroyOnHidden={false} onChange={key => { setSelected(key); onSelect?.(key); window.scrollTo({ top: 0 }); }} items={items.map(item => ({ ...item, children: <PageCacheContext.Provider value={{ ...cache, active: cache.active && item.key === activeKey }}>{item.children}</PageCacheContext.Provider> }))} />;
|
||||
const [visited, setVisited] = useState(() => new Set(activeKey ? [activeKey] : []));
|
||||
return <Tabs className="management-sections" activeKey={activeKey} destroyOnHidden={false} onChange={key => { setSelected(key); setVisited(previous => new Set(previous).add(key)); onSelect?.(key); window.scrollTo({ top: 0 }); }} items={items.map(item => ({ ...item, children: <PageCacheContext.Provider value={{ ...cache, active: cache.active && item.key === activeKey }}>{visited.has(item.key) ? item.children : null}</PageCacheContext.Provider> }))} />;
|
||||
}
|
||||
|
||||
+185
-97
@@ -1,5 +1,5 @@
|
||||
import { configurationDateTime } from './configurationName';
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { Alert, App, Button, Checkbox, Empty, Form, Input, InputNumber, Modal, Progress, Select, Spin, Steps, Tag } from 'antd';
|
||||
import { QualityTable as Table } from './QualityTable';
|
||||
import { ArrowRightOutlined, DeleteOutlined, FileExcelOutlined, ReloadOutlined, SwapOutlined, UndoOutlined, UploadOutlined } from '@ant-design/icons';
|
||||
@@ -7,7 +7,12 @@ import { api, collectionItems } from './api';
|
||||
import type { AuthUser, SourceItem } from './types';
|
||||
import type { DataField, DataStage, DataWorkflowOperation, DataWorkflowStatus, DeletionSource, MasterWorkbookKeyFormat, MasterWorkbookKind, MasterWorkbookPreview, SourceDeletionPreview, SourceUploadOptions, WorkbookPreview } from './NoCodeDataTypes';
|
||||
import { useDataWorkflowOperation } from './useDataWorkflowOperation';
|
||||
import { detectSourceWorkbook } from './sourceWorkbookDetection';
|
||||
import { readableSelectPopup } from './readableSelectPopup';
|
||||
import { usePageCache } from './pageCache';
|
||||
import { useDelayedBusy, useDelayedIndicator } from './useDelayedBusy';
|
||||
import { useVisiblePolling } from './useVisiblePolling';
|
||||
import { runImportPollFollowup } from './importLifecycleGuards';
|
||||
import './no-code-data-workflow.css';
|
||||
|
||||
type Row = Record<string, unknown>;
|
||||
@@ -55,6 +60,7 @@ function SimplifiedDataWorkflow({ options, workflowStatus, pendingDeletion, onDe
|
||||
const [activeId, setActiveId] = useState('');
|
||||
const [reading, setReading] = useState<{ done: number; total: number } | null>(null);
|
||||
const [busy, setBusy] = useState(false); const [error, setError] = useState('');
|
||||
const actionLock = useRef(false);
|
||||
const uploadOperation = useDataWorkflowOperation('source-import', () => { setDrafts([]); setActiveId(''); configured.current.clear(); consumed.current.clear(); onRefresh(); message.success('所选来源已统一导入,报表已更新'); });
|
||||
const recalcOperation = useDataWorkflowOperation('recalculate', value => { if (Array.isArray(value.sourceIds)) onDeleted(value.sourceIds.map(String)); onRefresh(); message.success('报表已更新'); });
|
||||
const active = drafts.find(item => item.id === activeId) || drafts[0];
|
||||
@@ -80,8 +86,9 @@ function SimplifiedDataWorkflow({ options, workflowStatus, pendingDeletion, onDe
|
||||
const reportError = (value: unknown) => { if (!onUnauthorized(value)) setError(failure(value)); };
|
||||
const removeDraft = (id: string) => { setDrafts(previous => previous.filter(item => item.id !== id)); configured.current.delete(id); };
|
||||
const readFiles = async (files: File[]) => {
|
||||
if (!files.length || importBusy) return;
|
||||
if (files.length + drafts.length > 50) { setError('一次最多导入50个文件'); if (input.current) input.current.value = ''; return; }
|
||||
if (!files.length || importBusy || actionLock.current) return;
|
||||
actionLock.current = true;
|
||||
if (files.length + drafts.length > 50) { setError('一次最多导入50个文件'); actionLock.current = false; if (input.current) input.current.value = ''; return; }
|
||||
setBusy(true); setError(''); const failures: string[] = [];
|
||||
const known = new Set(drafts.map(item => `${item.file.name}:${item.file.size}:${item.file.lastModified}`));
|
||||
const selected = files.filter(file => { const key = `${file.name}:${file.size}:${file.lastModified}`; if (known.has(key)) return false; known.add(key); return true; });
|
||||
@@ -89,9 +96,8 @@ function SimplifiedDataWorkflow({ options, workflowStatus, pendingDeletion, onDe
|
||||
for (let index = 0; index < selected.length; index += 2) {
|
||||
const results = await Promise.all(selected.slice(index, index + 2).map(async file => {
|
||||
try {
|
||||
const result = await api.previewSourceWorkbook(file);
|
||||
const scores = (['black', 'bright'] as DataStage[]).map(value => { const required = (options.fields[value] || []).filter(field => field.required); const matched = matchFields(options.fields[value] || [], result.preview.headers); return { stage: value, score: required.length ? required.filter(field => matched[field.name]).length / required.length : 0 }; });
|
||||
const detected = scores.sort((a, b) => b.score - a.score)[0].stage;
|
||||
const uploaded = await api.previewSourceWorkbook(file);
|
||||
const { workbook: result, stage: detected } = await detectSourceWorkbook(uploaded, options.fields, api.sourceWorkbookPreview);
|
||||
const nextMonth = Number(file.name.match(/(?:^|\D)(0?[1-9]|1[0-2])月/)?.[1] || new Date().getMonth() + 1);
|
||||
const nextYear = Number(file.name.match(/(20\d{2})年/)?.[1] || new Date().getFullYear());
|
||||
return { id: crypto.randomUUID(), file, workbook: result, stage: detected, year: nextYear, month: nextMonth, sheetName: result.preview.sheetName, headerRow: result.preview.headerRow, fieldMap: matchFields(options.fields[detected] || [], result.preview.headers), mode: 'ADD' as const, targetId: '', scopeCode: options.scopes[0] || 'ALL' };
|
||||
@@ -102,19 +108,19 @@ function SimplifiedDataWorkflow({ options, workflowStatus, pendingDeletion, onDe
|
||||
setReading({ done: Math.min(index + 2, selected.length), total: selected.length });
|
||||
}
|
||||
if (failures.length) setError(`以下文件未加入导入列表,可重新选择:${failures.join(';')}`);
|
||||
setReading(null); setBusy(false); if (input.current) input.current.value = '';
|
||||
setReading(null); actionLock.current = false; setBusy(false); if (input.current) input.current.value = '';
|
||||
};
|
||||
const changePreview = async (nextSheet: string, nextHeader = headerRow, nextStage = stage, preferredMap?: Record<string, string>) => {
|
||||
if (!workbook) return; setBusy(true); setError('');
|
||||
if (!workbook || actionLock.current) return; actionLock.current = true; setBusy(true); setError('');
|
||||
try {
|
||||
const result = await api.sourceWorkbookPreview(workbook.uploadId, { sheetName: nextSheet, headerRow: nextHeader, stage: nextStage });
|
||||
setWorkbook(result); setSheetName(result.preview.sheetName); setHeaderRow(result.preview.headerRow);
|
||||
const previous = preferredMap || fieldMap;
|
||||
setFieldMap({ ...matchFields(options.fields[nextStage] || [], result.preview.headers), ...Object.fromEntries(Object.entries(previous).filter(([, header]) => result.preview.headers.includes(header))) });
|
||||
} catch (value) { reportError(value); } finally { setBusy(false); }
|
||||
} catch (value) { reportError(value); } finally { actionLock.current = false; setBusy(false); }
|
||||
};
|
||||
const importAndUpdate = async () => {
|
||||
if (!canImport || importBusy) return; setBusy(true); setError('');
|
||||
if (!canImport || importBusy || actionLock.current) return; actionLock.current = true; setBusy(true); setError('');
|
||||
try {
|
||||
const sourceIds: string[] = [];
|
||||
for (const draft of drafts) {
|
||||
@@ -128,12 +134,14 @@ function SimplifiedDataWorkflow({ options, workflowStatus, pendingDeletion, onDe
|
||||
consumed.current.add(uploadId); configured.current.set(draft.id, { signature, sourceId: result.source.id }); sourceIds.push(result.source.id);
|
||||
}
|
||||
await uploadOperation.start(() => api.importDataWorkflow({ sourceIds }));
|
||||
} catch (value) { reportError(value); } finally { setBusy(false); }
|
||||
} catch (value) { reportError(value); } finally { actionLock.current = false; setBusy(false); }
|
||||
};
|
||||
const recalculate = async () => {
|
||||
if (actionLock.current) return; actionLock.current = true;
|
||||
setError('');
|
||||
try { await recalcOperation.start(() => pendingDeletion.ids.length ? api.deleteDataWorkflowSources({ sourceIds: pendingDeletion.ids, expectedCurrentReleaseId: pendingDeletion.releaseId }) : api.recalculateDataWorkflow()); }
|
||||
catch (value) { reportError(value); }
|
||||
finally { actionLock.current = false; }
|
||||
};
|
||||
return <div className="nc-simplified-intake">
|
||||
<section className="panel nc-simple-upload-panel">
|
||||
@@ -183,33 +191,46 @@ function ValidationNotice({ value }: { value: unknown }) {
|
||||
|
||||
export function DataWorkflowHub({ user, sources, currentReleaseId, pendingDeletion, onDeleted, onBusyChange, onUnauthorized, onRefresh }: { user: AuthUser; sources: SourceItem[]; currentReleaseId: string | null; pendingDeletion: PendingSourceDeletion; onDeleted: (ids: string[]) => void; onBusyChange: (busy: boolean) => void; onUnauthorized: (error: unknown) => boolean; onRefresh: () => void }) {
|
||||
const { message } = App.useApp();
|
||||
const { active } = usePageCache();
|
||||
const [mode, setMode] = useState<'ADD' | 'REPLACE' | 'REBUILD' | null>(null);
|
||||
const [options, setOptions] = useState<SourceUploadOptions | null>(null);
|
||||
const [workflowStatus, setWorkflowStatus] = useState<DataWorkflowStatus | null>(null);
|
||||
const [workflowStatusLoaded, setWorkflowStatusLoaded] = useState(false);
|
||||
const [workflowStatusError, setWorkflowStatusError] = useState('');
|
||||
const statusRead = useDelayedBusy();
|
||||
const optionsRead = useDelayedBusy();
|
||||
const candidatesRead = useDelayedBusy();
|
||||
const [optionError, setOptionError] = useState('');
|
||||
const [candidateError, setCandidateError] = useState('');
|
||||
const [candidates, setCandidates] = useState<Row[]>([]);
|
||||
const [candidatesLoaded, setCandidatesLoaded] = useState(false);
|
||||
const optionsAttempted = useRef(false);
|
||||
const candidatesAttempted = useRef(false);
|
||||
const [resumeId, setResumeId] = useState('');
|
||||
const canMaintain = rolesAllow(user, ['SYSTEM_ADMIN', 'DATA_MAINTAINER']);
|
||||
const canPublish = rolesAllow(user, ['SYSTEM_ADMIN', 'DATA_PUBLISHER']);
|
||||
const loadOptions = async () => {
|
||||
const loadOptions = useCallback(() => optionsRead.run(async () => {
|
||||
try { setOptions(await api.sourceUploadOptions()); setOptionError(''); }
|
||||
catch (error) { if (!onUnauthorized(error)) setOptionError(failure(error)); }
|
||||
};
|
||||
const loadWorkflowStatus = async () => {
|
||||
try { setWorkflowStatus(await api.dataWorkflowStatus()); }
|
||||
catch (error) { if (!onUnauthorized(error)) setWorkflowStatus(null); }
|
||||
finally { setWorkflowStatusLoaded(true); }
|
||||
};
|
||||
const loadCandidates = async () => {
|
||||
try { const result = await api.releases(); setCandidates(collectionItems(result).filter(row => String(row.status).toUpperCase() === 'CANDIDATE')); }
|
||||
catch (error) { if (!onUnauthorized(error)) setOptionError(failure(error)); }
|
||||
};
|
||||
useEffect(() => { void loadOptions(); void loadCandidates(); void loadWorkflowStatus(); }, [currentReleaseId, sources]);
|
||||
}), [onUnauthorized, optionsRead.run]);
|
||||
const loadWorkflowStatus = useCallback(() => statusRead.run(async () => {
|
||||
try { setWorkflowStatus(await api.dataWorkflowStatus()); setWorkflowStatusLoaded(true); setWorkflowStatusError(''); }
|
||||
catch (error) { if (!onUnauthorized(error)) setWorkflowStatusError(failure(error)); }
|
||||
}), [onUnauthorized, statusRead.run]);
|
||||
const loadCandidates = useCallback(() => candidatesRead.run(async () => {
|
||||
try { const result = await api.releases(); setCandidates(collectionItems(result).filter(row => String(row.status).toUpperCase() === 'CANDIDATE')); setCandidatesLoaded(true); setCandidateError(''); }
|
||||
catch (error) { if (!onUnauthorized(error)) setCandidateError(failure(error)); }
|
||||
}), [candidatesRead.run, onUnauthorized]);
|
||||
useEffect(() => {
|
||||
if (!active) return;
|
||||
if (!options && !optionsAttempted.current) { optionsAttempted.current = true; void loadOptions(); }
|
||||
if (!candidatesLoaded && !candidatesAttempted.current) { candidatesAttempted.current = true; void loadCandidates(); }
|
||||
if (!workflowStatusLoaded && !workflowStatusError) void loadWorkflowStatus();
|
||||
}, [active, currentReleaseId, sources, options, candidatesLoaded, workflowStatusLoaded, workflowStatusError, loadOptions, loadCandidates, loadWorkflowStatus]);
|
||||
useEffect(() => { const candidate = new URLSearchParams(window.location.search).get('candidateReleaseId'); if (candidate) setResumeId(candidate); }, []);
|
||||
const opened = mode !== null || Boolean(resumeId);
|
||||
const open = (next: 'ADD' | 'REPLACE' | 'REBUILD') => { setMode(next); setResumeId(''); void loadOptions(); };
|
||||
if (!workflowStatusLoaded) return <section className="panel nc-operation-status"><div><strong>读取当前维护模式</strong><span>正在加载可执行操作</span></div><Spin /></section>;
|
||||
const open = (next: 'ADD' | 'REPLACE' | 'REBUILD') => { setMode(next); setResumeId(''); if (!options) { optionsAttempted.current = true; void loadOptions(); } };
|
||||
if (!workflowStatusLoaded) return <section className="panel nc-operation-status">{statusRead.busy ? <div><strong>读取当前维护模式</strong><span>正在加载可执行操作</span><Spin /></div> : workflowStatusError ? <Alert showIcon type="error" message="维护模式读取失败" description={workflowStatusError} action={<Button size="small" onClick={() => void loadWorkflowStatus()}>重试</Button>} /> : null}</section>;
|
||||
if (workflowStatus?.simplified === true && workflowStatus.mode === 'TEST' && options) return <SimplifiedDataWorkflow options={options} workflowStatus={workflowStatus} pendingDeletion={pendingDeletion} onDeleted={onDeleted} onBusyChange={onBusyChange} onUnauthorized={onUnauthorized} onRefresh={onRefresh} />;
|
||||
return <>
|
||||
<section className="nc-intake-start panel">
|
||||
@@ -217,39 +238,54 @@ export function DataWorkflowHub({ user, sources, currentReleaseId, pendingDeleti
|
||||
<div className="nc-primary-actions"><Button type="primary" size="large" icon={<UploadOutlined />} disabled={!canMaintain || !options} onClick={() => open('ADD')}>上传新数据</Button><Button size="large" icon={<SwapOutlined />} disabled={!canMaintain || !options || !options.targets.length} onClick={() => open('REPLACE')}>替换已有数据</Button></div>
|
||||
<div className="nc-intake-links"><Button type="link" disabled={!canMaintain || !options?.targets.length} onClick={() => open('REBUILD')}>按当前来源重新计算</Button><span>上传 → 选择年月 → 匹配列 → 校验 → 发布</span></div>
|
||||
</section>
|
||||
{optionError && <Alert type="error" showIcon message="数据操作信息读取失败" description={optionError} action={<Button size="small" onClick={() => { void loadOptions(); void loadCandidates(); }}>重试</Button>} />}
|
||||
{optionError && <Alert type="error" message="上传选项读取失败" showIcon description={options ? `${optionError};已成功读取的选项仍保留。` : optionError} action={<Button size="small" onClick={() => { optionsAttempted.current = true; void loadOptions(); }}>重试</Button>} />}
|
||||
{candidateError && <Alert type="error" message="候选数据读取失败" showIcon description={candidatesLoaded ? `${candidateError};上次成功读取的候选仍保留。` : candidateError} action={<Button size="small" onClick={() => { candidatesAttempted.current = true; void loadCandidates(); }}>重试</Button>} />}
|
||||
{!options && optionsRead.busy && <div className="completion-loading"><Spin />读取上传选项…</div>}
|
||||
{!candidatesLoaded && candidatesRead.busy && <div className="completion-loading"><Spin />读取候选数据…</div>}
|
||||
{!canMaintain && <Alert showIcon type="info" message={canPublish ? '当前账号可以核对和发布已有候选数据' : '上传和替换需要数据维护权限'} description="已授权的操作会按账号权限显示。" />}
|
||||
{candidates.length > 0 && <section className="nc-pending-strip panel"><div><strong>待完成的数据</strong><span>已保存的候选可继续校验、对账和发布。</span></div><Select {...readableSelectPopup} aria-label="选择待完成候选数据" placeholder="选择候选数据" value={resumeId || undefined} options={candidates.map(row => ({ value: String(row.id), label: `${txt(row.name || row.id)}${row.complete === false ? ' · 校验未通过' : ''}` }))} onChange={value => { setMode(null); setResumeId(value); }} /></section>}
|
||||
{candidatesLoaded && candidates.length > 0 && <section className="nc-pending-strip panel"><div><strong>待完成的数据</strong><span>已保存的候选可继续校验、对账和发布。</span></div><Select {...readableSelectPopup} aria-label="选择待完成候选数据" placeholder="选择候选数据" value={resumeId || undefined} options={candidates.map(row => ({ value: String(row.id), label: `${txt(row.name || row.id)}${row.complete === false ? ' · 校验未通过' : ''}` }))} onChange={value => { setMode(null); setResumeId(value); }} /></section>}
|
||||
{opened && options && <DataUploadWizard key={`${mode}:${resumeId}`} user={user} mode={mode || 'ADD'} options={options} sources={sources} resumeId={resumeId} onUnauthorized={onUnauthorized} onClose={() => { setMode(null); setResumeId(''); }} onComplete={() => { onRefresh(); void loadOptions(); void loadCandidates(); message.success('操作结果已刷新'); }} />}
|
||||
</>;
|
||||
}
|
||||
|
||||
export function SourceFilesPanel({ user, sources, loading, pendingIds, maintenanceBusy, onToggleDelete, onClearDeletes, onUnauthorized, onRefresh }: { user: AuthUser; sources: SourceItem[]; loading: boolean; pendingIds: string[]; maintenanceBusy: boolean; onToggleDelete: (id: string) => void; onClearDeletes: () => void; onUnauthorized: (error: unknown) => boolean; onRefresh: () => void }) {
|
||||
export function SourceFilesPanel({ user, sources, sourcesLoaded, loading, pendingIds, maintenanceBusy, onToggleDelete, onClearDeletes, onUnauthorized, onRefresh }: { user: AuthUser; sources: SourceItem[]; sourcesLoaded: boolean; loading: boolean; pendingIds: string[]; maintenanceBusy: boolean; onToggleDelete: (id: string) => void; onClearDeletes: () => void; onUnauthorized: (error: unknown) => boolean; onRefresh: () => void }) {
|
||||
const { message } = App.useApp();
|
||||
const { active } = usePageCache();
|
||||
const [showDeleted, setShowDeleted] = useState(false);
|
||||
const [deleted, setDeleted] = useState<SourceDeletionPreview[]>([]);
|
||||
const [deletedLoaded, setDeletedLoaded] = useState(false);
|
||||
const deletedRead = useDelayedBusy();
|
||||
const [metadataError, setMetadataError] = useState('');
|
||||
const metadataAttempted = useRef(false);
|
||||
const [workflowStatus, setWorkflowStatus] = useState<DataWorkflowStatus | null>(null);
|
||||
const [currentSourceIds, setCurrentSourceIds] = useState<string[] | null>(null);
|
||||
const [deletedLoading, setDeletedLoading] = useState(false);
|
||||
const [deletedError, setDeletedError] = useState('');
|
||||
const [workflowStatusLoaded, setWorkflowStatusLoaded] = useState(false);
|
||||
const [selected, setSelected] = useState<{ id: string; restore: boolean } | null>(() => { const id = new URLSearchParams(window.location.search).get('sourceDeleteId'); return id ? { id, restore: false } : null; });
|
||||
const canOperate = rolesAllow(user, ['SYSTEM_ADMIN', 'DATA_MAINTAINER', 'DATA_PUBLISHER']);
|
||||
const loadDeleted = async () => {
|
||||
setDeletedLoading(true);
|
||||
try { const result = await api.deletedSources(); setDeleted(result.items); setDeletedError(''); }
|
||||
const loadDeleted = useCallback(() => deletedRead.run(async () => {
|
||||
try { const result = await api.deletedSources(); setDeleted(result.items); setDeletedLoaded(true); setDeletedError(''); }
|
||||
catch (value) { if (!onUnauthorized(value)) setDeletedError(failure(value)); }
|
||||
finally { setDeletedLoading(false); }
|
||||
};
|
||||
}), [deletedRead.run, onUnauthorized]);
|
||||
const sourceOperation = useDataWorkflowOperation('source-maintenance', value => {
|
||||
onRefresh(); if (showDeleted) void loadDeleted();
|
||||
message.success(String(value.operationType || '').toUpperCase().includes('RESTORE') ? '来源已恢复,报表已更新' : '来源已删除,报表已更新');
|
||||
});
|
||||
const loadMetadata = useCallback(async () => {
|
||||
const [status, options] = await Promise.allSettled([api.dataWorkflowStatus(), api.sourceUploadOptions()]);
|
||||
const errors: string[] = [];
|
||||
if (status.status === 'fulfilled') { setWorkflowStatus(status.value); setWorkflowStatusLoaded(true); }
|
||||
else if (!onUnauthorized(status.reason)) errors.push(`维护状态:${failure(status.reason)}`);
|
||||
if (options.status === 'fulfilled') setCurrentSourceIds(options.value.currentSourceIds || []);
|
||||
else if (!onUnauthorized(options.reason)) errors.push(`来源范围:${failure(options.reason)}`);
|
||||
setMetadataError(errors.join(';'));
|
||||
}, [onUnauthorized]);
|
||||
useEffect(() => {
|
||||
void api.dataWorkflowStatus().then(setWorkflowStatus).catch(() => setWorkflowStatus(null)).finally(() => setWorkflowStatusLoaded(true));
|
||||
void api.sourceUploadOptions().then(options => setCurrentSourceIds(options.currentSourceIds || [])).catch(() => setCurrentSourceIds(null));
|
||||
}, [sources]);
|
||||
useEffect(() => { if (showDeleted && canOperate) void loadDeleted(); }, [showDeleted, sources]);
|
||||
if (!active || metadataAttempted.current) return;
|
||||
metadataAttempted.current = true;
|
||||
void loadMetadata();
|
||||
}, [active, sources, loadMetadata]);
|
||||
useEffect(() => { if (active && showDeleted && canOperate && !deletedLoaded) void loadDeleted(); }, [active, showDeleted, canOperate, deletedLoaded, loadDeleted, sources]);
|
||||
const period = (source: DeletionSource) => source.year && source.month ? `${source.year}年${String(source.month).padStart(2, '0')}月` : '尚未确认';
|
||||
const close = () => { setSelected(null); const url = new URL(window.location.href); if (url.searchParams.has('sourceDeleteId')) { url.searchParams.delete('sourceDeleteId'); window.history.replaceState({}, '', `${url.pathname}${url.search}${url.hash}`); } };
|
||||
const simplified = workflowStatus?.simplified === true && workflowStatus.mode === 'TEST';
|
||||
@@ -262,9 +298,10 @@ export function SourceFilesPanel({ user, sources, loading, pendingIds, maintenan
|
||||
<div className="resource-toolbar"><strong>{showDeleted ? '已删除的来源文件' : '已接收的来源文件'}</strong><span>{showDeleted ? `${deleted.length} 个文件 · 原件和处理记录保留` : simplified ? `${sources.length} 个文件${pendingIds.length ? ` · ${pendingIds.length} 个待删除` : ''}` : `${sources.length} 个文件 · 上传或接收不等于已经发布`}</span>{canOperate && <Checkbox checked={showDeleted} onChange={event => setShowDeleted(event.target.checked)}>查看已删除来源</Checkbox>}</div>
|
||||
{simplified && <p className="nc-source-maintenance-note">删除先标记为待删除,可连续操作和撤销,点击上方“更新报表”后统一生效。原文件和处理记录保留。</p>}
|
||||
{simplified && pendingIds.length > 0 && <div className="nc-source-maintenance-note"><Button disabled={maintenanceBusy} onClick={onClearDeletes}>撤销全部待删除({pendingIds.length})</Button></div>}
|
||||
{deletedError && <Alert showIcon type="error" message="已删除来源读取失败" description={deletedError} action={<Button size="small" onClick={() => void loadDeleted()}>重试</Button>} />}
|
||||
{deletedError && <Alert showIcon type="error" message="已删除来源读取失败" description={deletedLoaded ? `${deletedError};上次成功读取的来源仍保留。` : deletedError} action={<Button size="small" onClick={() => void loadDeleted()}>重试</Button>} />}
|
||||
{metadataError && <Alert showIcon type="error" message="来源操作信息读取失败" description={workflowStatusLoaded || currentSourceIds !== null ? `${metadataError};已成功读取的状态仍保留。` : metadataError} action={<Button size="small" onClick={() => { metadataAttempted.current = true; setMetadataError(''); void loadMetadata(); }}>重试</Button>} />}
|
||||
{sourceOperation.operation && <WorkflowOperationFeedback operation={sourceOperation.operation} error={sourceOperation.error} busy={sourceOperation.busy} onResume={sourceOperation.resume} />}
|
||||
<Table<DeletionSource> size="small" bordered loading={showDeleted ? deletedLoading : loading} dataSource={showDeleted ? deleted.map(item => item.source) : sources} rowKey="id" pagination={{ pageSize: 15, showSizeChanger: false }} scroll={{ x: 980 }} columns={[
|
||||
{(!showDeleted && sourcesLoaded) || (showDeleted && (deletedLoaded || deletedRead.busy)) ? <Table<DeletionSource> size="small" bordered loading={showDeleted ? deletedRead.busy : loading} dataSource={showDeleted ? deleted.map(item => item.source) : sources} rowKey="id" pagination={{ pageSize: 15, showSizeChanger: false }} scroll={{ x: 980 }} columns={[
|
||||
{ title: '来源文件', dataIndex: 'sourceFile', key: 'sourceFile', width: 340, ellipsis: true },
|
||||
{ title: '阶段', dataIndex: 'stage', key: 'stage', align: 'center', width: 90, render: value => <Tag>{stageName(value)}</Tag> },
|
||||
{ title: '统计期间', key: 'period', align: 'center', width: 140, render: (_, row) => period(row) },
|
||||
@@ -276,22 +313,24 @@ export function SourceFilesPanel({ user, sources, loading, pendingIds, maintenan
|
||||
if (!workflowStatusLoaded || !canOperate || !permitted) return null;
|
||||
return <Button type="link" danger={!showDeleted} icon={showDeleted ? <UndoOutlined /> : <DeleteOutlined />} disabled={sourceOperation.busy || maintenanceBusy || loading} onClick={() => simplified ? showDeleted ? void runSourceOperation(row.id, true) : onToggleDelete(row.id) : setSelected({ id: row.id, restore: showDeleted })}>{simplified ? showDeleted ? '恢复并更新报表' : pendingIds.includes(row.id) ? '撤销删除' : '删除' : showDeleted ? '恢复' : '删除'}</Button>;
|
||||
} },
|
||||
]} locale={{ emptyText: showDeleted ? '没有已删除的来源。' : '尚无来源文件,点击“上传新数据”开始。' }} />
|
||||
]} locale={{ emptyText: showDeleted ? '没有已删除的来源。' : '尚无来源文件,点击“上传新数据”开始。' }} /> : null}
|
||||
</section>
|
||||
{selected && !simplified && <SourceDeletionDialog key={`${selected.id}:${selected.restore}`} user={user} sourceId={selected.id} restoring={selected.restore} sources={sources} onUnauthorized={onUnauthorized} onClose={close} onRefresh={() => { onRefresh(); if (showDeleted) void loadDeleted(); }} />}
|
||||
</>;
|
||||
}
|
||||
|
||||
function SourceDeletionDialog({ user, sourceId, restoring, sources, onUnauthorized, onClose, onRefresh }: { user: AuthUser; sourceId: string; restoring: boolean; sources: SourceItem[]; onUnauthorized: (error: unknown) => boolean; onClose: () => void; onRefresh: () => void }) {
|
||||
const { message } = App.useApp();
|
||||
const { message } = App.useApp(); const { active } = usePageCache();
|
||||
const [preview, setPreview] = useState<SourceDeletionPreview | null>(null);
|
||||
const [busy, setBusy] = useState(true); const [error, setError] = useState(''); const [notice, setNotice] = useState('');
|
||||
const [reason, setReason] = useState(''); const [confirmed, setConfirmed] = useState(false); const [finished, setFinished] = useState(false);
|
||||
const [candidateId, setCandidateId] = useState(''); const [options, setOptions] = useState<SourceUploadOptions | null>(null);
|
||||
const requestKey = useRef(crypto.randomUUID()); const buildKey = useRef(crypto.randomUUID());
|
||||
const reportError = (value: unknown) => { if (!onUnauthorized(value)) setError(failure(value)); };
|
||||
const load = async () => { setBusy(true); try { const result = await api.sourceDeletionPreview(sourceId); setPreview(result); setError(''); if (restoring && !result.hidden) { setFinished(true); setNotice('此来源已在日常清单中,无需重复恢复。'); } } catch (value) { reportError(value); } finally { setBusy(false); } };
|
||||
useEffect(() => { void load(); }, [sourceId]);
|
||||
const actionLock = useRef(false); const candidateLock = useRef(false);
|
||||
const showBusy = useDelayedIndicator(busy, 150);
|
||||
const reportError = useCallback((value: unknown) => { if (!onUnauthorized(value)) setError(failure(value)); }, [onUnauthorized]);
|
||||
const load = useCallback(async () => { if (!active || actionLock.current) return; setBusy(true); try { const result = await api.sourceDeletionPreview(sourceId); setPreview(result); setError(''); if (restoring && !result.hidden) { setFinished(true); setNotice('此来源已在日常清单中,无需重复恢复。'); } } catch (value) { reportError(value); } finally { setBusy(false); } }, [active, reportError, restoring, sourceId]);
|
||||
useEffect(() => { if (active) void load(); }, [active, load]);
|
||||
const request = preview?.changeRequest; const requestStatus = String(request?.status || '');
|
||||
const isRequested = preview?.nextAction === 'REVIEW_WITHDRAWAL'; const isApproved = preview?.nextAction === 'BUILD_WITHDRAWAL_CANDIDATE'; const isBuilt = preview?.nextAction === 'RECONCILE_CANDIDATE';
|
||||
const withdrawing = preview?.mode === 'WITHDRAW_CURRENT' || isRequested || isApproved || isBuilt;
|
||||
@@ -303,7 +342,7 @@ function SourceDeletionDialog({ user, sourceId, restoring, sources, onUnauthoriz
|
||||
const actualRestore = Boolean((restoring || preview?.hidden) && !finished);
|
||||
const reasonLabel = actualRestore ? '恢复理由' : isRequested ? '审批说明' : '删除理由';
|
||||
const act = async (kind: 'delete' | 'restore' | 'approve' | 'reject' | 'build') => {
|
||||
if (!preview) return; setBusy(true); setError('');
|
||||
if (!active || !preview || actionLock.current) return; actionLock.current = true; setBusy(true); setError('');
|
||||
try {
|
||||
if (kind === 'delete') {
|
||||
const result = await api.deleteSource(sourceId, { expectedCurrentReleaseId: preview.currentReleaseId, expectedDeleteVersion: preview.deleteVersion, ...(preview.currentUsage ? { expectedRevisionId: preview.currentUsage.revisionId } : {}), reason: reason.trim(), idempotencyKey: requestKey.current });
|
||||
@@ -325,12 +364,12 @@ function SourceDeletionDialog({ user, sourceId, restoring, sources, onUnauthoriz
|
||||
}
|
||||
setReason(''); setConfirmed(false); onRefresh();
|
||||
} catch (value) { reportError(value); }
|
||||
finally { setBusy(false); }
|
||||
finally { actionLock.current = false; setBusy(false); }
|
||||
};
|
||||
const openCandidate = async (releaseId: string) => {
|
||||
setBusy(true); setError('');
|
||||
if (!active || candidateLock.current) return; candidateLock.current = true; setBusy(true); setError('');
|
||||
try { const support = await api.sourceUploadOptions(); setOptions(support); setCandidateId(releaseId); }
|
||||
catch (value) { reportError(value); } finally { setBusy(false); }
|
||||
catch (value) { reportError(value); } finally { candidateLock.current = false; setBusy(false); }
|
||||
};
|
||||
const handoff = async () => {
|
||||
const url = new URL(window.location.href); url.searchParams.set('page', 'sources'); url.searchParams.set('sourceDeleteId', sourceId); url.searchParams.delete('candidateReleaseId');
|
||||
@@ -343,9 +382,9 @@ function SourceDeletionDialog({ user, sourceId, restoring, sources, onUnauthoriz
|
||||
<Button icon={<ReloadOutlined />} disabled={busy} onClick={() => void load()}>刷新状态</Button>
|
||||
{actualRestore ? <Button type="primary" loading={busy} disabled={!canRestore || !confirmed || !reason.trim()} onClick={() => void act('restore')}>确认恢复来源</Button> : isRequested ? <>{canReview && <><Button danger disabled={busy || !reason.trim()} onClick={() => void act('reject')}>驳回申请</Button><Button type="primary" loading={busy} disabled={!confirmed || !reason.trim()} onClick={() => void act('approve')}>批准删除申请</Button></>}</> : isApproved ? <Button type="primary" loading={busy} disabled={!canBuild || !confirmed} onClick={() => void act('build')}>生成删除候选</Button> : isBuilt ? <Button type="primary" loading={busy} disabled={!request?.resultReleaseId} onClick={() => { if (request?.resultReleaseId) void openCandidate(request.resultReleaseId); }}>核对并发布删除候选</Button> : <Button type="primary" danger loading={busy} disabled={!canStart || !confirmed || !reason.trim()} onClick={() => void act('delete')}>{withdrawing ? '提交删除申请' : '确认删除来源'}</Button>}
|
||||
</>}</div></div>}>
|
||||
{error && <Alert type="error" showIcon message="操作未完成" description={error} />}
|
||||
{error && <Alert type="error" showIcon message="操作未完成" description={preview ? `${error};已成功读取的来源信息仍保留。` : error} action={!preview ? <Button size="small" onClick={() => void load()}>重试</Button> : undefined} />}
|
||||
{notice && <Alert type={finished ? 'success' : 'info'} showIcon message={notice} />}
|
||||
<Spin spinning={busy}>{preview ? <>
|
||||
<Spin spinning={showBusy}>{preview ? <>
|
||||
<div className="nc-file-summary"><FileExcelOutlined /><strong>{preview.source.sourceFile}</strong><span>{preview.source.year && preview.source.month ? `${preview.source.year}年${preview.source.month}月` : '期间待确认'} · {stageName(preview.source.stage)}</span></div>
|
||||
{withdrawing && !actualRestore && <Steps className="nc-delete-steps" current={deletionStep} size="small" items={[{ title: '确认影响' }, { title: '审批申请' }, { title: '生成候选' }, { title: '对账与发布' }, { title: '移入已删除' }]} />}
|
||||
<div className="nc-review-facts nc-deletion-impact"><div><small>当前正式数据</small><strong>{preview.currentUsage ? '正在使用此来源' : '未使用此来源'}</strong></div><div><small>归档来源记录</small><strong>{preview.history.revisionCount} 个</strong></div><div><small>正式处理记录</small><strong>{preview.history.publishedReleaseCount} 个</strong></div><div><small>候选处理记录</small><strong>{preview.history.candidateReleaseCount} 个</strong></div></div>
|
||||
@@ -358,97 +397,145 @@ function SourceDeletionDialog({ user, sourceId, restoring, sources, onUnauthoriz
|
||||
</>}
|
||||
{waitingForColleague && !awaitingTask && <Alert type="info" showIcon message={isRequested ? '等待有审批权限的发布者继续' : isApproved ? '等待有权限的发布者生成候选' : actualRestore ? '此账号没有恢复权限' : '此账号没有本次删除操作权限'} description={<>{preview.blockedReason && <p>{preview.blockedReason}</p>}<span>可复制当前处理链接交接;对方打开后会看到相同来源、申请和下一步。</span><Button type="link" onClick={() => void handoff()}>复制处理链接</Button></>} />}
|
||||
{!finished && isBuilt && <Alert type="info" showIcon message="删除候选已保存,等待核对与发布" description="点击“核对并发布删除候选”继续查看差异;没有发布权限的账号可在候选窗口复制交接链接。" />}
|
||||
</> : !busy ? <Empty description="未读取到来源信息" /> : <div className="loading-panel">正在核对来源及影响…</div>}</Spin>
|
||||
</> : showBusy ? <div className="loading-panel">正在核对来源及影响…</div> : null}</Spin>
|
||||
</Modal>
|
||||
{candidateId && options && <DataUploadWizard key={`deletion:${candidateId}`} user={user} mode="ADD" purpose="WITHDRAW" handoffSourceId={sourceId} initialReason={request?.reason} options={options} sources={sources} resumeId={candidateId} onUnauthorized={onUnauthorized} onClose={() => { setCandidateId(''); void load(); }} onComplete={() => { setFinished(true); setNotice('删除候选已发布,该来源已从当前结果移除;原件和处理记录保留。'); onRefresh(); void load(); }} />}
|
||||
</>;
|
||||
}
|
||||
|
||||
function DataUploadWizard({ user, mode, purpose, handoffSourceId, initialReason, options, sources, resumeId, onUnauthorized, onClose, onComplete }: { user: AuthUser; mode: 'ADD' | 'REPLACE' | 'REBUILD'; purpose?: 'WITHDRAW'; handoffSourceId?: string; initialReason?: string; options: SourceUploadOptions; sources: SourceItem[]; resumeId: string; onUnauthorized: (error: unknown) => boolean; onClose: () => void; onComplete: () => void }) {
|
||||
const { message } = App.useApp(); const input = useRef<HTMLInputElement>(null); const generation = useRef(0); const importKey = useRef(crypto.randomUUID()); const publishKey = useRef(crypto.randomUUID());
|
||||
const [pollAttempt, setPollAttempt] = useState(0);
|
||||
const [step, setStep] = useState(resumeId ? 4 : 0); const [busy, setBusy] = useState(false); const [error, setError] = useState('');
|
||||
const { message } = App.useApp(); const { active } = usePageCache(); const activeRef = useRef(active); activeRef.current = active; const input = useRef<HTMLInputElement>(null); const generation = useRef(0); const importKey = useRef(crypto.randomUUID()); const publishKey = useRef(crypto.randomUUID());
|
||||
const runStorageKey = `quality-import-run:${user.id}`;
|
||||
const [storedRunId] = useState(() => { try { return localStorage.getItem(runStorageKey) || ''; } catch { return ''; } });
|
||||
const [step, setStep] = useState(resumeId ? 4 : storedRunId ? 3 : 0); const [busy, setBusy] = useState(Boolean(storedRunId)); const [error, setError] = useState('');
|
||||
const [workbook, setWorkbook] = useState<WorkbookPreview | null>(null); const [stage, setStage] = useState<DataStage>('black');
|
||||
const [year, setYear] = useState(new Date().getFullYear()); const [month, setMonth] = useState(new Date().getMonth() + 1);
|
||||
const [scopeCode, setScopeCode] = useState(options.scopes[0] || 'ALL'); const [targetId, setTargetId] = useState('');
|
||||
const [sheetName, setSheetName] = useState(''); const [headerRow, setHeaderRow] = useState(1); const [fieldMap, setFieldMap] = useState<Record<string, string>>({});
|
||||
const [configuredSourceId, setConfiguredSourceId] = useState('');
|
||||
const [reason, setReason] = useState(initialReason || ''); const [run, setRun] = useState<Row | null>(null); const [release, setRelease] = useState<Row | null>(null);
|
||||
const [reason, setReason] = useState(initialReason || ''); const [run, setRun] = useState<Row | null>(() => storedRunId ? { id: storedRunId, status: 'RUNNING' } : null); const [release, setRelease] = useState<Row | null>(null);
|
||||
const [runTerminalId, setRunTerminalId] = useState('');
|
||||
const completionNotified = useRef(new Set<string>());
|
||||
const actionLock = useRef(false); const pollLock = useRef(false); const pollAgainAfterCurrent = useRef(false); const candidateReadLock = useRef(false);
|
||||
const runIdRef = useRef('');
|
||||
const [reconciliation, setReconciliation] = useState<Row | null>(null); const [issues, setIssues] = useState<Row[]>([]);
|
||||
const [differenceReason, setDifferenceReason] = useState(''); const [confirmDifferences, setConfirmDifferences] = useState(false); const [publishConfirmed, setPublishConfirmed] = useState(false); const [published, setPublished] = useState(false);
|
||||
const target = options.targets.find(item => item.documentId === targetId); const fields = options.fields[stage] || [];
|
||||
const headers = workbook?.preview.headers || []; const missingFields = fields.filter(field => field.required && !fieldMap[field.name]); const duplicateColumns = Object.values(fieldMap).length !== new Set(Object.values(fieldMap)).size;
|
||||
const canPublish = rolesAllow(user, ['SYSTEM_ADMIN', 'DATA_PUBLISHER']);
|
||||
const reportError = (value: unknown) => { if (!onUnauthorized(value)) setError(failure(value)); };
|
||||
const loadCandidate = async (id: string) => {
|
||||
const inspected = await api.governanceReleaseInspect(id); setRelease(asRow(inspected.release));
|
||||
const result = await api.governanceReleaseReconciliations(id); const list = collectionItems(result); const selected = list.find(item => String(item.id) === String(result.acceptanceId)) || list[0];
|
||||
setReconciliation(selected?.id ? await api.governanceReconciliation(String(selected.id)) : null);
|
||||
const reportError = useCallback((value: unknown) => { if (!onUnauthorized(value)) setError(failure(value)); }, [onUnauthorized]);
|
||||
const loadCandidate = async (id: string, isCurrent: () => boolean = () => activeRef.current) => {
|
||||
if (!activeRef.current || !isCurrent()) return false;
|
||||
const inspected = await api.governanceReleaseInspect(id);
|
||||
if (!activeRef.current || !isCurrent()) return false;
|
||||
setRelease(asRow(inspected.release));
|
||||
const result = await api.governanceReleaseReconciliations(id);
|
||||
if (!activeRef.current || !isCurrent()) return false;
|
||||
const list = collectionItems(result); const selected = list.find(item => String(item.id) === String(result.acceptanceId)) || list[0];
|
||||
const reconciliation = selected?.id ? await api.governanceReconciliation(String(selected.id)) : null;
|
||||
if (!activeRef.current || !isCurrent()) return false;
|
||||
setReconciliation(reconciliation);
|
||||
return true;
|
||||
};
|
||||
useEffect(() => { if (resumeId) { setBusy(true); loadCandidate(resumeId).catch(reportError).finally(() => setBusy(false)); } return () => { generation.current++; }; }, []);
|
||||
const runId = String(run?.id || '');
|
||||
useEffect(() => {
|
||||
if (!runId) return;
|
||||
let alive = true; let timer: ReturnType<typeof setTimeout>;
|
||||
const poll = async () => {
|
||||
try {
|
||||
const result = await api.importRun(runId); if (!alive) return; setRun(result.run);
|
||||
if (String(result.run.status) === 'COMPLETED') {
|
||||
const id = String(result.run.resultReleaseId || ''); if (!id) throw new Error('校验已完成,但没有返回候选数据');
|
||||
await loadCandidate(id); if (!alive) return; setStep(4); setBusy(false); onComplete();
|
||||
if (asRow(result.run.validation).complete === false) { const issueList = await api.importIssues(runId); if (alive) setIssues(collectionItems(issueList)); }
|
||||
} else if (['FAILED', 'CANCELLED'].includes(String(result.run.status))) {
|
||||
setBusy(false); const issueList = await api.importIssues(runId); if (alive) setIssues(collectionItems(issueList));
|
||||
} else timer = setTimeout(poll, 1400);
|
||||
} catch (value) { if (alive) { reportError(value); setBusy(false); } }
|
||||
};
|
||||
timer = setTimeout(poll, 700); return () => { alive = false; clearTimeout(timer); };
|
||||
}, [runId, pollAttempt]);
|
||||
if (!active || !resumeId || candidateReadLock.current) return;
|
||||
candidateReadLock.current = true; setBusy(true);
|
||||
loadCandidate(resumeId).catch(reportError).finally(() => { candidateReadLock.current = false; setBusy(false); });
|
||||
return () => { generation.current++; };
|
||||
}, [active, reportError, resumeId]);
|
||||
const runId = String(run?.id || '');
|
||||
runIdRef.current = runId;
|
||||
const pollRun = useCallback(async () => {
|
||||
if (!activeRef.current || !runId) return;
|
||||
if (pollLock.current) { pollAgainAfterCurrent.current = true; return; }
|
||||
pollLock.current = true;
|
||||
try {
|
||||
const result = await api.importRun(runId);
|
||||
const isCurrent = () => activeRef.current && runIdRef.current === runId;
|
||||
if (!isCurrent()) return;
|
||||
setRun(result.run); setError('');
|
||||
const status = String(result.run.status || '').toUpperCase();
|
||||
if (status === 'COMPLETED') {
|
||||
const id = String(result.run.resultReleaseId || ''); if (!id) throw new Error('校验已完成,但没有返回候选数据');
|
||||
const candidateRead = await runImportPollFollowup(runId, () => isCurrent(), () => loadCandidate(id, isCurrent));
|
||||
if (!candidateRead.started || !candidateRead.current || !candidateRead.value || !isCurrent()) return;
|
||||
setStep(4);
|
||||
if (asRow(result.run.validation).complete === false) {
|
||||
const issueRead = await runImportPollFollowup(runId, () => isCurrent(), () => api.importIssues(runId));
|
||||
if (!issueRead.started || !issueRead.current) return;
|
||||
setIssues(collectionItems(issueRead.value));
|
||||
}
|
||||
if (!completionNotified.current.has(runId)) { completionNotified.current.add(runId); onComplete(); }
|
||||
setRunTerminalId(runId); setBusy(false);
|
||||
try { localStorage.removeItem(runStorageKey); } catch { /* The server task remains in task history. */ }
|
||||
} else if (['FAILED', 'CANCELLED'].includes(status)) {
|
||||
const issueRead = await runImportPollFollowup(runId, () => isCurrent(), () => api.importIssues(runId));
|
||||
if (!issueRead.started || !issueRead.current) return;
|
||||
setIssues(collectionItems(issueRead.value)); setRunTerminalId(runId); setBusy(false);
|
||||
try { localStorage.removeItem(runStorageKey); } catch { /* The server task remains in task history. */ }
|
||||
}
|
||||
} catch (value) { if (activeRef.current && runIdRef.current === runId) { reportError(value); setBusy(false); } }
|
||||
finally {
|
||||
pollLock.current = false;
|
||||
if (pollAgainAfterCurrent.current && activeRef.current && runIdRef.current === runId) {
|
||||
pollAgainAfterCurrent.current = false;
|
||||
void pollRun();
|
||||
}
|
||||
}
|
||||
}, [loadCandidate, onComplete, reportError, runId, runStorageKey]);
|
||||
useVisiblePolling(pollRun, 2000, active && Boolean(runId) && runTerminalId !== runId, true);
|
||||
const readFile = async (file?: File) => {
|
||||
if (!file) return; setBusy(true); setError(''); const ownGeneration = generation.current;
|
||||
if (!file || actionLock.current) return; actionLock.current = true; setBusy(true); setError(''); const ownGeneration = generation.current;
|
||||
try { const result = await api.previewSourceWorkbook(file); if (ownGeneration !== generation.current) return; setWorkbook(result); setSheetName(result.preview.sheetName); setHeaderRow(result.preview.headerRow); setFieldMap(matchFields(options.fields[stage] || [], result.preview.headers)); setStep(1); }
|
||||
catch (value) { reportError(value); } finally { setBusy(false); if (input.current) input.current.value = ''; }
|
||||
catch (value) { reportError(value); } finally { actionLock.current = false; setBusy(false); if (input.current) input.current.value = ''; }
|
||||
};
|
||||
const changePreview = async (nextSheet: string, nextHeader: number, nextStage = stage, preferredMap?: Record<string, string>) => {
|
||||
if (!workbook) return; setBusy(true); setError('');
|
||||
if (!workbook || actionLock.current) return; actionLock.current = true; setBusy(true); setError('');
|
||||
try { const result = await api.sourceWorkbookPreview(workbook.uploadId, { sheetName: nextSheet, headerRow: nextHeader, stage: nextStage }); setWorkbook(result); setSheetName(result.preview.sheetName); setHeaderRow(result.preview.headerRow); const chosen = preferredMap || fieldMap; setFieldMap({ ...matchFields(options.fields[nextStage] || [], result.preview.headers), ...Object.fromEntries(Object.entries(chosen).filter(([, header]) => result.preview.headers.includes(header))) }); }
|
||||
catch (value) { reportError(value); } finally { setBusy(false); }
|
||||
catch (value) { reportError(value); } finally { actionLock.current = false; setBusy(false); }
|
||||
};
|
||||
const chooseTarget = (id: string) => { const selected = options.targets.find(item => item.documentId === id); setTargetId(id); if (selected) { setStage(selected.stage); setYear(selected.year); setMonth(selected.month); setScopeCode(selected.scopeCode); setFieldMap(matchFields(options.fields[selected.stage] || [], headers)); } };
|
||||
const beginImport = async () => {
|
||||
if (!workbook || missingFields.length || (mode === 'REPLACE' && !target)) return;
|
||||
if (!active || !workbook || missingFields.length || (mode === 'REPLACE' && !target) || actionLock.current) return;
|
||||
actionLock.current = true;
|
||||
setBusy(true); setError('');
|
||||
try {
|
||||
const configured = configuredSourceId ? { source: { id: configuredSourceId } } : await api.configureSourceWorkbook({ uploadId: workbook.uploadId, stage, year, month, sheetName, headerRow, fieldMap, mode: mode === 'REPLACE' ? 'REPLACE' : 'ADD', expectedCurrentReleaseId: options.currentReleaseId, ...(target ? { targetDocumentId: target.documentId, targetRevisionId: target.revisionId } : {}), reason: reason.trim() || `新增${year}年${month}月${stageName(stage)}数据`, scopeCode });
|
||||
setConfiguredSourceId(configured.source.id);
|
||||
const created = asRow(await api.startImport({ sourceIds: [configured.source.id], expectedCurrentReleaseId: options.currentReleaseId, idempotencyKey: importKey.current })); const nextRun = asRow(created.run || created); setRun(nextRun);
|
||||
if (!nextRun.id) throw new Error('服务端未返回计算任务,已接收的来源可稍后重新校验');
|
||||
try { localStorage.setItem(runStorageKey, String(nextRun.id)); } catch { /* Server task history remains available if local storage is unavailable. */ }
|
||||
} catch (value) { reportError(value); setBusy(false); }
|
||||
finally { actionLock.current = false; }
|
||||
};
|
||||
const rebuild = async () => {
|
||||
if (!active || actionLock.current) return; actionLock.current = true;
|
||||
setBusy(true); setError(''); setStep(3);
|
||||
try {
|
||||
if (!options.currentReleaseId) throw new Error('当前没有可用于重新计算的来源');
|
||||
const inspected = await api.governanceReleaseInspect(options.currentReleaseId); const members = asRows(inspected.members);
|
||||
const ids = options.currentSourcesComplete && options.currentSourceIds?.length ? options.currentSourceIds : members.map(member => sources.find(source => source.sha256 === member.sha256 && source.stage === member.stage && source.year === Number(member.sourceYear) && source.month === Number(member.sourceMonth))?.id);
|
||||
if (!ids.length || ids.some(id => !id)) throw new Error('部分原始文件当前不可用于重算,请重新上传缺少的原始文件。');
|
||||
const created = asRow(await api.startImport({ sourceIds: ids as string[], expectedCurrentReleaseId: options.currentReleaseId, idempotencyKey: importKey.current })); setRun(asRow(created.run || created));
|
||||
const created = asRow(await api.startImport({ sourceIds: ids as string[], expectedCurrentReleaseId: options.currentReleaseId, idempotencyKey: importKey.current }));
|
||||
const nextRun = asRow(created.run || created); if (!nextRun.id) throw new Error('服务端未返回计算任务编号');
|
||||
setRun(nextRun); try { localStorage.setItem(runStorageKey, String(nextRun.id)); } catch { /* Server task history remains available if local storage is unavailable. */ }
|
||||
} catch (value) { reportError(value); setBusy(false); }
|
||||
finally { actionLock.current = false; }
|
||||
};
|
||||
const reconcile = async () => {
|
||||
if (!release?.id) return; setBusy(true); setError('');
|
||||
if (!active || !release?.id || actionLock.current) return; actionLock.current = true; setBusy(true); setError('');
|
||||
try { const created = await api.createGovernanceReconciliation(String(release.id), { ...(options.currentReleaseId ? { baselineReleaseId: options.currentReleaseId } : {}), dimensions: ['overall', 'department', 'group', 'product', 'projectGroup'] }); const detail = asRow(created.reconciliation || created); setReconciliation(detail.id ? await api.governanceReconciliation(String(detail.id)) : detail); setConfirmDifferences(false); }
|
||||
catch (value) { reportError(value); } finally { setBusy(false); }
|
||||
catch (value) { reportError(value); } finally { actionLock.current = false; setBusy(false); }
|
||||
};
|
||||
const confirm = async () => {
|
||||
if (!reconciliation?.id) return; setBusy(true); setError('');
|
||||
if (!active || !reconciliation?.id || actionLock.current) return; actionLock.current = true; setBusy(true); setError('');
|
||||
try { const evidence = asRow(reconciliation.result); const result = await api.confirmGovernanceReconciliation(String(reconciliation.id), { expectedRowVersion: Number(reconciliation.rowVersion || 0), expectedDifferenceHash: String(reconciliation.differenceHash), ...(evidence.transitionDifferenceHash ? { expectedTransitionDifferenceHash: String(evidence.transitionDifferenceHash) } : {}), reason: differenceReason.trim() }); setReconciliation(result); }
|
||||
catch (value) { reportError(value); } finally { setBusy(false); }
|
||||
catch (value) { reportError(value); } finally { actionLock.current = false; setBusy(false); }
|
||||
};
|
||||
const publish = async () => {
|
||||
if (!release?.id) return; setBusy(true); setError('');
|
||||
if (!active || !release?.id || actionLock.current) return; actionLock.current = true; setBusy(true); setError('');
|
||||
try { await api.publishRelease(String(release.id), { expectedCurrentReleaseId: release.expectedCurrentReleaseId === undefined ? options.currentReleaseId : release.expectedCurrentReleaseId as string | null, idempotencyKey: publishKey.current, reason: reason.trim() || differenceReason.trim() || '经来源校验与候选基线对账后发布' }); setPublished(true); onComplete(); }
|
||||
catch (value) { reportError(value); } finally { setBusy(false); }
|
||||
catch (value) { reportError(value); } finally { actionLock.current = false; setBusy(false); }
|
||||
};
|
||||
const evidence = asRow(reconciliation?.result); const comparisons = asRows(evidence.periodComparisons); const reconciliationErrors = Array.isArray(evidence.errors) ? evidence.errors : [];
|
||||
const publishReady = release?.complete === true && reconciliation?.publishReady === true;
|
||||
@@ -456,13 +543,13 @@ function DataUploadWizard({ user, mode, purpose, handoffSourceId, initialReason,
|
||||
const close = () => { generation.current++; onClose(); };
|
||||
return <Modal className="management-modal nc-workflow-modal" open width={1120} title={published ? purpose === 'WITHDRAW' ? '来源删除已发布' : '数据已发布' : purpose === 'WITHDRAW' ? '核对并发布删除候选' : resumeId ? '继续处理候选数据' : mode === 'REPLACE' ? '替换已有数据' : mode === 'REBUILD' ? '按当前来源重新计算' : '上传新数据'} onCancel={close} maskClosable={!busy} footer={<div className="nc-modal-footer"><span>{runId ? '关闭后任务继续,可在“数据接入”的“导入记录”查看;完成后从候选继续。' : '确认发布前,当前查询结果保持不变。'}</span><div>{step > 0 && step < 4 && !runId && !configuredSourceId && !busy && <Button onClick={() => { setStep(step - 1); setError(''); }}>上一步</Button>}<Button onClick={close}>{published ? '完成' : busy ? '关闭并稍后查看' : '关闭'}</Button>{!published && step === 1 && <Button type="primary" disabled={mode === 'REPLACE' && !target} loading={busy} onClick={() => { setStep(2); void changePreview(sheetName, headerRow); }}>下一步:匹配表头</Button>}{!published && step === 2 && <Button type="primary" loading={busy} disabled={Boolean(missingFields.length) || duplicateColumns || !sheetName} onClick={() => { if (workbook && (workbook.preview.headerRow !== headerRow || workbook.preview.sheetName !== sheetName)) { void changePreview(sheetName, headerRow); return; } setStep(3); }}>下一步:预览验证</Button>}{!published && step === 3 && !runId && mode !== 'REBUILD' && <Button type="primary" loading={busy} disabled={mode === 'REPLACE' && !reason.trim()} onClick={() => void beginImport()}>确认导入并校验</Button>}</div></div>}>
|
||||
<Steps className="nc-steps" current={published ? 5 : step} size="small" items={steps.map(title => ({ title }))} />
|
||||
{error && <Alert showIcon type="error" message="本次操作未完成" description={error} />}
|
||||
{error && <Alert showIcon type="error" message="本次操作未完成" description={error} action={resumeId && step === 4 ? <Button size="small" disabled={!active || busy || candidateReadLock.current} onClick={() => { if (!activeRef.current || candidateReadLock.current) return; candidateReadLock.current = true; setBusy(true); loadCandidate(resumeId).catch(reportError).finally(() => { candidateReadLock.current = false; setBusy(false); }); }}>重试读取候选</Button> : runId ? <Button size="small" disabled={!active || busy || pollLock.current} onClick={() => { if (!activeRef.current || pollLock.current) return; setBusy(true); void pollRun(); }}>重新获取处理结果</Button> : undefined} />}
|
||||
{published ? <div className="nc-success"><FileExcelOutlined /><h2>{purpose === 'WITHDRAW' ? '该来源已从当前查询结果移除' : '当前查询数据已更新'}</h2><p>来源原件和本次对账记录均已保留。</p></div> : <>
|
||||
{step === 0 && (mode === 'REBUILD' ? <div className="nc-rebuild-confirm"><h3>使用当前数据所用的全部来源重新计算</h3><p>计算使用当前启用的基础数据、对应关系和规则。完成后先生成候选,核对差异后再发布。</p><div className="nc-target-list">{options.targets.map(item => <div key={item.documentId}><Tag>{stageName(item.stage)}</Tag><strong>{item.year}年{item.month}月</strong><span>{item.sourceFile}</span></div>)}</div><Button type="primary" loading={busy} disabled={!options.targets.length} onClick={() => void rebuild()}>开始重新计算</Button></div> : <div className="nc-file-drop"><FileExcelOutlined /><h3>选择要{mode === 'REPLACE' ? '替换' : '上传'}的 Excel 文件</h3><p>支持 .xlsx;保留你的文件名,接下来选择数据期间和表头。</p><input className="visually-hidden-file" ref={input} type="file" accept=".xlsx" onChange={event => void readFile(event.target.files?.[0])} aria-label="选择质量数据Excel文件" /><Button type="primary" icon={<UploadOutlined />} loading={busy} onClick={() => input.current?.click()}>选择 Excel 文件</Button></div>)}
|
||||
{workbook && step > 0 && step < 4 && <div className="nc-file-summary"><FileExcelOutlined /><strong>{workbook.sourceFile}</strong><span>{stageName(stage)} · {year}年{month}月</span></div>}
|
||||
{step === 1 && <Form layout="vertical"><div className="nc-form-grid">{mode === 'REPLACE' ? <Form.Item className="nc-full-width" label="选择当前数据中的替换目标" required><Select {...readableSelectPopup} aria-label="选择当前数据中的替换目标" showSearch optionFilterProp="label" value={targetId || undefined} placeholder="选择年月、阶段和原文件" options={options.targets.map(item => ({ value: item.documentId, label: `${item.year}年${item.month}月 · ${stageName(item.stage)} · ${item.sourceFile}` }))} onChange={chooseTarget} /></Form.Item> : <><Form.Item label="数据阶段" required><Select aria-label="数据阶段" value={stage} options={[{ value: 'black', label: '黑片' }, { value: 'bright', label: '亮片' }]} onChange={value => { setStage(value); setFieldMap(matchFields(options.fields[value] || [], headers)); }} /></Form.Item><Form.Item label="统计年份" required><InputNumber aria-label="统计年份" min={2000} max={2100} value={year} onChange={value => { if (value) setYear(value); }} /></Form.Item><Form.Item label="统计月份" required><Select aria-label="统计月份" value={month} options={Array.from({ length: 12 }, (_, index) => ({ value: index + 1, label: `${index + 1}月` }))} onChange={setMonth} /></Form.Item>{options.scopes.length > 1 && <Form.Item label="数据范围" required><Select aria-label="数据范围" value={scopeCode} options={options.scopes.map(value => ({ value, label: value === 'ALL' ? '全部范围' : value }))} onChange={setScopeCode} /></Form.Item>}</>}</div>{target && <div className="nc-replacement"><span>原文件</span><strong>{target.sourceFile}</strong><ArrowRightOutlined /><span>新文件</span><strong>{workbook?.sourceFile}</strong></div>}<Form.Item label={mode === 'REPLACE' ? '替换理由' : '本次说明'} required={mode === 'REPLACE'}><Input.TextArea aria-label={mode === 'REPLACE' ? '替换理由' : '本次说明'} value={reason} rows={2} maxLength={1000} placeholder={mode === 'REPLACE' ? '例如:补齐遗漏记录,使用更新后的完整月表' : '可填写本次数据说明'} onChange={event => setReason(event.target.value)} /></Form.Item></Form>}
|
||||
{step === 2 && workbook && <><div className="nc-form-grid"><Form.Item label="工作表" required><Select aria-label="数据工作表" value={sheetName} options={workbook.sheets.map(sheet => ({ value: sheet.sheetName, label: sheet.sheetName }))} onChange={value => void changePreview(value, headerRow)} /></Form.Item><Form.Item label="表头在第几行" required><InputNumber aria-label="表头所在行" min={1} max={100} value={headerRow} onChange={value => { if (value) setHeaderRow(value); }} onBlur={() => { if (headerRow !== workbook.preview.headerRow) void changePreview(sheetName, headerRow); }} onPressEnter={() => void changePreview(sheetName, headerRow)} /></Form.Item></div><div className="nc-section-title"><h3>业务字段对应 Excel 中哪一列</h3><span>{duplicateColumns ? '同一 Excel 列不能对应多个业务字段' : missingFields.length ? `还需选择 ${missingFields.length} 个必填字段` : '必填字段已全部匹配'}</span></div><Spin spinning={busy}><ColumnMatching fields={fields} headers={headers} value={fieldMap} onChange={setFieldMap} /></Spin><h3>原表前几行</h3><SampleTable headers={headers} rows={workbook.preview.sampleRows.map(row => row.values)} /></>}
|
||||
{step === 3 && <>{!runId && workbook && <><div className="nc-review-facts"><div><small>统计期间</small><strong>{year}年{month}月 · {stageName(stage)}</strong></div><div><small>工作表与表头</small><strong>{sheetName} · 第{headerRow}行</strong></div><div><small>已匹配字段</small><strong>{Object.keys(fieldMap).length} 项</strong></div></div>{target && <Alert type="warning" showIcon message="即将使用新文件替换该期间的完整数据" description={`原文件:${target.sourceFile};新文件:${workbook.sourceFile}。本次先生成候选,最后发布后才更新查询结果。`} />}<SampleTable headers={Object.keys(fieldMap)} rows={workbook.preview.sampleRows.map(row => Object.fromEntries(Object.entries(fieldMap).map(([field, header]) => [field, row.values[header]])))} /><p className="nc-note">确认后由系统校验文件内容、数据范围及对应关系,并计算候选结果。</p></>}{(runId || (busy && mode === 'REBUILD')) && <div className="nc-processing"><Spin spinning={busy} /><h3>{statusLabel[String(run?.status)] || '正在创建计算任务'}</h3><Progress percent={Number(run?.total) > 0 ? Math.min(100, Math.round(Number(run?.processed || 0) / Number(run?.total) * 100)) : 0} status={run?.status === 'FAILED' ? 'exception' : 'active'} /><p>已处理 {txt(run?.processed || 0)} / {txt(run?.total)} 行</p>{run?.errorMessage ? <Alert type="error" showIcon message={txt(run.errorMessage)} /> : null}{!busy && runId && !['FAILED', 'CANCELLED'].includes(String(run?.status)) && <Button onClick={() => { setBusy(true); setPollAttempt(previous => previous + 1); }}>重新获取处理结果</Button>}</div>}<ValidationNotice value={run?.validation} /></>}
|
||||
{step === 3 && <>{!runId && workbook && <><div className="nc-review-facts"><div><small>统计期间</small><strong>{year}年{month}月 · {stageName(stage)}</strong></div><div><small>工作表与表头</small><strong>{sheetName} · 第{headerRow}行</strong></div><div><small>已匹配字段</small><strong>{Object.keys(fieldMap).length} 项</strong></div></div>{target && <Alert type="warning" showIcon message="即将使用新文件替换该期间的完整数据" description={`原文件:${target.sourceFile};新文件:${workbook.sourceFile}。本次先生成候选,最后发布后才更新查询结果。`} />}<SampleTable headers={Object.keys(fieldMap)} rows={workbook.preview.sampleRows.map(row => Object.fromEntries(Object.entries(fieldMap).map(([field, header]) => [field, row.values[header]])))} /><p className="nc-note">确认后由系统校验文件内容、数据范围及对应关系,并计算候选结果。</p></>}{(runId || (busy && mode === 'REBUILD')) && <div className="nc-processing"><Spin spinning={busy} /><h3>{statusLabel[String(run?.status)] || '正在创建计算任务'}</h3><Progress percent={Number(run?.total) > 0 ? Math.min(100, Math.round(Number(run?.processed || 0) / Number(run?.total) * 100)) : 0} status={run?.status === 'FAILED' ? 'exception' : 'active'} /><p>已处理 {txt(run?.processed || 0)} / {txt(run?.total)} 行</p>{run?.errorMessage ? <Alert type="error" showIcon message={txt(run.errorMessage)} /> : null}{!busy && runId && !['FAILED', 'CANCELLED'].includes(String(run?.status)) && <Button disabled={!active || pollLock.current} onClick={() => { if (!activeRef.current || pollLock.current) return; setBusy(true); void pollRun(); }}>重新获取处理结果</Button>}</div>}<ValidationNotice value={run?.validation} /></>}
|
||||
{step === 4 && <Spin spinning={busy}><div className="nc-review-facts"><div><small>候选数据</small><strong>待核对</strong></div><div><small>来源校验</small><strong>{release?.complete === true ? '通过' : '尚未通过'}</strong></div><div><small>基线对账</small><strong>{statusLabel[String(reconciliation?.status)] || '待执行'}</strong></div></div><ValidationNotice value={release?.validation || run?.validation} />{reconciliationErrors.length > 0 && <Alert showIcon type="error" message="对账存在阻断事项" description={reconciliationErrors.map(txt).join(';')} />}<div className="nc-section-title"><h3>与当前数据的差异</h3><Button icon={<ReloadOutlined />} loading={busy} disabled={!release?.id} onClick={() => void reconcile()}>{reconciliation ? '重新对账' : '执行基线对账'}</Button></div>{comparisons.length > 0 ? <Table size="small" bordered dataSource={comparisons} rowKey={(row, index) => `${row.dimension}:${row.key}:${index}`} pagination={{ pageSize: 15, showSizeChanger: false }} scroll={{ x: 900 }} columns={[{ title: '期间', width: 130, render: (_, row) => { const period = asRow(row.period); return `${txt(period.year)}年${period.month ? `${txt(period.month)}月` : period.quarter ? `第${txt(period.quarter)}季度` : '全年'}`; } }, { title: '维度 / 对象', width: 200, render: (_, row) => `${({ overall: '总体', department: '产业部', group: '业务分组', product: '产品', projectGroup: '项目组' } as Record<string, string>)[String(row.dimension)] || txt(row.dimension)} / ${txt(row.key)}` }, { title: '原综合率', width: 120, render: (_, row) => ratio(asRow(row.before).compositeRate) }, { title: '新综合率', width: 120, render: (_, row) => ratio(asRow(row.after).compositeRate) }, { title: '差异', render: (_, row) => asRows(row.differences).map(item => `${metricLabel(item.path)}:${txt(item.before)} → ${txt(item.after)}`).join(';') || '一致' }]} /> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description={reconciliation ? '本次没有可展示的期间比较;以对账结论为准' : '执行对账后在这里查看期间和指标差异'} />}{reconciliation?.status === 'REVIEW_REQUIRED' && <div className="nc-difference-confirm"><Alert type="warning" showIcon message={`发现 ${txt(evidence.differenceCount)} 项差异,需要发布者确认`} />{canPublish ? <><Input.TextArea aria-label="业务差异确认理由" rows={2} value={differenceReason} maxLength={1000} placeholder="填写差异原因及确认依据" onChange={event => setDifferenceReason(event.target.value)} /><Checkbox checked={confirmDifferences} onChange={event => setConfirmDifferences(event.target.checked)}>我已核对上方差异,并确认新数据正确</Checkbox><Button type="primary" disabled={!confirmDifferences || !differenceReason.trim() || busy} onClick={() => void confirm()}>确认差异并验收</Button></> : <p>候选已保存,请交由有数据发布权限的同事完成差异确认。</p>}</div>}{canPublish ? <div className="nc-publish-confirm"><Checkbox disabled={!publishReady} checked={publishConfirmed} onChange={event => setPublishConfirmed(event.target.checked)}>{purpose === 'WITHDRAW' ? '我确认发布此删除候选,从当前查询结果移除已批准的来源' : '我确认将此候选发布为当前查询数据'}{target ? `,替换${target.year}年${target.month}月${stageName(target.stage)}` : ''}</Checkbox><Button size="large" type="primary" disabled={!publishReady || !publishConfirmed || busy} onClick={() => void publish()}>确认发布</Button>{!publishReady && <span>来源校验和基线对账通过后可发布。</span>}</div> : <Alert showIcon type="info" message="候选数据已保存,等待有权限的同事发布" description={<><span>当前账号没有数据发布权限。可复制处理链接交接,正式查询数据尚未更新。</span><Button type="link" onClick={() => { const link = new URL(window.location.href); link.searchParams.set('page', 'sources'); if (handoffSourceId) { link.searchParams.set('sourceDeleteId', handoffSourceId); link.searchParams.delete('candidateReleaseId'); } else { link.searchParams.set('candidateReleaseId', String(release?.id || '')); link.searchParams.delete('sourceDeleteId'); } void navigator.clipboard.writeText(link.toString()).then(() => message.success('处理链接已复制')).catch(reportError); }}>复制处理链接</Button></>} />}</Spin>}
|
||||
{issues.length > 0 && <><h3>需要处理的来源行</h3><Table size="small" bordered dataSource={issues} rowKey={(row, index) => String(row.id || index)} pagination={{ pageSize: 15 }} columns={[{ title: '工作表', dataIndex: 'sheet', width: 120 }, { title: '行号', dataIndex: 'rowNumber', width: 80 }, { title: '字段', dataIndex: 'field', width: 130 }, { title: '问题说明', dataIndex: 'message' }]} /></>}
|
||||
</>}
|
||||
@@ -487,6 +574,7 @@ export function MasterWorkbookUpload({ kind, base, onUnauthorized, onComplete, s
|
||||
const [mode, setMode] = useState<'MERGE' | 'REPLACE'>('MERGE'); const [columns, setColumns] = useState<Record<string, string>>({});
|
||||
const [name, setName] = useState(''); const [reason, setReason] = useState(''); const [confirmed, setConfirmed] = useState(false);
|
||||
const [busy, setBusy] = useState(false); const [error, setError] = useState(''); const [result, setResult] = useState<Row | null>(null);
|
||||
const actionLock = useRef(false);
|
||||
const [preparedDefinition, setPreparedDefinition] = useState<Row | null>(null);
|
||||
const [preparedReleaseId, setPreparedReleaseId] = useState<string | null>(null);
|
||||
const workflowOperation = useDataWorkflowOperation('mapping-workbook-import', () => { onComplete(); message.success('基础数据已保存,报表已更新'); });
|
||||
@@ -523,7 +611,7 @@ export function MasterWorkbookUpload({ kind, base, onUnauthorized, onComplete, s
|
||||
setColumns(autoMatch(nextSheet?.headers || [], nextKind, format, suggestedTables, nextSheet?.name || sheetName));
|
||||
};
|
||||
const readFile = async (file?: File) => {
|
||||
if (!file) return; setBusy(true); setError('');
|
||||
if (!file || actionLock.current) return; actionLock.current = true; setBusy(true); setError('');
|
||||
try {
|
||||
const response = await api.previewMasterWorkbook(file); setPreview(response);
|
||||
const nextKind = response.standardBundleAvailable ? 'standardBundle' : (selectedKind === 'standardBundle' ? kind === 'masterData' ? 'departments' : 'categoryLookup' : selectedKind);
|
||||
@@ -535,10 +623,10 @@ export function MasterWorkbookUpload({ kind, base, onUnauthorized, onComplete, s
|
||||
setName(simplified ? configurationDateTime(new Date()) : `${nextKind === 'standardBundle' ? '整本基础数据' : kindLabel(nextKind)}·${file.name.replace(/\.xlsx$/i, '')}`.slice(0, 120));
|
||||
setResult(null); setConfirmed(false);
|
||||
} catch (value) { if (!onUnauthorized(value)) setError(failure(value)); }
|
||||
finally { setBusy(false); if (fileInput.current) fileInput.current.value = ''; }
|
||||
finally { actionLock.current = false; setBusy(false); if (fileInput.current) fileInput.current.value = ''; }
|
||||
};
|
||||
const submit = async () => {
|
||||
if (!preview || !base || !sheet) return; setBusy(true); setError('');
|
||||
if (!preview || !base || !sheet || actionLock.current) return; actionLock.current = true; setBusy(true); setError('');
|
||||
try {
|
||||
if (simplified && preparedDefinition) {
|
||||
await workflowOperation.start(() => api.applyDataWorkflow({ kind: 'mapping', name: name.trim(), definition: preparedDefinition, description: '测试阶段基础数据导入', expectedCurrentReleaseId: preparedReleaseId }));
|
||||
@@ -563,7 +651,7 @@ export function MasterWorkbookUpload({ kind, base, onUnauthorized, onComplete, s
|
||||
}
|
||||
setResult(response); onComplete();
|
||||
} catch (value) { if (!onUnauthorized(value)) setError(failure(value)); }
|
||||
finally { setBusy(false); }
|
||||
finally { actionLock.current = false; setBusy(false); }
|
||||
};
|
||||
const canSubmit = Boolean(base && name.trim() && (simplified || (reason.trim() && confirmed)) && (bundle ? preview?.standardBundleAvailable && suggestedTables.length : sheet && activeColumns.every(column => !column.required || columns[column.key])));
|
||||
return <>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { Alert, App, Button, Descriptions, Form, Input, Modal, Tabs } from 'antd';
|
||||
import { api } from './api';
|
||||
import type { AuthUser } from './types';
|
||||
@@ -20,6 +20,7 @@ export default function PersonalAccount({ user, tab, onClose, onUserChange, onUn
|
||||
const [form] = Form.useForm<PasswordValues>();
|
||||
const [activeTab, setActiveTab] = useState<AccountTab>('profile');
|
||||
const [busy, setBusy] = useState(false);
|
||||
const savingRef = useRef(false);
|
||||
const [error, setError] = useState('');
|
||||
const forced = user.forcePasswordChange === true;
|
||||
const open = tab !== null || forced;
|
||||
@@ -29,6 +30,8 @@ export default function PersonalAccount({ user, tab, onClose, onUserChange, onUn
|
||||
}, [open, tab, forced, form]);
|
||||
|
||||
const save = async (values: PasswordValues) => {
|
||||
if (savingRef.current) return;
|
||||
savingRef.current = true;
|
||||
setBusy(true); setError('');
|
||||
try {
|
||||
await api.changePassword(values.currentPassword, values.newPassword);
|
||||
@@ -38,7 +41,7 @@ export default function PersonalAccount({ user, tab, onClose, onUserChange, onUn
|
||||
message.success('密码已修改,下次登录请使用新密码');
|
||||
} catch (failure) {
|
||||
if (!onUnauthorized(failure)) setError(failure instanceof Error ? failure.message : '修改失败,请重试');
|
||||
} finally { setBusy(false); }
|
||||
} finally { savingRef.current = false; setBusy(false); }
|
||||
};
|
||||
|
||||
return <Modal className="personal-account-modal" open={open} title="个人账户" width={520} footer={null}
|
||||
|
||||
@@ -34,7 +34,7 @@ import { workspaceThemes, type WorkspaceThemeId } from './ui-themes';
|
||||
import { readableSelectPopup } from './readableSelectPopup';
|
||||
import PersonalAccount, { type AccountTab } from './PersonalAccount';
|
||||
|
||||
import { CachedWorkspacePages, type WorkspaceNavigation } from './CachedWorkspacePages';
|
||||
import { CachedWorkspacePages, preloadWorkspacePage, type WorkspaceNavigation } from './CachedWorkspacePages';
|
||||
|
||||
export type PageKey = 'overall' | 'department' | 'group' | 'product' | 'blackProduct' | 'brightProduct' | 'basis' | 'analysis' | 'sources' | 'imports' | 'rules' | 'mappings' | 'masterData' | 'tasks' | 'access';
|
||||
|
||||
@@ -138,6 +138,8 @@ export default function QualityWorkspace({ appearance, onAppearanceChange }: Qua
|
||||
|
||||
useEffect(() => {
|
||||
let alive = true;
|
||||
// Fetch only the selected page's code while identity validation runs; data stays gated.
|
||||
void preloadWorkspacePage(pageFromLocation()).catch(() => {});
|
||||
(async () => {
|
||||
try {
|
||||
await api.refreshCsrf();
|
||||
|
||||
+58
-56
@@ -1,9 +1,12 @@
|
||||
import { loadedQueryScope, queryForLocation, readQueryLocation } from './queryLoadingScope';
|
||||
import { AnimatedMetricText, SmoothTableFrame, useAnimatedMetricText, useRetainedResult } from './QueryResultMotion';
|
||||
import { trendBarPalette } from './trendBarPalette';
|
||||
import { getWorkspaceTheme } from './ui-themes';
|
||||
import { queryScrapWeight, queryTotalScrapWeight, type QueryRateBasis } from './queryMetricValues';
|
||||
import { BusinessValue } from './BusinessValue';
|
||||
import { usePageCache } from './pageCache';
|
||||
import { useDelayedIndicator } from './useDelayedBusy';
|
||||
import { useResourceVisibility } from './useResourceVisibility';
|
||||
import { useCallback, useEffect, useImperativeHandle, useLayoutEffect, useMemo, useRef, useState } from 'react';
|
||||
import * as echarts from 'echarts/core';
|
||||
import { BarChart, LineChart } from 'echarts/charts';
|
||||
@@ -153,6 +156,7 @@ function monthNumber(value: number | string): number | null {
|
||||
return result >= 1 && result <= 12 ? result : null;
|
||||
}
|
||||
|
||||
|
||||
function fullYearTrend(rows: TrendMetricRow[], year: number, granularity: 'month' | 'quarter' | 'year'): TrendMetricRow[] {
|
||||
if (granularity === 'year') return rows;
|
||||
const byPeriod = new Map<string, TrendMetricRow>();
|
||||
@@ -228,16 +232,7 @@ function escapeTooltipText(value: string): string {
|
||||
}
|
||||
|
||||
export function queryFromLocation(search = window.location.search): Partial<QueryParams> {
|
||||
const context = new URLSearchParams(search).get('context');
|
||||
if (!context) return {};
|
||||
try {
|
||||
const binary = atob(context.replace(/-/g, '+').replace(/_/g, '/') + '='.repeat((4 - context.length % 4) % 4));
|
||||
const parsed = JSON.parse(new TextDecoder().decode(Uint8Array.from(binary, character => character.charCodeAt(0)))) as { query?: unknown };
|
||||
if (!parsed.query || typeof parsed.query !== 'object') return {};
|
||||
const query = { ...(parsed.query as Partial<QueryParams>) };
|
||||
delete query.releaseId;
|
||||
return query;
|
||||
} catch { return {}; }
|
||||
return readQueryLocation(search);
|
||||
}
|
||||
|
||||
function toApiParams(args: {
|
||||
@@ -291,7 +286,7 @@ export default function QueryPage({ page, onUnauthorized }: {
|
||||
onNavigate?: (page: PageKey, query: QueryParams, resultRef?: TopResultRef) => void;
|
||||
}) {
|
||||
const { message } = App.useApp();
|
||||
const { active, initialSearch, refreshKey, onLocationChange } = usePageCache();
|
||||
const { active, initialSearch, refreshKey, onLocationChange, currentReleaseId } = usePageCache();
|
||||
const baseView = SCOPE[page] || 'overall';
|
||||
const [initialQuery] = useState(() => queryFromLocation(initialSearch));
|
||||
const [viewOverrideState, setViewOverrideState] = useState<{ page: PageKey; view: ViewKind } | undefined>(() => initialQuery.view && initialQuery.view !== baseView ? { page, view: initialQuery.view } : undefined);
|
||||
@@ -340,6 +335,7 @@ export default function QueryPage({ page, onUnauthorized }: {
|
||||
const [error, setError] = useState('');
|
||||
const [errorKey, setErrorKey] = useState('');
|
||||
const [queryRevision, setQueryRevision] = useState(0);
|
||||
const [trendRevision, setTrendRevision] = useState(0);
|
||||
const [selectedRecord, setSelectedRecord] = useState<MetricRow | null>(null);
|
||||
const [recordsOpen, setRecordsOpen] = useState(false);
|
||||
const [recordStage, setRecordStage] = useState<Stage>('black');
|
||||
@@ -361,8 +357,10 @@ export default function QueryPage({ page, onUnauthorized }: {
|
||||
|
||||
|
||||
useEffect(() => {
|
||||
if (!active) return;
|
||||
let alive = true;
|
||||
api.options().then(result => {
|
||||
const controller = new AbortController();
|
||||
api.options(controller.signal).then(result => {
|
||||
if (!alive) return;
|
||||
setOptions(result);
|
||||
if (automaticPeriod.current) {
|
||||
@@ -375,8 +373,8 @@ export default function QueryPage({ page, onUnauthorized }: {
|
||||
if (onUnauthorized(errorValue)) return;
|
||||
if (alive) setOptionsError(chooseError(errorValue));
|
||||
}).finally(() => { if (alive) setOptionsLoading(false); });
|
||||
return () => { alive = false; };
|
||||
}, [onUnauthorized, queryRevision]);
|
||||
return () => { alive = false; controller.abort(); };
|
||||
}, [active, onUnauthorized, queryRevision]);
|
||||
|
||||
const allowedGroups = useMemo(() => {
|
||||
const parents = new Set(department);
|
||||
@@ -406,7 +404,7 @@ export default function QueryPage({ page, onUnauthorized }: {
|
||||
if (product.length && !product.includes(exactProductSearch)) return [EMPTY_PRODUCT_SEARCH];
|
||||
return [exactProductSearch];
|
||||
}, [exactProductSearch, product]);
|
||||
const queryParams = useMemo(() => toApiParams({ year, period, month, quarter, department, group, product: productFilterForQuery, productSearch: view === 'product' ? appliedSearch : undefined, projectGroup, extraFilters, view, includeUnassigned, trendGranularity }), [year, period, month, quarter, department, group, productFilterForQuery, appliedSearch, projectGroup, extraFilters, view, includeUnassigned, trendGranularity]);
|
||||
const queryParams = useMemo(() => ({ ...toApiParams({ year, period, month, quarter, department, group, product: productFilterForQuery, productSearch: view === 'product' ? appliedSearch : undefined, projectGroup, extraFilters, view, includeUnassigned, trendGranularity }), releaseId: initialQuery.releaseId || currentReleaseId || undefined }), [year, period, month, quarter, department, group, productFilterForQuery, appliedSearch, projectGroup, extraFilters, view, includeUnassigned, trendGranularity, initialQuery.releaseId, currentReleaseId]);
|
||||
const queryKey = useMemo(() => JSON.stringify(queryParams), [queryParams]);
|
||||
const drilldownContextKey = JSON.stringify({ view, year, department, group, product, projectGroup, extraFilters, includeUnassigned });
|
||||
useEffect(() => {
|
||||
@@ -420,7 +418,6 @@ export default function QueryPage({ page, onUnauthorized }: {
|
||||
const queryBusy = loading || queryPending;
|
||||
const metricKeyRef = useRef(metricKey);
|
||||
metricKeyRef.current = metricKey;
|
||||
const useSummaryTrend = period === 'year' && !trendObject && trendGranularity === 'month';
|
||||
const trendParams = useMemo<QueryParams>(() => {
|
||||
const params = applyTrendObject(queryParams, trendObject, view);
|
||||
delete params.month;
|
||||
@@ -438,7 +435,7 @@ export default function QueryPage({ page, onUnauthorized }: {
|
||||
if (!active) return;
|
||||
const url = new URL(window.location.href);
|
||||
if (!['overall', 'department', 'group', 'product'].includes(url.searchParams.get('page') || '')) return;
|
||||
const bytes = new TextEncoder().encode(JSON.stringify({ query: queryParams }));
|
||||
const bytes = new TextEncoder().encode(JSON.stringify({ query: queryForLocation(queryParams, initialQuery.releaseId) }));
|
||||
let binary = '';
|
||||
for (const byte of bytes) binary += String.fromCharCode(byte);
|
||||
const context = btoa(binary).replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_');
|
||||
@@ -448,7 +445,7 @@ export default function QueryPage({ page, onUnauthorized }: {
|
||||
}, [queryKey, active]);
|
||||
|
||||
useEffect(() => {
|
||||
if (optionsLoading) return;
|
||||
if (!active || optionsLoading || optionsError) return;
|
||||
const controller = new AbortController();
|
||||
setLoading(true);
|
||||
setError('');
|
||||
@@ -457,10 +454,6 @@ export default function QueryPage({ page, onUnauthorized }: {
|
||||
if (controller.signal.aborted || metricKeyRef.current !== metricKey) return;
|
||||
setData(result);
|
||||
setDataKey(metricKey);
|
||||
if (useSummaryTrend && trendKeyRef.current === trendKey) {
|
||||
setTrendData(Array.isArray(result.trend) ? result.trend : []);
|
||||
setTrendDataKey(trendKey);
|
||||
}
|
||||
setError('');
|
||||
setErrorKey('');
|
||||
}).catch(errorValue => {
|
||||
@@ -470,9 +463,10 @@ export default function QueryPage({ page, onUnauthorized }: {
|
||||
setErrorKey(metricKey);
|
||||
}).finally(() => { if (!controller.signal.aborted) setLoading(false); });
|
||||
return () => controller.abort();
|
||||
}, [metricKey, queryRevision, onUnauthorized, optionsLoading]);
|
||||
}, [active, metricKey, queryRevision, onUnauthorized, optionsLoading, optionsError]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!active) return;
|
||||
if (!trendObject || defectQueryKey === queryKey) {
|
||||
setTrendObjectMetrics(null);
|
||||
setTrendObjectMetricsLoading(false);
|
||||
@@ -491,18 +485,14 @@ export default function QueryPage({ page, onUnauthorized }: {
|
||||
})
|
||||
.finally(() => { if (!controller.signal.aborted) setTrendObjectMetricsLoading(false); });
|
||||
return () => controller.abort();
|
||||
}, [trendObject, defectQueryKey, queryKey, queryRevision, onUnauthorized]);
|
||||
}, [active, trendObject, defectQueryKey, queryKey, queryRevision, onUnauthorized]);
|
||||
|
||||
useEffect(() => {
|
||||
if (optionsLoading) return;
|
||||
if (!active || optionsLoading || optionsError) return;
|
||||
setTrendFailure(null);
|
||||
if (useSummaryTrend) {
|
||||
setTrendLoading(false);
|
||||
return;
|
||||
}
|
||||
const controller = new AbortController();
|
||||
setTrendLoading(true);
|
||||
api.metrics(trendParams, controller.signal).then(result => {
|
||||
api.trend(trendParams, controller.signal).then(result => {
|
||||
if (controller.signal.aborted || trendKeyRef.current !== trendKey) return;
|
||||
setTrendData(Array.isArray(result.trend) ? result.trend : []);
|
||||
setTrendDataKey(trendKey);
|
||||
@@ -511,9 +501,10 @@ export default function QueryPage({ page, onUnauthorized }: {
|
||||
if (!controller.signal.aborted && !onUnauthorized(errorValue)) setTrendFailure({ key: trendKey, message: chooseError(errorValue) });
|
||||
}).finally(() => { if (!controller.signal.aborted) setTrendLoading(false); });
|
||||
return () => controller.abort();
|
||||
}, [trendKey, useSummaryTrend, queryRevision, onUnauthorized, optionsLoading]);
|
||||
}, [active, trendKey, queryRevision, trendRevision, onUnauthorized, optionsLoading, optionsError]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!active || optionsLoading || optionsError) return;
|
||||
let alive = true;
|
||||
setTrendTarget(null);
|
||||
setTrendTargetKey('');
|
||||
@@ -532,14 +523,15 @@ export default function QueryPage({ page, onUnauthorized }: {
|
||||
}
|
||||
});
|
||||
return () => { alive = false; };
|
||||
}, [trendKey, queryRevision, onUnauthorized]);
|
||||
}, [active, trendKey, queryRevision, trendRevision, onUnauthorized, optionsLoading, optionsError]);
|
||||
|
||||
const currentTrendTarget = trendTargetKey === trendKey ? trendTarget : null;
|
||||
const visibleTrendData = useMemo(() => fullYearTrend(trendDataKey === trendKey ? trendData : [], year, trendGranularity), [trendData, trendDataKey, trendKey, year, trendGranularity]);
|
||||
const currentTrendError = trendFailure?.key === trendKey ? trendFailure.message : '';
|
||||
const trendRefreshing = trendLoading || (useSummaryTrend && queryBusy) || (trendDataKey !== trendKey && !(useSummaryTrend ? currentMetricsError : currentTrendError));
|
||||
const trendRefreshing = !currentTrendError && (trendLoading || trendDataKey !== trendKey);
|
||||
const showTrendLoading = useDelayedIndicator(trendRefreshing);
|
||||
// 只在当前查询返回后替换画面;钻取等待期间保留上一次趋势和目标线。
|
||||
const retainedTrend = useRetainedResult(trendDataKey === trendKey ? { rows: visibleTrendData, target: currentTrendTarget } : null);
|
||||
const retainedTrend = useRetainedResult(trendDataKey === trendKey ? { rows: visibleTrendData, target: currentTrendTarget, query: trendParams } : null);
|
||||
const renderedTrendData = retainedTrend?.rows || visibleTrendData;
|
||||
const renderedTrendTarget = retainedTrend ? retainedTrend.target : currentTrendTarget;
|
||||
const drilledTrendData = useMemo(
|
||||
@@ -585,7 +577,7 @@ export default function QueryPage({ page, onUnauthorized }: {
|
||||
view: drilledProduct ? 'overall' as const : view,
|
||||
layoutView: drilledProduct ? 'product' as const : view,
|
||||
period: drilledProduct ? 'year' as const : period,
|
||||
year, month, quarter, drilledProduct,
|
||||
year, month, quarter, drilledProduct, paginationScope: JSON.stringify({query:queryParams,drilledProduct,view}),
|
||||
} : null);
|
||||
const tableRows = retainedTable?.rows || [];
|
||||
const tablePeriod = retainedTable?.period || period;
|
||||
@@ -755,7 +747,7 @@ export default function QueryPage({ page, onUnauthorized }: {
|
||||
</div>}
|
||||
</section>
|
||||
|
||||
{currentMetricsError && <Alert showIcon type="error" message="质量指标查询失败" description={currentMetricsError} action={<Button size="small" icon={<ReloadOutlined />} onClick={() => setQueryRevision(value => value + 1)}>重试</Button>} />}
|
||||
{currentMetricsError && <Alert showIcon type="error" message={data ? "更新失败,当前显示上次结果" : "质量指标查询失败"} description={currentMetricsError} action={<Button size="small" icon={<ReloadOutlined />} onClick={() => setQueryRevision(value => value + 1)}>重试</Button>} />}
|
||||
{drilledProduct && summaryMetricsError && <Alert showIcon type="error" message="当前产品指标查询失败" description={summaryMetricsError} action={<Button size="small" onClick={() => setQueryRevision(value => value + 1)}>重试</Button>} />}
|
||||
<section className={`metric-strip ${!displayedSummaryData ? 'query-awaiting-data' : ''}`} aria-label="质量指标" aria-busy={summaryBusy} inert={!summaryMetricsData}>
|
||||
<div className="rate-basis-control"><Segmented size="small" value={rateBasis} options={[{ label: '原口径', value: 'original' }, { label: '去本部报废', value: 'withoutHeadquartersScrap' }]} onChange={value => setRateBasis(value as typeof rateBasis)} aria-label="合格率口径" /></div>
|
||||
@@ -776,12 +768,12 @@ export default function QueryPage({ page, onUnauthorized }: {
|
||||
defectDisplay={defectDisplay} onDefectDisplay={setDefectDisplay} object={trendObject} onObject={setSynchronizedTrendObject}
|
||||
objects={trendOptions} scopeName={scopeName}
|
||||
stageSwitch={<Segmented value={trendStage} options={[{ label: '亮片', value: 'bright' }, { label: '黑片', value: 'black' }]} onChange={value => setTrendStage(value as Stage)} aria-label="趋势阶段" />}>
|
||||
{currentTrendError && <Alert type="warning" showIcon message="趋势读取失败" description={currentTrendError} action={<Button onClick={() => setQueryRevision(value => value + 1)}>重试</Button>} />}
|
||||
{currentTrendError && <Alert type="warning" showIcon message={retainedTrend ? "趋势更新失败,当前显示上次结果" : "趋势读取失败"} description={retainedTrend ? `${currentTrendError};当前范围:${loadedQueryScope(retainedTrend.query, decodeQueryValueList)}` : currentTrendError} action={<Button onClick={() => setTrendRevision(value => value + 1)}>重试</Button>} />}
|
||||
<div className="trend-chart-shell" aria-busy={trendRefreshing} inert={trendRefreshing || trendDataKey !== trendKey}>
|
||||
{trendMode === 'data'
|
||||
? <TrendTable rows={renderedTrendData} defectDisplay={defectDisplay} rateBasis={rateBasis} onMonth={selectTrendPeriod} />
|
||||
: <TrendChart rows={renderedTrendData} mode={trendMode} stage={trendStage} rateBasis={rateBasis} targetRate={renderedTrendTarget} selectedPeriod={selectedTrendPeriod} onMonth={selectTrendPeriod} />}
|
||||
{trendRefreshing && <span className="trend-refresh-indicator"><Spin size="small" />正在更新趋势</span>}
|
||||
{showTrendLoading && <span className="trend-refresh-indicator"><Spin size="small" />{retainedTrend ? `正在更新 · 当前显示上次筛选的${loadedQueryScope(retainedTrend.query, decodeQueryValueList)}` : '正在读取趋势'}</span>}
|
||||
</div>
|
||||
</QueryTrendPanel>
|
||||
|
||||
@@ -792,7 +784,7 @@ export default function QueryPage({ page, onUnauthorized }: {
|
||||
fullFields={fullFields} onFullFields={setFullFields} defectDisplay={defectDisplay} onDefectDisplay={setDefectDisplay}
|
||||
returnControls={<>{!drilledProduct && (view !== baseView || view === 'group' || view === 'product' && (group.length > 0 || department.length > 0)) && <Button className="query-return-button" icon={<ArrowLeftOutlined />} onClick={() => { setSearch(''); setAppliedSearch(''); setTrendObject(''); if (view === 'product') { setProduct([]); setGroup([]); setViewOverride('group'); } else if (view === 'group') { setGroup([]); setDepartment([]); setViewOverride('department'); } else { setViewOverride(); } }}>返回上一级</Button>}
|
||||
{drilledProduct && <Button className="query-return-button" icon={<ArrowLeftOutlined />} onClick={() => { setDrilledProduct(''); setTrendObject(''); setTrendMode('production'); }}>返回上一级</Button>}</>}
|
||||
exporting={summaryExporting} exportDisabled={queryBusy || summaryBusy || !summaryMetricsData || Boolean(drilledProduct && trendLoading) || !(drilledProduct ? drilledTrendData : visibleRows).length}
|
||||
exporting={summaryExporting} exportDisabled={queryBusy || summaryBusy || !tableReady || !summaryMetricsData || Boolean(drilledProduct && (trendLoading || currentTrendError)) || !(drilledProduct ? drilledTrendData : visibleRows).length}
|
||||
onExport={async () => {
|
||||
setSummaryExporting(true);
|
||||
try { await summaryExport.current?.exportExcel(); }
|
||||
@@ -802,6 +794,7 @@ export default function QueryPage({ page, onUnauthorized }: {
|
||||
<SmoothTableFrame busy={queryBusy || !tableReady} blocked={queryBusy || summaryBusy || !tableReady}>
|
||||
<MetricTable
|
||||
ref={summaryExport}
|
||||
paginationScope={retainedTable?.paginationScope}
|
||||
exportFilename={`${drilledProduct || scopeName}质量汇总-${year}${drilledProduct || period === 'year' ? '' : period === 'month' ? `-${String(month).padStart(2, '0')}` : `-Q${quarter}`}-${fullFields ? '完整字段' : '关键指标'}`}
|
||||
rows={tableRows}
|
||||
view={tableView}
|
||||
@@ -929,8 +922,11 @@ export function DefectParetoPanel({ releaseId, query, externalScrapWeight, onUna
|
||||
...(query.includeUnassigned ? { includeUnassigned: true } : {}),
|
||||
}), [query.year, query.month, query.quarter, query.department, query.group, query.product, query.productSearch, query.projectGroup, query.extraFilters, query.columnFilters, query.includeUnassigned]);
|
||||
const fineQueryKey = JSON.stringify(fineQuery);
|
||||
const visible = useResourceVisibility(container, active);
|
||||
const showLoading = useDelayedIndicator(loading);
|
||||
|
||||
useEffect(() => {
|
||||
if (!active || !visible) return;
|
||||
if (!releaseId) { setResponses(null); setLoading(false); setError(''); return; }
|
||||
const controller = new AbortController();
|
||||
const base = { releaseId, ...fineQuery, mode: 'top', dimension: 'defect', limit: 100 };
|
||||
@@ -947,7 +943,7 @@ export function DefectParetoPanel({ releaseId, query, externalScrapWeight, onUna
|
||||
})
|
||||
.finally(() => { if (!controller.signal.aborted) setLoading(false); });
|
||||
return () => controller.abort();
|
||||
}, [releaseId, fineQueryKey, onUnauthorized, onlyStage, refreshKey, externalScrapWeight]);
|
||||
}, [active, visible, releaseId, fineQueryKey, onUnauthorized, onlyStage, refreshKey, externalScrapWeight]);
|
||||
|
||||
useEffect(() => {
|
||||
const refresh = () => setThemeRevision(value => value + 1);
|
||||
@@ -1049,7 +1045,7 @@ export function DefectParetoPanel({ releaseId, query, externalScrapWeight, onUna
|
||||
}, [items, totalWeight, themeRevision, active]);
|
||||
|
||||
return <section className="defect-pareto-section" aria-busy={loading || pending} aria-label={onlyStage ? `${onlyStage === 'black' ? '黑片' : '亮片'}报废重量柏拉图` : '综合报废重量柏拉图'}>
|
||||
<div className="defect-pareto-heading"><strong>{onlyStage ? `${onlyStage === 'black' ? '黑片' : '亮片'}报废重量柏拉图` : '黑片与亮片综合报废重量柏拉图'}</strong>{loading && <span className="defect-refresh-indicator"><Spin size="small" />正在更新</span>}</div>
|
||||
<div className="defect-pareto-heading"><strong>{onlyStage ? `${onlyStage === 'black' ? '黑片' : '亮片'}报废重量柏拉图` : '黑片与亮片综合报废重量柏拉图'}</strong>{showLoading && <span className="defect-refresh-indicator"><Spin size="small" />正在更新</span>}</div>
|
||||
{error && <Alert showIcon type="warning" message="细分报废重量读取失败" description={error} />}
|
||||
{!loading && !releaseId && <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="当前没有已发布数据版本" />}
|
||||
{!loading && !error && responses && !items.length && <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="当前筛选下没有正值细分报废重量" />}
|
||||
@@ -1078,10 +1074,10 @@ const totalWeightTitle = (label: string) => <span className="query-total-weight-
|
||||
const rateBasisTitle = (label: string, basis: QueryRateBasis, kind: 'bright' | 'composite', onBasis?: () => void) => <span className="query-total-weight-title query-rate-rule-title"><span className="query-rate-label">{onBasis ? <button className="header-link" onClick={onBasis}>{label}</button> : label}{basis !== 'original' && <small className="query-rate-subtitle">(去本部报废)</small>}</span>{basis !== 'original' && <Tooltip trigger={['hover', 'focus']} title={<div>{kind === 'composite' && <>综合合格率=黑片合格率×亮片合格率。<br /></>}原口径:亮片合格重量÷亮片总重量。<br />去本部报废:(亮片合格重量+本部报废)÷亮片总重量,同时从亮片报废重量中扣除本部报废,总重量不变。<br />当前:去本部报废。计算结果以已发布数据版本及生效规则为准。</div>}><InfoCircleOutlined tabIndex={0} role="img" aria-label={`${kind === 'composite' ? '综合合格率' : '亮片合格率'}计算说明`} /></Tooltip>}</span>;
|
||||
|
||||
export function MetricTable({
|
||||
ref, exportFilename, rows, view, layoutView = view, pageSizeOverride, period, month, quarter, fullFields, rateBasis, onDetail, onBasis, onDrilldown, onlyStage, defectDisplay = 'weight', emptyText = '当前条件下暂无数据',
|
||||
ref, exportFilename, rows, view, layoutView = view, pageSizeOverride, paginationScope, period, month, quarter, fullFields, rateBasis, onDetail, onBasis, onDrilldown, onlyStage, defectDisplay = 'weight', emptyText = '当前条件下暂无数据',
|
||||
}: {
|
||||
ref?: React.Ref<{ exportExcel: () => Promise<void> }>; exportFilename: string;
|
||||
rows: MetricRow[]; view: ViewKind; layoutView?: ViewKind; pageSizeOverride?: number; period: PeriodKind; month: number; quarter: number; fullFields: boolean;
|
||||
rows: MetricRow[]; view: ViewKind; layoutView?: ViewKind; pageSizeOverride?: number; paginationScope?: string; period: PeriodKind; month: number; quarter: number; fullFields: boolean;
|
||||
rateBasis: 'original' | 'withoutHeadquartersScrap';
|
||||
onDetail: (row: MetricRow | null, stage: Stage, month?: number) => void; onBasis: () => void; onDrilldown: (row: MetricRow) => void;
|
||||
emptyText?: string; onlyStage?: Stage; defectDisplay?: 'weight'|'rate';
|
||||
@@ -1149,9 +1145,9 @@ export function MetricTable({
|
||||
const dataSource = rows.map((row, index) => ({ ...row, key: row.key || `${title(row)}-${index}` }));
|
||||
const [currentPage, setCurrentPage] = useState(1);
|
||||
const [pageSize, setPageSize] = useState(SUMMARY_PAGE_SIZE);
|
||||
const effectivePage = pageSizeOverride == null ? currentPage : 1;
|
||||
const effectivePage = pageSizeOverride == null ? Math.min(currentPage, Math.max(1, Math.ceil(rows.length / pageSize))) : 1;
|
||||
const effectivePageSize = pageSizeOverride ?? pageSize;
|
||||
useEffect(() => setCurrentPage(1), [rows]);
|
||||
useEffect(() => setCurrentPage(1), [paginationScope ?? rows]);
|
||||
const columnWidth = (column: ColumnsType<MetricRow>[number]): number => {
|
||||
if ('children' in column && column.children?.length) {
|
||||
return column.children.reduce((total, child) => total + columnWidth(child), 0);
|
||||
@@ -1163,7 +1159,7 @@ export function MetricTable({
|
||||
const displayColumns = compact ? columns.flatMap(column => 'children' in column && column.children ? column.children : [column]) : columns;
|
||||
const pageRows = dataSource.slice((effectivePage - 1) * effectivePageSize, effectivePage * effectivePageSize);
|
||||
return <div className="metric-table-scroll"><Table<MetricRow> size="small" bordered tableLayout="fixed" columns={displayColumns} dataSource={pageRows} pagination={false} scroll={scroll} rowKey="key" locale={{ emptyText }} />
|
||||
{pageSizeOverride == null && <MetricTablePagination current={currentPage} total={dataSource.length} pageSize={pageSize} onChange={(nextPage, nextPageSize) => { setPageSize(nextPageSize); setCurrentPage(nextPageSize === pageSize ? nextPage : 1); }} />}
|
||||
{pageSizeOverride == null && <MetricTablePagination current={effectivePage} total={dataSource.length} pageSize={pageSize} onChange={(nextPage, nextPageSize) => { setPageSize(nextPageSize); setCurrentPage(nextPageSize === pageSize ? nextPage : 1); }} />}
|
||||
</div>;
|
||||
}
|
||||
|
||||
@@ -1181,6 +1177,7 @@ function trendBarWidth(chartWidth: number, count: number): number {
|
||||
export function TrendChart({ rows, mode, stage, rateBasis, targetRate, selectedPeriod, onMonth, onlyStage }: { rows: TrendMetricRow[]; mode: 'production' | 'defects'; stage: Stage; rateBasis: 'original' | 'withoutHeadquartersScrap'; targetRate: number | null; selectedPeriod?: string; onMonth: (value: number | string) => void; onlyStage?: Stage }) {
|
||||
const { active } = usePageCache();
|
||||
const container = useRef<HTMLDivElement>(null);
|
||||
const visible = useResourceVisibility(container, active);
|
||||
const chart = useRef<ReturnType<typeof echarts.init> | null>(null);
|
||||
const onMonthRef = useRef(onMonth);
|
||||
const rowsRef = useRef(rows);
|
||||
@@ -1228,7 +1225,7 @@ export function TrendChart({ rows, mode, stage, rateBasis, targetRate, selectedP
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!container.current || !hasRows || !active) return;
|
||||
if (!container.current || !hasRows || !visible) return;
|
||||
const instance = echarts.init(container.current, undefined, { renderer: 'svg', width: container.current.clientWidth, height: container.current.clientHeight });
|
||||
chart.current = instance;
|
||||
graphicIds.current.clear();
|
||||
@@ -1260,7 +1257,7 @@ export function TrendChart({ rows, mode, stage, rateBasis, targetRate, selectedP
|
||||
});
|
||||
observer.observe(container.current);
|
||||
return () => { observer.disconnect(); instance.dispose(); chart.current = null; };
|
||||
}, [hasRows, refreshBarMasks, active]);
|
||||
}, [hasRows, refreshBarMasks, visible]);
|
||||
|
||||
useEffect(() => {
|
||||
const instance = chart.current;
|
||||
@@ -1350,7 +1347,7 @@ export function TrendChart({ rows, mode, stage, rateBasis, targetRate, selectedP
|
||||
}
|
||||
instance.setOption(option, { replaceMerge: ['series', 'yAxis'], lazyUpdate: false });
|
||||
refreshBarMasks();
|
||||
}, [rows, mode, stage, rateBasis, targetRate, themeRevision, refreshBarMasks, onlyStage, selectedPeriod, active]);
|
||||
}, [rows, mode, stage, rateBasis, targetRate, themeRevision, refreshBarMasks, onlyStage, selectedPeriod, active, visible]);
|
||||
|
||||
const dimmedPeriod = selectedPeriod === lineSelectedPeriod ? undefined : selectedPeriod;
|
||||
|
||||
@@ -1420,7 +1417,7 @@ export function RecordsDrawer({
|
||||
query: QueryParams; month?: number; onUnauthorized: (error: unknown) => boolean; lockedStage?: boolean;
|
||||
}) {
|
||||
const { message } = App.useApp();
|
||||
const { refreshKey } = usePageCache();
|
||||
const { active, refreshKey } = usePageCache();
|
||||
const recordPages = useRef(new Map<string, RecordsResponse>());
|
||||
const [page, setPage] = useState(1);
|
||||
const [response, setResponse] = useState<{ key: string; data: RecordsResponse } | null>(null);
|
||||
@@ -1445,14 +1442,16 @@ export function RecordsDrawer({
|
||||
const result = response?.key === requestKey ? response.data : null;
|
||||
const error = failure?.key === requestKey ? failure.message : '';
|
||||
const fetching = loading || !result && !error;
|
||||
const retainedResult = useRetainedResult(result);
|
||||
const showRecordLoading = useDelayedIndicator(fetching && open);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
if (!open || !active) return;
|
||||
const cached = recordPages.current.get(requestKey);
|
||||
if (cached) { setResponse({ key: requestKey, data: cached }); setFailure(null); setLoading(false); return; }
|
||||
const controller = new AbortController();
|
||||
setLoading(true);
|
||||
setResponse(null); setFailure(null);
|
||||
setFailure(null);
|
||||
api.records(requestParams, controller.signal).then(value => {
|
||||
if (controller.signal.aborted) return;
|
||||
const lastPage = Math.max(1, Math.ceil(value.total / value.pageSize));
|
||||
@@ -1468,7 +1467,7 @@ export function RecordsDrawer({
|
||||
if (!onUnauthorized(errorValue)) setFailure({ key: requestKey, message: chooseError(errorValue) });
|
||||
}).finally(() => { if (!controller.signal.aborted) setLoading(false); });
|
||||
return () => controller.abort();
|
||||
}, [open, requestKey, revision, onUnauthorized]);
|
||||
}, [open, active, requestKey, revision, onUnauthorized]);
|
||||
|
||||
const visibleRawFields = selectedColumns ?? rawFields.slice(0, 8);
|
||||
const exportRecords = async () => {
|
||||
@@ -1536,7 +1535,7 @@ export function RecordsDrawer({
|
||||
];
|
||||
|
||||
return <Drawer className="source-records-drawer" open={open} onClose={onClose} width={Math.min(1120, window.innerWidth)} title={<div className="drawer-title">来源明细 <small>{row?.label || (month ? MONTHS[month - 1] : '当前筛选条件')}</small></div>} destroyOnClose>
|
||||
<div className="drawer-controls"><Segmented disabled={lockedStage} value={stage} options={[{ label: '黑片', value: 'black' }, { label: '亮片', value: 'bright' }]} onChange={value => { onStage(value as Stage); setPage(1); setRawFields([]); setField(undefined); setFieldSearch(''); setSelectedColumns(undefined); setSort(undefined); }} aria-label="明细阶段" /><span>{result ? `共 ${result.total} 条来源记录 · 已载入 ${rawFields.length} 个原始字段` : '按当前查询条件获取原始来源行'}</span><Button size="small" icon={<DownloadOutlined />} loading={exporting} onClick={exportRecords} title={lockedStage ? '导出当前阶段和筛选范围的全部来源明细' : '导出当前查询范围全部来源明细,含黑片和亮片两个工作表'}>导出明细 Excel</Button></div>
|
||||
<div className="drawer-controls"><Segmented disabled={lockedStage} value={stage} options={[{ label: '黑片', value: 'black' }, { label: '亮片', value: 'bright' }]} onChange={value => { onStage(value as Stage); setPage(1); setRawFields([]); setField(undefined); setFieldSearch(''); setSelectedColumns(undefined); setSort(undefined); }} aria-label="明细阶段" /><span>{result ? `共 ${result.total} 条来源记录 · 已载入 ${rawFields.length} 个原始字段` : '按当前查询条件获取原始来源行'}</span><Button size="small" icon={<DownloadOutlined />} loading={exporting} disabled={fetching || !result || !!error} onClick={exportRecords} title={lockedStage ? '导出当前阶段和筛选范围的全部来源明细' : '导出当前查询范围全部来源明细,含黑片和亮片两个工作表'}>导出明细 Excel</Button></div>
|
||||
<div className="record-query-tools">
|
||||
<label><span>字段检索</span><Select {...readableSelectPopup} allowClear showSearch optionFilterProp="label" placeholder="选择原始字段" value={field} options={rawFields.map(name => ({ label: name, value: name }))} onChange={value => { setField(value); setPage(1); }} /></label>
|
||||
<Input allowClear disabled={!field} prefix={<SearchOutlined />} placeholder={field ? `搜索字段:${field}` : '先选择检索字段'} value={fieldSearch} onChange={event => { setFieldSearch(event.target.value); setPage(1); }} />
|
||||
@@ -1548,8 +1547,11 @@ export function RecordsDrawer({
|
||||
]} onChange={value => { setSort(value); setPage(1); }} /></label>
|
||||
<Segmented value={direction} options={[{ label: '升序', value: 'asc' }, { label: '降序', value: 'desc' }]} onChange={value => { setDirection(value as 'asc' | 'desc'); setPage(1); }} aria-label="排序方向" />
|
||||
</div>
|
||||
{error && <Alert type="error" showIcon message="来源明细加载失败" description={error} action={<Button size="small" onClick={() => setRevision(value => value + 1)}>重试</Button>} />}
|
||||
{fetching ? <div className="loading-panel"><Spin />正在读取来源行…</div> : result?.rows.length ? <Table size="small" bordered columns={fixedColumns} dataSource={result.rows} rowKey="id" pagination={false} scroll={{ x: 1800 + visibleRawFields.length * 180 }} /> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description={error ? '来源记录加载失败' : '当前条件没有来源记录'} />}
|
||||
{error && <Alert type="error" showIcon message={retainedResult ? "更新失败,当前显示上次结果" : "来源明细加载失败"} description={error} action={<Button size="small" onClick={() => setRevision(value => value + 1)}>重试</Button>} />}
|
||||
{showRecordLoading && <div role="status">{retainedResult ? '正在更新,当前显示上次来源结果' : <><Spin size="small" />正在读取来源行…</>}</div>}
|
||||
<div aria-busy={fetching} inert={!result || !!error}>
|
||||
{retainedResult?.rows.length ? <Table size="small" bordered columns={fixedColumns} dataSource={retainedResult.rows} rowKey="id" pagination={false} scroll={{ x: 1800 + visibleRawFields.length * 180 }} /> : !fetching && !error && <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="当前条件没有来源记录" />}
|
||||
</div>
|
||||
{result && result.total > result.pageSize && <Pagination className="records-pagination" current={page} pageSize={result.pageSize} total={result.total} showTotal={total => `共 ${total} 条`} onChange={next => setPage(next)} />}
|
||||
</Drawer>;
|
||||
}
|
||||
|
||||
@@ -55,13 +55,13 @@ export function SmoothTableFrame({ children, busy, blocked }: { children: ReactN
|
||||
useLayoutEffect(() => {
|
||||
const node = content.current;
|
||||
if (!node) return;
|
||||
const measure = () => setHeight(node.offsetHeight);
|
||||
const measure = () => { if (node.offsetHeight > 0) setHeight(node.offsetHeight); };
|
||||
measure();
|
||||
const observer = new ResizeObserver(measure);
|
||||
observer.observe(node);
|
||||
return () => observer.disconnect();
|
||||
}, []);
|
||||
useLayoutEffect(() => { if (content.current) setHeight(content.current.offsetHeight); }, [children]);
|
||||
useLayoutEffect(() => { if (content.current && content.current.offsetHeight > 0) setHeight(content.current.offsetHeight); }, [children]);
|
||||
return <div className="smooth-table-frame" style={{ height }}>
|
||||
<div ref={content} className="query-table-content" aria-busy={busy} inert={blocked}>{children}</div>
|
||||
</div>;
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { loadedQueryScope, queryForLocation } from './queryLoadingScope';
|
||||
import { SmoothTableFrame, useRetainedResult } from './QueryResultMotion';
|
||||
import { queryScrapWeight } from './queryMetricValues';
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
@@ -8,10 +9,11 @@ import { MetricTable, MetricCard, DefectBreakdown, DefectParetoPanel, SectionHea
|
||||
import { StageSourceFilters } from './StageSourceFilters';
|
||||
import { stageProductQuery, sortStageRowsByTotalWeight } from './stageProductQuery';
|
||||
import { usePageCache } from './pageCache';
|
||||
import { useDelayedIndicator } from './useDelayedBusy';
|
||||
import { defaultQueryMonth, previousCompleteMonth, previousCompleteQuarter } from './periodDefaults';
|
||||
import { readableSelectPopup } from './readableSelectPopup';
|
||||
import { readableMetricFormula } from './publicDataDisplay';
|
||||
import type { MetricRow, MetricsResponse, OptionsResponse, PeriodKind, QueryParams, SourceColumnField, SourceColumnFilter, Stage } from './types';
|
||||
import type { MetricRow, MetricsResponse, OptionsResponse, PeriodKind, QueryParams, SourceColumnField, SourceColumnFilter, Stage, TrendResponse } from './types';
|
||||
import { QueryTrendPanel, QueryTablePanel } from './QueryPanels';
|
||||
import { selectTrendPeriod as nextTrendPeriod } from './trendPeriodSelection';
|
||||
import './stage-product.css';
|
||||
@@ -19,7 +21,7 @@ import './stage-product.css';
|
||||
const weight=(v:number|null|undefined)=>typeof v==='number'?v.toLocaleString('zh-CN',{maximumFractionDigits:2}):'—';
|
||||
const rate=(v:number|null|undefined)=>typeof v==='number'?`${(v*100).toFixed(2)}%`:'—';
|
||||
export default function StageProductPage({stage,onUnauthorized}:{stage:Stage;onUnauthorized:(error:unknown)=>boolean}) {
|
||||
const {message}=App.useApp();const {active,initialSearch,refreshKey,onLocationChange}=usePageCache();
|
||||
const {message}=App.useApp();const {active,initialSearch,refreshKey,onLocationChange,currentReleaseId}=usePageCache();
|
||||
const [initial]=useState(()=>queryFromLocation(initialSearch));const defaults=previousCompleteMonth();
|
||||
const automaticPeriod=useRef(!initial.year&&!initial.month&&!initial.quarter);
|
||||
const [period,setPeriod]=useState<PeriodKind>(initial.quarter?'quarter':initial.month?'month':initial.year?'year':'month');
|
||||
@@ -33,21 +35,23 @@ export default function StageProductPage({stage,onUnauthorized}:{stage:Stage;onU
|
||||
const [fullFields,setFullFields]=useState(true);const [rateBasis,setRateBasis]=useState<'original'|'withoutHeadquartersScrap'>('original');const [basisOpen,setBasisOpen]=useState(false);const [trendMode,setTrendMode]=useState<'production'|'defects'|'data'>('production');
|
||||
const [drilledProduct,setDrilledProduct]=useState('');const drillParentSearch=useRef('');
|
||||
const [trendGranularity,setTrendGranularity]=useState<'month'|'quarter'|'year'>('month');
|
||||
const [trendResponse,setTrendResponse]=useState<{key:string;value:MetricsResponse}|null>(null);const [trendError,setTrendError]=useState('');const [trendLoading,setTrendLoading]=useState(false);
|
||||
const [trendResponse,setTrendResponse]=useState<{key:string;value:TrendResponse;query:QueryParams}|null>(null);const [trendRevision,setTrendRevision]=useState(0);const [trendError,setTrendError]=useState('');const [trendLoading,setTrendLoading]=useState(false);
|
||||
const [recordVisible,setRecordVisible]=useState(false);const [records,setRecords]=useState<{row:MetricRow|null;query:QueryParams}|null>(null);const exporter=useRef<{exportExcel:()=>Promise<void>}>(null);const [exporting,setExporting]=useState(false);
|
||||
const label=stage==='black'?'黑片':'亮片';
|
||||
const supportGeneration=useRef(0);const supportController=useRef<AbortController|null>(null);
|
||||
const loadSupport=useCallback(async()=>{
|
||||
const generation=++supportGeneration.current;supportController.current?.abort();const controller=new AbortController();supportController.current=controller;
|
||||
setSupportLoading(true);setSupportError('');
|
||||
try{const [choices,source]=await Promise.all([api.options(),api.sourceColumnCatalog()]);if(automaticPeriod.current){const available=defaultQueryMonth(choices);setYear(available.year);setMonth(available.month);automaticPeriod.current=false;}setOptions(choices);setCatalog(source);}
|
||||
catch(error){if(!onUnauthorized(error))setSupportError(error instanceof Error?error.message:'查询条件读取失败');}
|
||||
finally{setSupportLoading(false);}
|
||||
},[onUnauthorized]);
|
||||
useEffect(()=>{if(active)void loadSupport();},[active,refreshKey,loadSupport]);
|
||||
try{const [choices,source]=await Promise.all([api.options(controller.signal),api.sourceColumnCatalog(initial.releaseId||currentReleaseId||undefined,controller.signal)]);if(generation!==supportGeneration.current)return;if(automaticPeriod.current){const available=defaultQueryMonth(choices);setYear(available.year);setMonth(available.month);automaticPeriod.current=false;}setOptions(choices);setCatalog(source);}
|
||||
catch(error){if(generation===supportGeneration.current&&!onUnauthorized(error))setSupportError(error instanceof Error?error.message:'查询条件读取失败');}
|
||||
finally{if(generation===supportGeneration.current)setSupportLoading(false);}
|
||||
},[onUnauthorized,initial.releaseId,currentReleaseId]);
|
||||
useEffect(()=>{if(active)void loadSupport();return()=>{supportGeneration.current++;supportController.current?.abort();};},[active,refreshKey,loadSupport]);
|
||||
const fields=useMemo(()=>catalog?.sourceFields.filter(field=>field.type==='source_value'&&field.stages.includes(stage))||[],[catalog,stage]);
|
||||
const exactProductSearch=useMemo(()=>(options?.products||[]).find(name=>name.trim().toLocaleLowerCase()===appliedSearch.trim().toLocaleLowerCase())||'', [options,appliedSearch]);
|
||||
const queryProducts=useMemo(()=>drilledProduct?[drilledProduct]:exactProductSearch?product.length&&!product.includes(exactProductSearch)?['__codex_no_product_search_match__']:[exactProductSearch]:product,[drilledProduct,exactProductSearch,product]);
|
||||
useEffect(()=>{setDrilledProduct('');},[year,department,group,product,projectGroup,sourceFilters]);
|
||||
const draft=useMemo(()=>stageProductQuery({year,...(period==='month'?{month}:period==='quarter'?{quarter}:{}),department:encodeQueryValueList(department),group:encodeQueryValueList(group),product:encodeQueryValueList(queryProducts),projectGroup:encodeQueryValueList(projectGroup),productSearch:drilledProduct?undefined:appliedSearch.trim()||undefined,includeUnassigned,view:'product',trendGranularity:'month',releaseId:catalog?.releaseId},stage,sourceFilters),[year,period,month,quarter,department,group,queryProducts,drilledProduct,projectGroup,appliedSearch,includeUnassigned,catalog,stage,sourceFilters]);
|
||||
const draft=useMemo(()=>stageProductQuery({year,...(period==='month'?{month}:period==='quarter'?{quarter}:{}),department:encodeQueryValueList(department),group:encodeQueryValueList(group),product:encodeQueryValueList(queryProducts),projectGroup:encodeQueryValueList(projectGroup),productSearch:drilledProduct?undefined:appliedSearch.trim()||undefined,includeUnassigned,view:'product',trendGranularity:'month',releaseId:initial.releaseId||currentReleaseId||catalog?.releaseId},stage,sourceFilters),[year,period,month,quarter,department,group,queryProducts,drilledProduct,projectGroup,appliedSearch,includeUnassigned,catalog,stage,sourceFilters,initial.releaseId,currentReleaseId]);
|
||||
// Apply organizational/source filters directly, like the other query pages. Product text search keeps its explicit submit.
|
||||
useEffect(()=>{if(active&&catalog&&!supportLoading&&!supportError)setApplied(previous=>JSON.stringify(previous)===JSON.stringify(draft)?previous:draft);},[active,catalog,draft,supportLoading,supportError]);
|
||||
const queryKey=JSON.stringify({query:applied,revision});const current=response?.key===queryKey?response.value:null;const error=failure?.key===queryKey?failure.message:'';
|
||||
@@ -56,10 +60,10 @@ export default function StageProductPage({stage,onUnauthorized}:{stage:Stage;onU
|
||||
void api.metrics(applied,controller.signal).then(value=>{if(!controller.signal.aborted)setResponse({key:queryKey,value});}).catch(e=>{if(!controller.signal.aborted&&!onUnauthorized(e))setFailure({key:queryKey,message:e instanceof Error?e.message:'查询失败'});}).finally(()=>{if(!controller.signal.aborted)setLoading(false);});
|
||||
return()=>controller.abort();
|
||||
},[active,queryKey,onUnauthorized,supportError]);
|
||||
useEffect(()=>{if(!active||!applied)return;const bytes=new TextEncoder().encode(JSON.stringify({query:applied}));const encoded=btoa(Array.from(bytes,b=>String.fromCharCode(b)).join('')).replace(/=/g,'').replace(/\+/g,'-').replace(/\//g,'_');const url=`?page=${stage==='black'?'blackProduct':'brightProduct'}&context=${encoded}`;window.history.replaceState({},'',`${location.pathname}${url}`);onLocationChange(url);},[active,applied,stage]);
|
||||
useEffect(()=>{if(!active||!applied)return;const bytes=new TextEncoder().encode(JSON.stringify({query:queryForLocation(applied,initial.releaseId)}));const encoded=btoa(Array.from(bytes,b=>String.fromCharCode(b)).join('')).replace(/=/g,'').replace(/\+/g,'-').replace(/\//g,'_');const url=`?page=${stage==='black'?'blackProduct':'brightProduct'}&context=${encoded}`;window.history.replaceState({},'',`${location.pathname}${url}`);onLocationChange(url);},[active,applied,stage]);
|
||||
const trendQuery=useMemo(()=>applied?{...applied,month:undefined,quarter:undefined,...(trendGranularity==='year'?{year:undefined}:{}),trendGranularity}:null,[applied,trendGranularity]);
|
||||
const trendKey=JSON.stringify({query:trendQuery,revision});
|
||||
useEffect(()=>{if(!active||!current||!trendQuery)return;const controller=new AbortController();setTrendLoading(true);setTrendError('');void api.metrics(trendQuery,controller.signal).then(value=>{if(!controller.signal.aborted)setTrendResponse({key:trendKey,value});}).catch(error=>{if(!controller.signal.aborted&&!onUnauthorized(error))setTrendError(error instanceof Error?error.message:'趋势读取失败');}).finally(()=>{if(!controller.signal.aborted)setTrendLoading(false);});return()=>controller.abort();},[active,trendKey,!!current,onUnauthorized]);
|
||||
useEffect(()=>{if(!active||!trendQuery||supportError)return;const controller=new AbortController();setTrendLoading(true);setTrendError('');void api.trend(trendQuery,controller.signal).then(value=>{if(!controller.signal.aborted)setTrendResponse({key:trendKey,value,query:trendQuery});}).catch(error=>{if(!controller.signal.aborted&&!onUnauthorized(error))setTrendError(error instanceof Error?error.message:'趋势读取失败');}).finally(()=>{if(!controller.signal.aborted)setTrendLoading(false);});return()=>controller.abort();},[active,trendKey,trendRevision,onUnauthorized,supportError]);
|
||||
const visibleTrend=useMemo(()=>fullYearTrend(trendResponse?.key===trendKey?trendResponse.value.trend:[],applied?.year||year,trendGranularity),[trendResponse,trendKey,applied?.year,year,trendGranularity]);
|
||||
const displayedTrend=useRetainedResult(trendResponse?.key===trendKey?visibleTrend:null)||visibleTrend;
|
||||
const selectedTrendPeriod=trendGranularity==='month'&&applied?.month
|
||||
@@ -83,8 +87,9 @@ export default function StageProductPage({stage,onUnauthorized}:{stage:Stage;onU
|
||||
const moreFilterSummary=[projectGroup.length?`项目组:${projectGroup.map(v=>v==='__UNASSIGNED__'?'未分类':v).join('、')}`:'',...sourceFilters.map(rule=>fields.find(field=>field.key===rule.field)?.label||rule.field)].filter(Boolean).join(';');
|
||||
const displayed = useRetainedResult(current && applied ? { data: current, query: applied } : null);
|
||||
const sortedRows=useMemo(()=>sortStageRowsByTotalWeight(displayed?.data.rows||[],stage),[displayed?.data,stage]);
|
||||
const trendRefreshing=trendLoading||!current||trendResponse?.key!==trendKey;
|
||||
const tableReady=!!current&&(!drilledProduct||!trendRefreshing);
|
||||
const trendRefreshing=!trendError&&(trendLoading||trendResponse?.key!==trendKey);
|
||||
const showTrendLoading=useDelayedIndicator(trendRefreshing);
|
||||
const tableReady=!!current&&(!drilledProduct||(trendResponse?.key===trendKey&&!trendLoading&&!trendError));
|
||||
const table=useRetainedResult(tableReady&&applied?{rows:drilledProduct?visibleTrend:sortedRows,query:applied,drilledProduct,period:drilledProduct?'year' as const:applied.month?'month' as const:applied.quarter?'quarter' as const:'year' as const}:null);
|
||||
const summary=displayed?.data.summary[stage];const stageRate=stage==='bright'&&rateBasis==='withoutHeadquartersScrap'?summary?.rateWithoutHeadquartersScrap:summary?.rate;
|
||||
const openDetail=(row:MetricRow|null,_stage:Stage,selectedMonth?:number)=>{if(!applied||!current?.release)return;setRecordVisible(true);setRecords({row,query:{...applied,releaseId:current.release.id,...(row&&selectedMonth==null?{product:row.product||'__UNASSIGNED__'}:{}),...(selectedMonth?{month:selectedMonth,quarter:undefined}: {})}});};
|
||||
@@ -110,7 +115,7 @@ export default function StageProductPage({stage,onUnauthorized}:{stage:Stage;onU
|
||||
{catalog&&<StageSourceFilters stage={stage} fields={fields} query={draft} value={sourceFilters} onChange={setSourceFilters} onUnauthorized={onUnauthorized}/>}
|
||||
</div>}
|
||||
</section>
|
||||
{error&&<Alert showIcon type="error" message="查询失败" description={error} action={<Button onClick={()=>setRevision(v=>v+1)}>重试</Button>}/>}
|
||||
{error&&<Alert showIcon type="error" message={response?"更新失败,当前显示上次结果":"查询失败"} description={error} action={<Button onClick={()=>setRevision(v=>v+1)}>重试</Button>}/>}
|
||||
<section className="metric-strip stage-metric-strip" aria-label="质量指标" aria-busy={loading} inert={!current}>
|
||||
{stage==='bright'&&<div className="rate-basis-control"><Segmented size="small" aria-label="合格率口径" value={rateBasis} options={[{label:'原口径',value:'original'},{label:'去本部报废',value:'withoutHeadquartersScrap'}]} onChange={v=>setRateBasis(v as typeof rateBasis)}/></div>}
|
||||
<MetricCard primary stage={stage} label={`${label}合格率`} value={rate(stageRate)} onClick={()=>setBasisOpen(true)}/>
|
||||
@@ -121,12 +126,12 @@ export default function StageProductPage({stage,onUnauthorized}:{stage:Stage;onU
|
||||
<div className="analysis-stack">
|
||||
<QueryTrendPanel mode={trendMode} onMode={setTrendMode} granularity={trendGranularity} onGranularity={setTrendGranularity}
|
||||
defectDisplay={defectDisplay} onDefectDisplay={setDefectDisplay} object={trendObject} onObject={setTrendObject} objects={trendOptions} scopeName="产品">
|
||||
{trendError&&<Alert type="warning" showIcon message="趋势读取失败" description={trendError} action={<Button onClick={()=>setRevision(v=>v+1)}>重试</Button>}/>}
|
||||
{trendError&&<Alert type="warning" showIcon message={trendResponse?"趋势更新失败,当前显示上次结果":"趋势读取失败"} description={trendResponse?`${trendError};当前范围:${loadedQueryScope(trendResponse.query,decodeQueryValueList)}`:trendError} action={<Button onClick={()=>setTrendRevision(v=>v+1)}>重试</Button>}/>}
|
||||
<div className="trend-chart-shell" aria-busy={trendRefreshing} inert={trendRefreshing||!!trendError}>
|
||||
{trendMode==='data'
|
||||
? <TrendTable rows={displayedTrend} defectDisplay={defectDisplay} rateBasis={rateBasis} onlyStage={stage} onMonth={selectTrendPeriod}/>
|
||||
: <TrendChart rows={displayedTrend} mode={trendMode} stage={stage} onlyStage={stage} rateBasis={rateBasis} targetRate={null} selectedPeriod={selectedTrendPeriod} onMonth={selectTrendPeriod}/>}
|
||||
{trendRefreshing&&<span className="trend-refresh-indicator"><Spin size="small"/>正在更新趋势</span>}
|
||||
{showTrendLoading&&<span className="trend-refresh-indicator"><Spin size="small"/>{trendResponse?`正在更新 · 当前显示上次筛选的${loadedQueryScope(trendResponse.query,decodeQueryValueList)}`:'正在读取趋势'}</span>}
|
||||
</div>
|
||||
</QueryTrendPanel>
|
||||
<QueryTablePanel heading={<SectionHeading title={table?.drilledProduct?'产品月度质量数据':`${label}产品质量汇总`} subtitle={table?.drilledProduct?`${table.query.year} 年 · ${table.drilledProduct==='__UNASSIGNED__'?'未分类':table.drilledProduct} · 重量 / kg 合格率 / %`:'重量 / kg 合格率 / %'}/>}
|
||||
@@ -136,6 +141,7 @@ export default function StageProductPage({stage,onUnauthorized}:{stage:Stage;onU
|
||||
exporting={exporting} exportDisabled={!current||loading||!tableReady||!table?.rows.length} onExport={()=>void runExport()}>
|
||||
<SmoothTableFrame busy={queryBusy||!tableReady} blocked={queryBusy||!tableReady}>
|
||||
<MetricTable ref={exporter} exportFilename={`${table?.drilledProduct||label}产品汇总-${table?.query.year||year}-${fullFields?'完整字段':'关键指标'}`}
|
||||
paginationScope={JSON.stringify({query:table?.query,drilledProduct:table?.drilledProduct})}
|
||||
rows={table?.rows||[]} view={table?.drilledProduct?'overall':'product'} layoutView="product" pageSizeOverride={table?.drilledProduct?12:undefined}
|
||||
period={table?.period||period} month={table?.query.month||month} quarter={table?.query.quarter||quarter}
|
||||
fullFields={fullFields} defectDisplay={defectDisplay} rateBasis={rateBasis} onlyStage={stage} onDetail={openDetail} onBasis={()=>setBasisOpen(true)}
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { usePageCache } from './pageCache';
|
||||
import { useDelayedIndicator } from './useDelayedBusy';
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { Alert, Button, Select, Spin } from 'antd';
|
||||
import { CloseOutlined } from '@ant-design/icons';
|
||||
@@ -7,8 +9,11 @@ import { readableSelectPopup } from './readableSelectPopup';
|
||||
|
||||
function SourceValues({field,stage,query,value,onChange,onUnauthorized}:{field:SourceColumnField;stage:Stage;query:QueryParams;value:string[];onChange:(value:string[])=>void;onUnauthorized:(error:unknown)=>boolean}) {
|
||||
const [search,setSearch]=useState('');const [choices,setChoices]=useState<string[]>([]);const [busy,setBusy]=useState(false);const [error,setError]=useState('');const [more,setMore]=useState(false);const [revision,setRevision]=useState(0);
|
||||
const {active}=usePageCache();
|
||||
const showBusy=useDelayedIndicator(busy);
|
||||
const contextKey=JSON.stringify(query);const current=useRef(0);
|
||||
useEffect(()=>{
|
||||
if(!active)return;
|
||||
const generation=++current.current,controller=new AbortController();setBusy(true);setError('');setChoices([]);
|
||||
const timer=window.setTimeout(()=>{
|
||||
const {year,month,quarter,department,group,product,projectGroup,includeUnassigned,columnFilters,releaseId}=query;
|
||||
@@ -18,8 +23,8 @@ function SourceValues({field,stage,query,value,onChange,onUnauthorized}:{field:S
|
||||
.finally(()=>{if(current.current===generation)setBusy(false);});
|
||||
},search?300:0);
|
||||
return()=>{window.clearTimeout(timer);controller.abort();current.current++;};
|
||||
},[field.key,stage,contextKey,search,revision,onUnauthorized]);
|
||||
return <Select {...readableSelectPopup} mode="multiple" allowClear showSearch aria-label={`${field.label}筛选值`} placeholder="选择筛选值" value={value} searchValue={search} filterOption={false} onSearch={setSearch} loading={busy} maxTagCount="responsive" onChange={values=>{onChange(values);setSearch('');}} options={[...new Set([...choices,...value])].map(v=>({label:v,value:v}))} notFoundContent={busy?<Spin size="small"/>:error?<Button size="small" onClick={()=>setRevision(v=>v+1)}>读取失败,重试</Button>:'暂无匹配值'} popupRender={menu=><>{menu}{more&&<div className="query-options-hint">输入关键词搜索更多值</div>}{error&&<div role="alert" className="query-options-hint">{error}</div>}</>}/>;
|
||||
},[active,field.key,stage,contextKey,search,revision,onUnauthorized]);
|
||||
return <Select {...readableSelectPopup} mode="multiple" allowClear showSearch aria-label={`${field.label}筛选值`} placeholder="选择筛选值" value={value} searchValue={search} filterOption={false} onSearch={setSearch} loading={showBusy} maxTagCount="responsive" onChange={values=>{onChange(values);setSearch('');}} options={[...new Set([...choices,...value])].map(v=>({label:v,value:v}))} notFoundContent={showBusy?<Spin size="small"/>:error?<Button size="small" onClick={()=>setRevision(v=>v+1)}>读取失败,重试</Button>:'暂无匹配值'} popupRender={menu=><>{menu}{more&&<div className="query-options-hint">输入关键词搜索更多值</div>}{error&&<div role="alert" className="query-options-hint">{error}</div>}</>}/>;
|
||||
}
|
||||
export function StageSourceFilters({stage,fields,query,value,onChange,onUnauthorized,part='both'}:{part?:'both'|'picker'|'rows';stage:Stage;fields:SourceColumnField[];query:QueryParams;value:SourceColumnFilter[];onChange:(value:SourceColumnFilter[])=>void;onUnauthorized:(error:unknown)=>boolean}) {
|
||||
const selected=value.map(rule=>rule.field);const patch=(key:string,change:Partial<SourceColumnFilter>)=>onChange(value.map(rule=>rule.field===key?{...rule,...change}:rule));
|
||||
|
||||
@@ -10,6 +10,8 @@ import type { AuthUser } from './types';
|
||||
import { BackupOperationsPanel, OperationsMonitorPanel } from './GovernanceCompletion';
|
||||
import { configurationDateTime } from './configurationName';
|
||||
import { backupSummary, isActive, isFailed, monitorLabel, orderedTasks, taskFailure, taskPercent, type MonitorRow } from './taskMonitorModel';
|
||||
import { useDelayedBusy } from './useDelayedBusy';
|
||||
import { useVisiblePolling } from './useVisiblePolling';
|
||||
|
||||
export function TasksMonitorPage({user,onUnauthorized}:{user:AuthUser;onUnauthorized:(error:unknown)=>boolean}) {
|
||||
const {message}=App.useApp();
|
||||
@@ -18,29 +20,35 @@ export function TasksMonitorPage({user,onUnauthorized}:{user:AuthUser;onUnauthor
|
||||
const [items,setItems]=useState<MonitorRow[]>([]);
|
||||
const [backup,setBackup]=useState<MonitorRow>({});
|
||||
const [taskError,setTaskError]=useState(''); const [backupError,setBackupError]=useState('');
|
||||
const [loading,setLoading]=useState(true);
|
||||
const loaded = useRef(false);
|
||||
const [tasksLoaded,setTasksLoaded]=useState(false); const [backupLoaded,setBackupLoaded]=useState(false);
|
||||
const [section,setSection] = useState('tasks');
|
||||
const taskBusy = useDelayedBusy(); const backupBusy = useDelayedBusy();
|
||||
const loading = sectionLoading();
|
||||
const [filter,setFilter]=useState('all'); const [selected,setSelected]=useState<MonitorRow|null>(null);
|
||||
const actionInFlight = useRef(false);
|
||||
const canManage=user.roles.some(role=>['SYSTEM_ADMIN','SYSTEM_OPERATOR'].includes(role));
|
||||
const load=useCallback(async()=>{
|
||||
setLoading(true);
|
||||
await Promise.all([
|
||||
api.taskOverview().then(value=>{setItems(value.items);setTaskError('');}).catch(error=>{if(!onUnauthorized(error))setTaskError(error instanceof Error?error.message:'任务读取失败');}),
|
||||
api.latestBackup().then(value=>{setBackup(value);setBackupError('');}).catch(error=>{if(!onUnauthorized(error))setBackupError(error instanceof Error?error.message:'备份状态读取失败');}),
|
||||
]);setLoading(false);
|
||||
},[onUnauthorized]);
|
||||
useEffect(()=>{if(!loaded.current){loaded.current=true;void load();}},[load]);
|
||||
function sectionLoading() { return section === 'tasks' ? taskBusy.busy : backupBusy.busy; }
|
||||
const loadTasks=useCallback(()=>taskBusy.run(async()=>{
|
||||
try { const value=await api.taskOverview();setItems(value.items);setTaskError('');setTasksLoaded(true); }
|
||||
catch(error){ if(!onUnauthorized(error))setTaskError(error instanceof Error?error.message:'任务读取失败'); }
|
||||
}),[onUnauthorized,taskBusy.run]);
|
||||
const loadBackup=useCallback(()=>backupBusy.run(async()=>{
|
||||
try { const value=await api.latestBackup();setBackup(value);setBackupError('');setBackupLoaded(true); }
|
||||
catch(error){ if(!onUnauthorized(error))setBackupError(error instanceof Error?error.message:'备份状态读取失败'); }
|
||||
}),[onUnauthorized,backupBusy.run]);
|
||||
const load=useCallback(()=>section==='tasks'?loadTasks():loadBackup(),[section,loadTasks,loadBackup]);
|
||||
useEffect(()=>{if(!active)return;if(section==='tasks'&&!tasksLoaded)void loadTasks();if(section==='latestBackup'&&!backupLoaded)void loadBackup();},[active,section,tasksLoaded,backupLoaded,loadTasks,loadBackup]);
|
||||
useMaintenanceRefresh(load);
|
||||
useEffect(()=>{if(!active || !['tasks','latestBackup'].includes(section))return;const timer=window.setInterval(()=>{if(document.visibilityState==='visible')void load();},15000);return()=>window.clearInterval(timer);},[load,active,section]);
|
||||
useVisiblePolling(load,15000,active&&['tasks','latestBackup'].includes(section));
|
||||
const runAction=async(row:MonitorRow,action:'retry'|'cancel')=>{
|
||||
if(actionInFlight.current)return; actionInFlight.current=true;
|
||||
setBusy(true);
|
||||
try {
|
||||
if(action==='retry') {const releases=await api.releases();await api.retryTask(String(row.id),{idempotencyKey:crypto.randomUUID(),expectedCurrentReleaseId:releases.currentReleaseId??null});}
|
||||
else await api.cancelTask(String(row.id),{expectedStatus:String(row.status)});
|
||||
message.success(action==='retry'?'已提交重试,请查看最新任务状态':'已取消排队任务');setSelected(null);await load();
|
||||
} catch(error){if(!onUnauthorized(error))message.error(error instanceof Error?error.message:'任务操作失败');}
|
||||
finally{setBusy(false);}
|
||||
finally{actionInFlight.current=false;setBusy(false);}
|
||||
};
|
||||
const latest=(backup.latest || {}) as MonitorRow;
|
||||
const columns:ColumnsType<MonitorRow>=[
|
||||
@@ -54,13 +62,14 @@ export function TasksMonitorPage({user,onUnauthorized}:{user:AuthUser;onUnauthor
|
||||
<ManagementSections onSelect={setSection} items={[
|
||||
{ key:'tasks', label:'任务进度', children: <> <section className="panel section-panel">
|
||||
<div className="completion-panel-heading"><strong>任务进度</strong><div className="completion-actions"><Select aria-label="筛选任务" value={filter} onChange={setFilter} options={[{value:'all',label:'全部任务'},{value:'active',label:'进行中'},{value:'failed',label:'失败 / 未完成'},{value:'completed',label:'已完成'}]}/><Button icon={<ReloadOutlined/>} loading={loading} onClick={()=>void load()}>刷新</Button></div></div>
|
||||
{taskError&&<Alert showIcon type="error" message="任务暂不可用" description={taskError}/>}
|
||||
{loading&&!items.length?<Spin/>:!taskError&&<Table size="small" bordered columns={columns} dataSource={orderedTasks(items,filter)} rowKey={row=>`${row.sourceKind}-${row.id}`} pagination={{pageSize:15,showSizeChanger:false}} scroll={{x:1000}} locale={{emptyText:<Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="暂无符合条件的任务"/>}}/>}
|
||||
{taskError&&<Alert showIcon type="error" message="任务暂不可用" description={tasksLoaded?`${taskError};以下为上次成功读取的结果。`:taskError} action={!tasksLoaded?<Button size="small" onClick={()=>void loadTasks()}>重试</Button>:undefined}/>}
|
||||
{loading&&!tasksLoaded?<Spin/>:tasksLoaded&&<Table size="small" bordered columns={columns} dataSource={orderedTasks(items,filter)} rowKey={row=>`${row.sourceKind}-${row.id}`} pagination={{pageSize:15,showSizeChanger:false}} scroll={{x:1000}} locale={{emptyText:<Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="暂无符合条件的任务"/>}}/>}
|
||||
<p className="completion-note">每类最多显示 50 条记录,进行中及失败任务优先。智能分析仅显示本人任务。</p>
|
||||
</section>
|
||||
</> },
|
||||
{ key:'latestBackup', label:'最近备份', children: <> <section className="panel section-panel"><div className="completion-panel-heading"><strong>最近备份状态</strong></div>
|
||||
{backupError?<Alert showIcon type="error" message="备份状态暂不可用" description={backupError}/>:loading&&!latest.createdAt?<Spin/>:<div className="governance-monitor-grid"><div><small>最近备份</small><strong>{backupSummary(latest)}</strong></div><div><small>备份时间</small><strong>{configurationDateTime(latest.createdAt)||'—'}</strong></div><div><small>恢复验证时间</small><strong>{configurationDateTime(latest.restoreVerifiedAt)||'—'}</strong></div><div><small>自动备份</small><strong>{backup.planActive===true?'已启用':'未启用'}</strong></div></div>}
|
||||
{backupError&&<Alert showIcon type="error" message="备份状态暂不可用" description={backupLoaded?`${backupError};以下为上次成功读取的结果。`:backupError} action={!backupLoaded?<Button size="small" onClick={()=>void loadBackup()}>重试</Button>:undefined}/>}
|
||||
{loading&&!backupLoaded?<Spin/>:backupLoaded&&<div className="governance-monitor-grid"><div><small>最近备份</small><strong>{backupSummary(latest)}</strong></div><div><small>备份时间</small><strong>{configurationDateTime(latest.createdAt)||'—'}</strong></div><div><small>恢复验证时间</small><strong>{configurationDateTime(latest.restoreVerifiedAt)||'—'}</strong></div><div><small>自动备份</small><strong>{backup.planActive===true?'已启用':'未启用'}</strong></div></div>}
|
||||
</section>
|
||||
</> },
|
||||
...(canManage ? [{ key:'monitor', label:'运行监控与告警', children:<OperationsMonitorPanel user={user} onUnauthorized={onUnauthorized}/> },{ key:'backups', label:'备份管理', children:<BackupOperationsPanel user={user} onUnauthorized={onUnauthorized}/> }] : []),
|
||||
|
||||
+218
-48
@@ -1,7 +1,15 @@
|
||||
import { WORKSPACE_INVALIDATED } from './pageCache';
|
||||
import { consumeEventStream, type StreamEvent } from './eventStream';
|
||||
import { publicErrorMessage } from './publicDataDisplay';
|
||||
import { RequestTimeoutError, withRequestDeadline } from './requestDeadline';
|
||||
import {
|
||||
clearReadCache,
|
||||
configureRequestScope,
|
||||
coordinateRequest,
|
||||
getRequestDiagnostics,
|
||||
invalidateReadResources,
|
||||
resetRequestScope,
|
||||
type CoordinatedResult,
|
||||
} from './requestCoordinator';
|
||||
import type {
|
||||
AuthUser,
|
||||
FilterField,
|
||||
@@ -9,6 +17,7 @@ import type {
|
||||
Collection,
|
||||
FineDefectTopResponse,
|
||||
MetricsResponse,
|
||||
TrendResponse,
|
||||
OptionsResponse,
|
||||
QueryParams,
|
||||
RecordExportParams,
|
||||
@@ -17,6 +26,8 @@ import type {
|
||||
} from './types';
|
||||
import type { ConfigureSourceBody, DataStage, DataWorkflowOperation, DataWorkflowStatus, MasterWorkbookImportBody, MasterWorkbookPreview, SourceDeletionPreview, SourceUploadOptions, WorkbookPreview } from './NoCodeDataTypes';
|
||||
|
||||
export { configureRequestScope, getRequestDiagnostics, invalidateReadResources, resetRequestScope };
|
||||
|
||||
export class ApiError extends Error {
|
||||
status: number;
|
||||
details: unknown;
|
||||
@@ -39,8 +50,9 @@ async function fetchApi(path: string, init: RequestInit): Promise<Response> {
|
||||
}
|
||||
}
|
||||
|
||||
async function readResponse<T>(response: Response): Promise<T> {
|
||||
async function readResponse<T>(response: Response): Promise<CoordinatedResult<T>> {
|
||||
const raw = await response.text();
|
||||
const responseBytes = new TextEncoder().encode(raw).byteLength;
|
||||
let payload: unknown;
|
||||
if (raw) {
|
||||
try {
|
||||
@@ -61,43 +73,83 @@ async function readResponse<T>(response: Response): Promise<T> {
|
||||
: typeof payload === 'string' && payload.trim()
|
||||
? payload
|
||||
: `请求失败(${response.status})`;
|
||||
throw new ApiError(response.status, message, payload);
|
||||
const error = new ApiError(response.status, message, payload);
|
||||
Object.defineProperty(error, 'responseBytes', { value: responseBytes });
|
||||
throw error;
|
||||
}
|
||||
if (typeof payload === 'string') throw new ApiError(response.status, '服务返回格式异常,请稍后重试。');
|
||||
return payload as T;
|
||||
if (typeof payload === 'string') {
|
||||
const error = new ApiError(response.status, '服务返回格式异常,请稍后重试。');
|
||||
Object.defineProperty(error, 'responseBytes', { value: responseBytes });
|
||||
throw error;
|
||||
}
|
||||
return { data: payload as T, status: response.status, bytes: responseBytes };
|
||||
}
|
||||
|
||||
async function request<T>(path: string, init: RequestInit = {}, timeoutMs?: number): Promise<T> {
|
||||
export async function request<T>(path: string, init: RequestInit = {}, timeoutMs?: number): Promise<T> {
|
||||
const headers = new Headers(init.headers);
|
||||
if (init.body && !(init.body instanceof FormData) && !headers.has('Content-Type')) headers.set('Content-Type', 'application/json');
|
||||
const send = async (signal = init.signal) => {
|
||||
const response = await fetchApi(path, { ...init, signal, headers, credentials: 'same-origin', cache: 'no-store' });
|
||||
return readResponse<T>(response);
|
||||
};
|
||||
if (!timeoutMs) return send();
|
||||
try { return await withRequestDeadline(signal => send(signal), timeoutMs); }
|
||||
const method = (init.method ?? 'GET').toUpperCase();
|
||||
try {
|
||||
return await coordinateRequest({
|
||||
url: path,
|
||||
method,
|
||||
signal: init.signal ?? undefined,
|
||||
timeoutMs: timeoutMs ?? requestTimeoutFor(path),
|
||||
cache: method === 'GET' && isImmutableRead(path),
|
||||
tags: requestResourceTags(path),
|
||||
category: requestCategory(path),
|
||||
priority: requestPriority(path),
|
||||
execute: async signal => {
|
||||
const response = await fetchApi(path, { ...init, signal, headers, credentials: 'same-origin', cache: 'no-store' });
|
||||
return readResponse<T>(response);
|
||||
},
|
||||
});
|
||||
}
|
||||
catch (error) {
|
||||
if (error instanceof RequestTimeoutError) throw new ApiError(408, '连接质量数据服务超时,请点击重新连接;服务恢复后可继续使用。');
|
||||
handleAccessFailure(error);
|
||||
if (error instanceof Error && error.name === 'RequestTimeoutError') throw new ApiError(408, '连接质量数据服务超时,请点击重新连接;服务恢复后可继续使用。');
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async function requestBlob(path: string, signal?: AbortSignal): Promise<{ blob: Blob; filename: string }> {
|
||||
const response = await fetchApi(path, { credentials: 'same-origin', cache: 'no-store', signal });
|
||||
if (!response.ok) {
|
||||
const raw = await response.text();
|
||||
let payload: unknown = raw;
|
||||
try { payload = raw ? JSON.parse(raw) as unknown : undefined; } catch { /* keep plain text */ }
|
||||
const body = payload && typeof payload === 'object' ? payload as Record<string, unknown> : undefined;
|
||||
const message = typeof body?.detail === 'string' ? body.detail : typeof body?.message === 'string' ? body.message : `下载失败(${response.status})`;
|
||||
throw new ApiError(response.status, message, payload);
|
||||
try {
|
||||
return await coordinateRequest({
|
||||
url: path,
|
||||
method: 'GET',
|
||||
signal,
|
||||
timeoutMs: 900_000,
|
||||
queue: false,
|
||||
retry: false,
|
||||
tags: requestResourceTags(path),
|
||||
category: 'export',
|
||||
priority: 'active',
|
||||
execute: async requestSignal => {
|
||||
const response = await fetchApi(path, { credentials: 'same-origin', cache: 'no-store', signal: requestSignal });
|
||||
if (!response.ok) {
|
||||
const raw = await response.text();
|
||||
let payload: unknown = raw;
|
||||
try { payload = raw ? JSON.parse(raw) as unknown : undefined; } catch { /* keep plain text */ }
|
||||
const body = payload && typeof payload === 'object' ? payload as Record<string, unknown> : undefined;
|
||||
const message = typeof body?.detail === 'string' ? body.detail : typeof body?.message === 'string' ? body.message : `下载失败(${response.status})`;
|
||||
const error = new ApiError(response.status, message, payload);
|
||||
Object.defineProperty(error, 'responseBytes', { value: new TextEncoder().encode(raw).byteLength });
|
||||
throw error;
|
||||
}
|
||||
const disposition = response.headers.get('Content-Disposition') || '';
|
||||
const encoded = disposition.match(/filename\*=UTF-8''([^;]+)/i)?.[1];
|
||||
const plain = disposition.match(/filename="?([^";]+)"?/i)?.[1];
|
||||
let filename = 'source-evidence.xlsx';
|
||||
try { filename = encoded ? decodeURIComponent(encoded) : plain || filename; } catch { filename = plain || filename; }
|
||||
const blob = await response.blob();
|
||||
return { data: { blob, filename }, status: response.status, bytes: blob.size };
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
handleAccessFailure(error);
|
||||
if (error instanceof Error && error.name === 'RequestTimeoutError') throw new ApiError(408, '文件导出超时,请稍后重试。');
|
||||
throw error;
|
||||
}
|
||||
const disposition = response.headers.get('Content-Disposition') || '';
|
||||
const encoded = disposition.match(/filename\*=UTF-8''([^;]+)/i)?.[1];
|
||||
const plain = disposition.match(/filename="?([^";]+)"?/i)?.[1];
|
||||
let filename = 'source-evidence.xlsx';
|
||||
try { filename = encoded ? decodeURIComponent(encoded) : plain || filename; } catch { filename = plain || filename; }
|
||||
return { blob: await response.blob(), filename };
|
||||
}
|
||||
|
||||
export type { StreamEvent } from './eventStream';
|
||||
@@ -105,16 +157,21 @@ export type { StreamEvent } from './eventStream';
|
||||
async function readEventStream(path: string, options: { signal?: AbortSignal; lastEventId?: string; onEvent: (event: StreamEvent) => void }): Promise<void> {
|
||||
const headers = new Headers({ Accept: 'text/event-stream' });
|
||||
if (options.lastEventId) headers.set('Last-Event-ID', options.lastEventId);
|
||||
const response = await fetchApi(path, { headers, credentials: 'same-origin', cache: 'no-store', signal: options.signal });
|
||||
if (!response.ok) {
|
||||
const raw = await response.text();
|
||||
let payload: unknown = raw;
|
||||
try { payload = raw ? JSON.parse(raw) as unknown : undefined; } catch { /* keep plain text */ }
|
||||
const body = payload && typeof payload === 'object' ? payload as Record<string, unknown> : undefined;
|
||||
throw new ApiError(response.status, typeof body?.detail === 'string' ? body.detail : typeof body?.message === 'string' ? body.message : `事件流读取失败(${response.status})`, payload);
|
||||
try {
|
||||
const response = await fetchApi(path, { headers, credentials: 'same-origin', cache: 'no-store', signal: options.signal });
|
||||
if (!response.ok) {
|
||||
const raw = await response.text();
|
||||
let payload: unknown = raw;
|
||||
try { payload = raw ? JSON.parse(raw) as unknown : undefined; } catch { /* keep plain text */ }
|
||||
const body = payload && typeof payload === 'object' ? payload as Record<string, unknown> : undefined;
|
||||
throw new ApiError(response.status, typeof body?.detail === 'string' ? body.detail : typeof body?.message === 'string' ? body.message : `事件流读取失败(${response.status})`, payload);
|
||||
}
|
||||
if (!response.body) throw new ApiError(response.status, '浏览器没有收到可读的分析事件流');
|
||||
await consumeEventStream(response.body, options.onEvent);
|
||||
} catch (error) {
|
||||
handleAccessFailure(error);
|
||||
throw error;
|
||||
}
|
||||
if (!response.body) throw new ApiError(response.status, '浏览器没有收到可读的分析事件流');
|
||||
await consumeEventStream(response.body, options.onEvent);
|
||||
}
|
||||
|
||||
export async function refreshCsrf(): Promise<string> {
|
||||
@@ -131,7 +188,7 @@ async function mutate<T>(path: string, body?: unknown, method = 'POST', timeoutM
|
||||
headers,
|
||||
...(body === undefined ? {} : { body: JSON.stringify(body) }),
|
||||
}, timeoutMs);
|
||||
if (!silent && !/^\/api\/(?:analysis|auth)(?:\/|$)/.test(path)) window.dispatchEvent(new Event(WORKSPACE_INVALIDATED));
|
||||
if (!silent && !/^\/api\/(?:analysis|auth)(?:\/|$)/.test(path)) invalidateAfterMutation(path);
|
||||
return result;
|
||||
}
|
||||
|
||||
@@ -142,17 +199,17 @@ async function queryPost<T>(path: string, body: unknown, signal?: AbortSignal):
|
||||
|
||||
async function mutateForm<T>(path: string, body: FormData): Promise<T> {
|
||||
const token = csrfToken ?? await refreshCsrf();
|
||||
const result = await request<T>(path, { method: 'POST', headers: { 'X-XSRF-TOKEN': token }, body });
|
||||
window.dispatchEvent(new Event(WORKSPACE_INVALIDATED));
|
||||
const result = await request<T>(path, { method: 'POST', headers: { 'X-XSRF-TOKEN': token }, body }, 900_000);
|
||||
invalidateAfterMutation(path);
|
||||
return result;
|
||||
}
|
||||
|
||||
export const api = {
|
||||
sourceColumnCatalog(releaseId?: string) { return request<{releaseId:string;sourceFields:SourceColumnField[]}>(`/api/analysis/source/catalog?${toQuery({releaseId})}`); },
|
||||
sourceColumnCatalog(releaseId?: string, signal?: AbortSignal) { return request<{releaseId:string;sourceFields:SourceColumnField[]}>(`/api/analysis/source/catalog?${toQuery({releaseId})}`, { signal }); },
|
||||
sourceColumnValues(body: Record<string,unknown>, signal?: AbortSignal) { return queryPost<{values:Array<string|null>;hasMore?:boolean;total?:number;limit?:number}>('/api/analysis/source/values',body,signal); },
|
||||
workspaceState() { return request<{ authRevision: string; dataRevision: string }>('/api/workspace/state', {}, 8000); },
|
||||
filterFields(manage = false) { return request<FilterField[]>(`/api/filter-fields?manage=${manage}`); },
|
||||
filterFieldOptions(key: string, search = '') { return request<{ values: string[]; hasMore: boolean }>(`/api/filter-fields/options?${toQuery({key, search})}`); },
|
||||
workspaceState() { return request<{ authRevision: string; dataRevision: string; currentReleaseId: string | null }>('/api/workspace/state', {}, 8000); },
|
||||
filterFields(manage = false, signal?: AbortSignal) { return request<FilterField[]>(`/api/filter-fields?manage=${manage}`, { signal }); },
|
||||
filterFieldOptions(key: string, search = '', signal?: AbortSignal) { return request<{ values: string[]; hasMore: boolean }>(`/api/filter-fields/options?${toQuery({key, search})}`, { signal }); },
|
||||
filterFieldColumns() { return request<{ black: string[]; bright: string[] }>('/api/filter-fields/columns'); },
|
||||
saveFilterFields(fields: FilterField[]) { return mutate<FilterField[]>('/api/filter-fields', fields, 'PUT'); },
|
||||
refreshCsrf,
|
||||
@@ -160,17 +217,20 @@ export const api = {
|
||||
const result = await request<{ user: AuthUser }>('/api/auth/me', {}, 8000);
|
||||
return result.user;
|
||||
},
|
||||
login(username: string, password: string) {
|
||||
async login(username: string, password: string) {
|
||||
csrfToken = undefined;
|
||||
resetRequestScope();
|
||||
return mutate<{ user: AuthUser }>('/api/auth/login', { username, password });
|
||||
},
|
||||
logout() {
|
||||
return mutate<void>('/api/auth/logout');
|
||||
async logout() {
|
||||
try { return await mutate<void>('/api/auth/logout'); }
|
||||
finally { csrfToken = undefined; resetRequestScope(); }
|
||||
},
|
||||
changePassword(currentPassword: string, newPassword: string) {
|
||||
return mutate<{ success: boolean }>('/api/auth/change-password', { currentPassword, newPassword });
|
||||
},
|
||||
options() {
|
||||
return request<OptionsResponse>('/api/options');
|
||||
options(signal?: AbortSignal) {
|
||||
return request<OptionsResponse>('/api/options', { signal });
|
||||
},
|
||||
referenceNames() {
|
||||
return request<Pick<OptionsResponse, 'departments' | 'groups' | 'products' | 'projectGroups' | 'groupDepartments'>>('/api/options/reference-names');
|
||||
@@ -178,6 +238,9 @@ export const api = {
|
||||
metrics(params: QueryParams, signal?: AbortSignal) {
|
||||
return request<MetricsResponse>(`/api/metrics?${toQuery(params)}`, { signal });
|
||||
},
|
||||
trend(params: QueryParams, signal?: AbortSignal) {
|
||||
return request<TrendResponse>(`/api/metrics/trend?${toQuery(params)}`, { signal });
|
||||
},
|
||||
fineDefectTop(params: Record<string, unknown>, signal?: AbortSignal) {
|
||||
return queryPost<FineDefectTopResponse>('/api/analysis/defects', params, signal);
|
||||
},
|
||||
@@ -690,6 +753,113 @@ function toQuery(values: object): string {
|
||||
return query.toString();
|
||||
}
|
||||
|
||||
function requestPath(path: string): string {
|
||||
const base = typeof location === 'undefined' ? 'http://localhost' : location.origin;
|
||||
return new URL(path, base).pathname;
|
||||
}
|
||||
|
||||
function requestTimeoutFor(path: string): number | undefined {
|
||||
const pathname = requestPath(path);
|
||||
return pathname === '/api/workspace/state' || pathname === '/api/auth/me' || pathname === '/api/auth/csrf' ? 8_000 : undefined;
|
||||
}
|
||||
|
||||
function isImmutableRead(path: string): boolean {
|
||||
const pathname = requestPath(path);
|
||||
if (pathname === '/api/metrics' || pathname === '/api/metrics/trend') return true;
|
||||
if (pathname === '/api/options' || pathname === '/api/options/reference-names') return true;
|
||||
if (pathname === '/api/analysis/source/catalog' || pathname === '/api/rules/schema') return true;
|
||||
if (/^\/api\/governance\/releases\/[^/]+\/(?:inspect|diff)$/.test(pathname)) return true;
|
||||
if (pathname === '/api/governance/coverage') {
|
||||
const url = new URL(path, typeof location === 'undefined' ? 'http://localhost' : location.origin);
|
||||
return Boolean(url.searchParams.get('releaseId'));
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function requestResourceTags(path: string): string[] {
|
||||
const pathname = requestPath(path);
|
||||
if (pathname.startsWith('/api/metrics')) return ['metrics', 'trend', 'query'];
|
||||
if (pathname.startsWith('/api/options')) return ['options', 'query'];
|
||||
if (pathname.startsWith('/api/filter-fields') || pathname === '/api/analysis/source/catalog') return ['options', 'catalog', 'configuration'];
|
||||
if (pathname.startsWith('/api/records')) return ['records', 'query'];
|
||||
if (pathname.startsWith('/api/analytics/targets')) return ['targets', 'query'];
|
||||
if (pathname.startsWith('/api/sources')) return ['sources', 'workflow', 'catalog'];
|
||||
if (pathname.startsWith('/api/data-workflow')) return ['workflow', 'sources', 'tasks', 'releases'];
|
||||
if (pathname.startsWith('/api/tasks') || pathname.startsWith('/api/import-runs')) return ['tasks', 'workflow'];
|
||||
if (pathname.startsWith('/api/analysis/')) return ['analysis', 'reports', 'options', 'catalog'];
|
||||
if (pathname.startsWith('/api/rules') || pathname.startsWith('/api/mappings') || pathname.startsWith('/api/governance/mapping-issues')) return ['configuration', 'metrics', 'trend', 'records', 'options', 'catalog'];
|
||||
if (pathname.startsWith('/api/governance/backups')) return ['backups', 'monitor', 'workflow'];
|
||||
if (pathname.startsWith('/api/governance/monitor')) return ['monitor', 'workflow'];
|
||||
if (pathname.startsWith('/api/governance/')) return ['configuration', 'workflow', 'sources', 'releases'];
|
||||
if (pathname.startsWith('/api/analytics/')) return ['configuration', 'targets'];
|
||||
if (pathname.startsWith('/api/users') || pathname.startsWith('/api/audit') || pathname.includes('/access-policy') || pathname.includes('/effective-access') || pathname.includes('/scope-preview') || pathname.includes('/service-identities') || pathname.includes('/service-bindings')) return ['access', 'users', 'audit', 'policy'];
|
||||
return [];
|
||||
}
|
||||
|
||||
function requestCategory(path: string): string {
|
||||
const pathname = requestPath(path);
|
||||
if (pathname === '/api/workspace/state') return 'workspace';
|
||||
if (pathname.startsWith('/api/auth/')) return 'auth';
|
||||
if (pathname.startsWith('/api/metrics')) return 'metrics';
|
||||
if (pathname.includes('/export') || pathname.endsWith('/download')) return 'export';
|
||||
if (pathname.startsWith('/api/analysis/')) return 'analysis';
|
||||
if (pathname.startsWith('/api/governance/')) return 'governance';
|
||||
if (pathname.startsWith('/api/tasks') || pathname.startsWith('/api/import-runs')) return 'tasks';
|
||||
if (pathname.startsWith('/api/sources')) return 'sources';
|
||||
if (pathname.startsWith('/api/analytics/')) return 'analytics';
|
||||
return 'other';
|
||||
}
|
||||
|
||||
function requestPriority(path: string): 'active' | 'background' {
|
||||
const pathname = requestPath(path);
|
||||
return pathname.startsWith('/api/data-workflow/operations/') || pathname.startsWith('/api/import-runs/') || pathname.startsWith('/api/tasks/')
|
||||
? 'background'
|
||||
: 'active';
|
||||
}
|
||||
|
||||
function mutationResources(path: string): string[] | null {
|
||||
const pathname = requestPath(path);
|
||||
if (pathname.startsWith('/api/auth/') || pathname.startsWith('/api/analysis/')) return [];
|
||||
if (pathname.startsWith('/api/users') || pathname.startsWith('/api/audit') || pathname.includes('/access-policy') || pathname.includes('/effective-access') || pathname.includes('/scope-preview') || pathname.includes('/service-identities') || pathname.includes('/service-bindings')) return ['*'];
|
||||
if (pathname.startsWith('/api/sources') || pathname.startsWith('/api/releases') || pathname.startsWith('/api/data-workflow') || pathname.startsWith('/api/import-runs')) {
|
||||
return ['metrics', 'trend', 'records', 'options', 'catalog', 'sources', 'workflow', 'tasks', 'releases', 'configuration'];
|
||||
}
|
||||
if (pathname.startsWith('/api/filter-fields')) return ['options', 'catalog', 'query', 'configuration'];
|
||||
if (pathname.startsWith('/api/rules') || pathname.startsWith('/api/mappings') || pathname.startsWith('/api/governance/mapping-issues') || pathname.startsWith('/api/metric-dictionary')) {
|
||||
return ['metrics', 'trend', 'records', 'options', 'catalog', 'configuration'];
|
||||
}
|
||||
if (pathname.startsWith('/api/tasks')) return ['tasks', 'workflow'];
|
||||
if (pathname.startsWith('/api/governance/backups')) return ['backups', 'monitor', 'workflow', 'configuration'];
|
||||
if (pathname.startsWith('/api/governance/monitor')) return ['monitor', 'workflow', 'configuration'];
|
||||
if (pathname.startsWith('/api/analytics/targets')) return ['targets', 'configuration'];
|
||||
if (pathname.startsWith('/api/analytics/')) return ['configuration'];
|
||||
if (pathname.startsWith('/api/governance/')) return ['configuration', 'workflow', 'sources', 'releases'];
|
||||
if (pathname.startsWith('/api/')) return null;
|
||||
return null;
|
||||
}
|
||||
|
||||
function invalidateAfterMutation(path: string): void {
|
||||
const resources = mutationResources(path);
|
||||
if (resources?.length === 0) return;
|
||||
const invalidated = resources ?? ['*'];
|
||||
invalidateReadResources(resources?.includes('*') ? undefined : resources ?? undefined);
|
||||
window.dispatchEvent(new CustomEvent(WORKSPACE_INVALIDATED, { detail: { resources: invalidated } }));
|
||||
}
|
||||
|
||||
function hasStatus(error: unknown, status: number): boolean {
|
||||
return !!error && typeof error === 'object' && (error as { status?: unknown }).status === status;
|
||||
}
|
||||
|
||||
function handleAccessFailure(error: unknown): void {
|
||||
if (hasStatus(error, 401)) {
|
||||
csrfToken = undefined;
|
||||
resetRequestScope();
|
||||
} else if (hasStatus(error, 403)) {
|
||||
clearReadCache();
|
||||
window.dispatchEvent(new Event('quality-permission-recheck'));
|
||||
}
|
||||
}
|
||||
|
||||
const MULTI_VALUE_MARKER = '~qv1~';
|
||||
|
||||
/** Encodes multiple selected values into the scalar query wire format understood by the API. */
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
export type GovernanceResource = 'coverage' | 'protocols' | 'changes' | 'candidates' | 'documents';
|
||||
export type GovernanceFreshness = Partial<Record<GovernanceResource, boolean>>;
|
||||
|
||||
export const GOVERNANCE_RESOURCES: GovernanceResource[] = ['coverage', 'protocols', 'changes', 'candidates', 'documents'];
|
||||
|
||||
const TAB_RESOURCES: Record<string, GovernanceResource[]> = {
|
||||
coverage: ['coverage'],
|
||||
protocols: ['protocols'],
|
||||
changes: ['changes', 'candidates'],
|
||||
revisions: ['documents'],
|
||||
};
|
||||
|
||||
export function governanceResourcesForTab(tab: string): GovernanceResource[] {
|
||||
return TAB_RESOURCES[tab] || [];
|
||||
}
|
||||
|
||||
export function markGovernanceResourcesStale(
|
||||
current: GovernanceFreshness,
|
||||
resources: GovernanceResource[] = GOVERNANCE_RESOURCES,
|
||||
): GovernanceFreshness {
|
||||
return resources.reduce((next, resource) => ({ ...next, [resource]: true }), { ...current });
|
||||
}
|
||||
|
||||
export function markGovernanceResourcesFresh(current: GovernanceFreshness, resources: GovernanceResource[]): GovernanceFreshness {
|
||||
return resources.reduce((next, resource) => ({ ...next, [resource]: false }), { ...current });
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
export function importIssuePageKey(runId: string, page: number): string {
|
||||
return `${runId}:${page}`;
|
||||
}
|
||||
|
||||
export function matchesImportIssuePage(loadedRunId: string, loadedPage: number, runId: string, page: number): boolean {
|
||||
return loadedRunId === runId && loadedPage === page;
|
||||
}
|
||||
|
||||
export async function runImportPollFollowup<T>(
|
||||
runId: string,
|
||||
isCurrent: (runId: string) => boolean,
|
||||
followup: () => Promise<T>,
|
||||
): Promise<{ started: false; current: false } | { started: true; current: boolean; value: T }> {
|
||||
if (!isCurrent(runId)) return { started: false, current: false };
|
||||
const value = await followup();
|
||||
return { started: true, current: isCurrent(runId), value };
|
||||
}
|
||||
@@ -1,7 +1,12 @@
|
||||
import { createContext, useContext, useEffect, useRef } from 'react';
|
||||
|
||||
export const WORKSPACE_INVALIDATED = 'quality-workspace-invalidated';
|
||||
export const PageCacheContext = createContext({ active: true, initialSearch: undefined as string | undefined, refreshKey: 0, onLocationChange: (_search: string) => {} });
|
||||
export type PageCacheState = {
|
||||
active: boolean; initialSearch?: string; refreshKey: number;
|
||||
currentReleaseId?: string | null; authRevision?: string; dataRevision?: string;
|
||||
onLocationChange: (search: string) => void;
|
||||
};
|
||||
export const PageCacheContext = createContext<PageCacheState>({ active: true, refreshKey: 0, onLocationChange: () => {} });
|
||||
export const usePageCache = () => useContext(PageCacheContext);
|
||||
|
||||
/** Revalidate retained maintenance data on a real revision change, not on every visit. */
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
import type { QueryParams } from './types';
|
||||
|
||||
export function loadedQueryPeriod(query: Pick<QueryParams, 'year' | 'month' | 'quarter'>): string {
|
||||
if (query.year == null) return '全部年份';
|
||||
return query.month ? `${query.year}年${String(query.month).padStart(2, '0')}月`
|
||||
: query.quarter ? `${query.year}年第${query.quarter}季度` : `${query.year}年全年`;
|
||||
}
|
||||
|
||||
|
||||
/** Request snapshots follow the workspace unless the incoming link explicitly pins a release. */
|
||||
export function queryForLocation(query: QueryParams, explicitReleaseId?: string): QueryParams {
|
||||
const { releaseId: _boundRelease, ...filters } = query;
|
||||
return explicitReleaseId ? { ...filters, releaseId: explicitReleaseId } : filters;
|
||||
}
|
||||
|
||||
export function readQueryLocation(search = window.location.search): Partial<QueryParams> {
|
||||
const context = new URLSearchParams(search).get('context');
|
||||
if (!context) return {};
|
||||
try {
|
||||
const binary = atob(context.replace(/-/g, '+').replace(/_/g, '/') + '='.repeat((4 - context.length % 4) % 4));
|
||||
const parsed = JSON.parse(new TextDecoder().decode(Uint8Array.from(binary, character => character.charCodeAt(0)))) as { query?: unknown };
|
||||
if (!parsed.query || typeof parsed.query !== 'object') return {};
|
||||
const query = { ...(parsed.query as Partial<QueryParams>) };
|
||||
return query;
|
||||
} catch { return {}; }
|
||||
}
|
||||
|
||||
|
||||
/** Keep the applied scope readable while the controls already show a newer draft. */
|
||||
export function loadedQueryScope(query: QueryParams, decode: (value: string | undefined) => string[]): string {
|
||||
const selections = [query.department, query.group, query.product, query.projectGroup]
|
||||
.flatMap(value => decode(value)).map(value => value === '__UNASSIGNED__' ? '未分类' : value);
|
||||
const sourceCount = (query.columnFilters?.length || 0) + Object.keys(query.extraFilters || {}).length;
|
||||
return [loadedQueryPeriod(query), ...selections, query.productSearch ? `搜索:${query.productSearch}` : '', sourceCount ? `来源条件 ${sourceCount} 项` : ''].filter(Boolean).join(' · ');
|
||||
}
|
||||
@@ -0,0 +1,457 @@
|
||||
export interface RequestScope {
|
||||
userId: string | null;
|
||||
authRevision: string | null;
|
||||
dataRevision: string | null;
|
||||
currentReleaseId: string | null;
|
||||
}
|
||||
|
||||
export interface CoordinatedResult<T> {
|
||||
data: T;
|
||||
status?: number;
|
||||
bytes?: number;
|
||||
}
|
||||
|
||||
export interface CoordinatedRequest<T> {
|
||||
url: string;
|
||||
method?: string;
|
||||
signal?: AbortSignal;
|
||||
timeoutMs?: number;
|
||||
cache?: boolean;
|
||||
queue?: boolean;
|
||||
retry?: boolean;
|
||||
tags?: readonly string[];
|
||||
category?: string;
|
||||
priority?: 'active' | 'background';
|
||||
execute: (signal: AbortSignal) => Promise<CoordinatedResult<T>>;
|
||||
}
|
||||
|
||||
export interface RequestDiagnostic {
|
||||
category: string;
|
||||
elapsedMs: number;
|
||||
bytes: number;
|
||||
status: number | null;
|
||||
retries: number;
|
||||
}
|
||||
|
||||
export const REQUEST_CACHE_LIMIT_BYTES = 32 * 1024 * 1024;
|
||||
export const REQUEST_MAX_GET_CONCURRENCY = 4;
|
||||
const DEFAULT_GET_TIMEOUT_MS = 30_000;
|
||||
const RETRY_DELAY_MS = 1_000;
|
||||
const MAX_DIAGNOSTICS = 120;
|
||||
|
||||
export class RequestTimeoutError extends Error {
|
||||
constructor() {
|
||||
super('请求超时');
|
||||
this.name = 'RequestTimeoutError';
|
||||
}
|
||||
}
|
||||
|
||||
interface CacheEntry {
|
||||
data: unknown;
|
||||
bytes: number;
|
||||
tags: readonly string[];
|
||||
}
|
||||
|
||||
interface Subscriber<T = unknown> {
|
||||
resolve: (value: T) => void;
|
||||
reject: (error: unknown) => void;
|
||||
signal?: AbortSignal;
|
||||
abortListener?: () => void;
|
||||
}
|
||||
|
||||
interface Flight<T = unknown> {
|
||||
key: string;
|
||||
url: string;
|
||||
scopeKey: string;
|
||||
scopeEpoch: number;
|
||||
cacheEpoch: number;
|
||||
controller: AbortController;
|
||||
subscribers: Set<Subscriber<T>>;
|
||||
request: CoordinatedRequest<T>;
|
||||
startedAt: number;
|
||||
deadlineAt: number;
|
||||
timer?: ReturnType<typeof setTimeout>;
|
||||
retries: number;
|
||||
queued: boolean;
|
||||
slotHeld: boolean;
|
||||
settled: boolean;
|
||||
}
|
||||
|
||||
let scope: RequestScope = { userId: null, authRevision: null, dataRevision: null, currentReleaseId: null };
|
||||
let scopeKey = serializeScope(scope);
|
||||
let scopeEpoch = 0;
|
||||
let cacheEpoch = 0;
|
||||
let activeGets = 0;
|
||||
let cacheBytes = 0;
|
||||
const flights = new Map<string, Flight<any>>();
|
||||
const queue: Flight<any>[] = [];
|
||||
const cache = new Map<string, CacheEntry>();
|
||||
const diagnostics: RequestDiagnostic[] = [];
|
||||
const directControllers = new Set<AbortController>();
|
||||
|
||||
export function configureRequestScope(next: RequestScope): void {
|
||||
const normalized: RequestScope = {
|
||||
userId: next.userId ?? null,
|
||||
authRevision: next.authRevision ?? null,
|
||||
dataRevision: next.dataRevision ?? null,
|
||||
currentReleaseId: next.currentReleaseId ?? null,
|
||||
};
|
||||
const nextKey = serializeScope(normalized);
|
||||
if (nextKey === scopeKey) return;
|
||||
scope = normalized;
|
||||
scopeKey = nextKey;
|
||||
scopeEpoch += 1;
|
||||
clearCache();
|
||||
for (const flight of [...flights.values()]) abortFlight(flight, createAbortError());
|
||||
for (const controller of directControllers) controller.abort();
|
||||
drainQueue();
|
||||
}
|
||||
|
||||
export function invalidateReadResources(tags?: readonly string[]): void {
|
||||
const selected = tags ? new Set(tags) : null;
|
||||
for (const [key, entry] of cache) {
|
||||
if (!selected || entry.tags.some(tag => selected.has(tag))) {
|
||||
cacheBytes -= entry.bytes;
|
||||
cache.delete(key);
|
||||
}
|
||||
}
|
||||
for (const flight of [...flights.values()]) {
|
||||
if (!selected || flight.request.tags?.some(tag => selected.has(tag))) abortFlight(flight, createAbortError());
|
||||
}
|
||||
drainQueue();
|
||||
}
|
||||
|
||||
/** Clears private response data without interrupting unrelated active reads. */
|
||||
export function clearReadCache(): void {
|
||||
clearCache();
|
||||
}
|
||||
|
||||
export function resetRequestScope(): void {
|
||||
scope = { userId: null, authRevision: null, dataRevision: null, currentReleaseId: null };
|
||||
scopeKey = serializeScope(scope);
|
||||
scopeEpoch += 1;
|
||||
clearCache();
|
||||
for (const flight of [...flights.values()]) abortFlight(flight, createAbortError());
|
||||
for (const controller of directControllers) controller.abort();
|
||||
drainQueue();
|
||||
}
|
||||
|
||||
export function coordinateRequest<T>(request: CoordinatedRequest<T>): Promise<T> {
|
||||
const method = (request.method ?? 'GET').toUpperCase();
|
||||
if (request.signal?.aborted) return Promise.reject(createAbortError());
|
||||
if (method !== 'GET' || request.queue === false) return runDirect(request);
|
||||
|
||||
const normalizedUrl = normalizeUrl(request.url);
|
||||
const flightKey = `${scopeEpoch}\u0000${scopeKey}\u0000${normalizedUrl}`;
|
||||
if (request.cache) {
|
||||
const cached = cache.get(flightKey);
|
||||
if (cached) {
|
||||
cache.delete(flightKey);
|
||||
cache.set(flightKey, cached);
|
||||
recordDiagnostic(request.category ?? categoryFromUrl(normalizedUrl), 0, cached.bytes, 200, 0);
|
||||
return Promise.resolve(cloneValue(cached.data) as T);
|
||||
}
|
||||
}
|
||||
|
||||
const existing = flights.get(flightKey) as Flight<T> | undefined;
|
||||
if (existing && !existing.settled) return subscribe(existing, request.signal);
|
||||
|
||||
const timeoutMs = request.timeoutMs ?? DEFAULT_GET_TIMEOUT_MS;
|
||||
const flight: Flight<T> = {
|
||||
key: flightKey,
|
||||
url: normalizedUrl,
|
||||
scopeKey,
|
||||
scopeEpoch,
|
||||
cacheEpoch,
|
||||
controller: new AbortController(),
|
||||
subscribers: new Set(),
|
||||
request: { ...request, method },
|
||||
startedAt: Date.now(),
|
||||
deadlineAt: Date.now() + timeoutMs,
|
||||
retries: 0,
|
||||
queued: true,
|
||||
slotHeld: false,
|
||||
settled: false,
|
||||
};
|
||||
flights.set(flightKey, flight);
|
||||
const subscriber = subscribe(flight, request.signal);
|
||||
flight.timer = setTimeout(() => {
|
||||
abortFlight(flight, new RequestTimeoutError());
|
||||
}, timeoutMs);
|
||||
queue.push(flight);
|
||||
drainQueue();
|
||||
return subscriber;
|
||||
}
|
||||
|
||||
export function getRequestDiagnostics(): readonly RequestDiagnostic[] {
|
||||
return diagnostics.map(item => ({ ...item }));
|
||||
}
|
||||
|
||||
export function clearRequestDiagnostics(): void {
|
||||
diagnostics.length = 0;
|
||||
}
|
||||
|
||||
function subscribe<T>(flight: Flight<T>, signal?: AbortSignal): Promise<T> {
|
||||
return new Promise<T>((resolve, reject) => {
|
||||
const subscriber: Subscriber<T> = { resolve, reject, signal };
|
||||
if (signal?.aborted) {
|
||||
reject(createAbortError());
|
||||
return;
|
||||
}
|
||||
subscriber.abortListener = () => {
|
||||
removeSubscriber(flight, subscriber);
|
||||
reject(createAbortError());
|
||||
if (flight.subscribers.size === 0) abortFlight(flight, createAbortError());
|
||||
};
|
||||
signal?.addEventListener('abort', subscriber.abortListener, { once: true });
|
||||
flight.subscribers.add(subscriber);
|
||||
});
|
||||
}
|
||||
|
||||
function removeSubscriber<T>(flight: Flight<T>, subscriber: Subscriber<T>): void {
|
||||
flight.subscribers.delete(subscriber);
|
||||
if (subscriber.signal && subscriber.abortListener) subscriber.signal.removeEventListener('abort', subscriber.abortListener);
|
||||
}
|
||||
|
||||
function drainQueue(): void {
|
||||
if (activeGets >= REQUEST_MAX_GET_CONCURRENCY || queue.length === 0) return;
|
||||
queue.sort((left, right) => {
|
||||
const priority = Number(right.request.priority !== 'background') - Number(left.request.priority !== 'background');
|
||||
return priority || left.startedAt - right.startedAt;
|
||||
});
|
||||
while (activeGets < REQUEST_MAX_GET_CONCURRENCY && queue.length > 0) {
|
||||
const flight = queue.shift()!;
|
||||
if (flight.settled || flight.subscribers.size === 0) continue;
|
||||
flight.queued = false;
|
||||
flight.slotHeld = true;
|
||||
activeGets += 1;
|
||||
void executeFlight(flight);
|
||||
}
|
||||
}
|
||||
|
||||
async function executeFlight(flight: Flight<any>): Promise<void> {
|
||||
const request = flight.request;
|
||||
let status: number | null = null;
|
||||
let bytes = 0;
|
||||
try {
|
||||
const result = await executeWithRetry(flight);
|
||||
status = result.status ?? 200;
|
||||
bytes = result.bytes ?? estimateBytes(result.data);
|
||||
if (flight.settled) return;
|
||||
if (!isCurrentScope(flight)) throw createAbortError();
|
||||
if (request.cache && flight.cacheEpoch === cacheEpoch) putCache(flight.key, { data: cloneValue(result.data), bytes, tags: request.tags ?? [] });
|
||||
settleFlight(flight, undefined, result.data);
|
||||
} catch (error) {
|
||||
status = readStatus(error);
|
||||
bytes = readBytes(error);
|
||||
if (!flight.settled) settleFlight(flight, error);
|
||||
} finally {
|
||||
if (flight.timer) clearTimeout(flight.timer);
|
||||
flight.timer = undefined;
|
||||
releaseSlot(flight);
|
||||
recordDiagnostic(request.category ?? categoryFromUrl(flight.url), Date.now() - flight.startedAt, bytes, status, flight.retries);
|
||||
drainQueue();
|
||||
}
|
||||
}
|
||||
|
||||
async function executeWithRetry(flight: Flight<any>): Promise<CoordinatedResult<any>> {
|
||||
for (;;) {
|
||||
if (flight.controller.signal.aborted) throw createAbortError();
|
||||
try {
|
||||
const result = await flight.request.execute(flight.controller.signal);
|
||||
if (flight.controller.signal.aborted) throw createAbortError();
|
||||
return result;
|
||||
} catch (error) {
|
||||
if (flight.controller.signal.aborted || flight.request.retry === false || flight.retries >= 1 || !isRetryable(error)) throw error;
|
||||
flight.retries += 1;
|
||||
await delay(RETRY_DELAY_MS, flight.controller.signal);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function runDirect<T>(request: CoordinatedRequest<T>): Promise<T> {
|
||||
const startedAt = Date.now(), ownerEpoch = scopeEpoch;
|
||||
const controller = new AbortController();
|
||||
directControllers.add(controller);
|
||||
let timedOut = false;
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
let status: number | null = null;
|
||||
let bytes = 0;
|
||||
let rejectCancellation: (error: Error) => void = () => {};
|
||||
const cancelled = new Promise<never>((_, reject) => { rejectCancellation = reject; });
|
||||
const onCancelled = () => rejectCancellation(createAbortError());
|
||||
controller.signal.addEventListener('abort', onCancelled, { once: true });
|
||||
const abortListener = () => controller.abort();
|
||||
request.signal?.addEventListener('abort', abortListener, { once: true });
|
||||
if (request.signal?.aborted) controller.abort();
|
||||
try {
|
||||
if (controller.signal.aborted) throw createAbortError();
|
||||
if (request.timeoutMs && request.timeoutMs > 0) {
|
||||
timer = setTimeout(() => {
|
||||
timedOut = true;
|
||||
controller.abort();
|
||||
}, request.timeoutMs);
|
||||
}
|
||||
const result = await Promise.race([request.execute(controller.signal), cancelled]);
|
||||
if (controller.signal.aborted || ownerEpoch !== scopeEpoch) throw createAbortError();
|
||||
status = result.status ?? 200;
|
||||
bytes = result.bytes ?? estimateBytes(result.data);
|
||||
return result.data;
|
||||
} catch (error) {
|
||||
status = readStatus(error);
|
||||
bytes = readBytes(error);
|
||||
if (timedOut) throw new RequestTimeoutError();
|
||||
throw error;
|
||||
} finally {
|
||||
if (timer) clearTimeout(timer);
|
||||
directControllers.delete(controller);
|
||||
controller.signal.removeEventListener('abort', onCancelled);
|
||||
request.signal?.removeEventListener('abort', abortListener);
|
||||
recordDiagnostic(request.category ?? categoryFromUrl(request.url), Date.now() - startedAt, bytes, status, 0);
|
||||
}
|
||||
}
|
||||
|
||||
function settleFlight(flight: Flight<any>, error?: unknown, value?: unknown): void {
|
||||
if (flight.settled) return;
|
||||
flight.settled = true;
|
||||
if (flight.timer) clearTimeout(flight.timer);
|
||||
flight.timer = undefined;
|
||||
flights.delete(flight.key);
|
||||
if (flight.queued) {
|
||||
const index = queue.indexOf(flight);
|
||||
if (index >= 0) queue.splice(index, 1);
|
||||
flight.queued = false;
|
||||
}
|
||||
const subscribers = [...flight.subscribers];
|
||||
flight.subscribers.clear();
|
||||
for (const subscriber of subscribers) {
|
||||
if (subscriber.signal && subscriber.abortListener) subscriber.signal.removeEventListener('abort', subscriber.abortListener);
|
||||
if (error !== undefined) subscriber.reject(error);
|
||||
else subscriber.resolve(value as any);
|
||||
}
|
||||
}
|
||||
|
||||
function abortFlight(flight: Flight<any>, error: unknown): void {
|
||||
if (flight.settled) return;
|
||||
flight.controller.abort();
|
||||
settleFlight(flight, error);
|
||||
releaseSlot(flight);
|
||||
}
|
||||
|
||||
function releaseSlot(flight: Flight<any>): void {
|
||||
if (!flight.slotHeld) return;
|
||||
flight.slotHeld = false;
|
||||
activeGets = Math.max(0, activeGets - 1);
|
||||
}
|
||||
|
||||
function isCurrentScope(flight: Flight<any>): boolean {
|
||||
return flight.scopeEpoch === scopeEpoch && flight.scopeKey === scopeKey;
|
||||
}
|
||||
|
||||
function putCache(key: string, entry: CacheEntry): void {
|
||||
const safeBytes = Math.max(0, Number.isFinite(entry.bytes) ? entry.bytes : estimateBytes(entry.data));
|
||||
if (safeBytes > REQUEST_CACHE_LIMIT_BYTES) return;
|
||||
const previous = cache.get(key);
|
||||
if (previous) cacheBytes -= previous.bytes;
|
||||
cache.delete(key);
|
||||
cache.set(key, { ...entry, bytes: safeBytes });
|
||||
cacheBytes += safeBytes;
|
||||
while (cacheBytes > REQUEST_CACHE_LIMIT_BYTES && cache.size > 0) {
|
||||
const oldestKey = cache.keys().next().value as string | undefined;
|
||||
if (oldestKey === undefined) break;
|
||||
const oldest = cache.get(oldestKey)!;
|
||||
cache.delete(oldestKey);
|
||||
cacheBytes -= oldest.bytes;
|
||||
}
|
||||
}
|
||||
|
||||
function clearCache(): void {
|
||||
cache.clear();
|
||||
cacheBytes = 0;
|
||||
cacheEpoch += 1;
|
||||
}
|
||||
|
||||
function estimateBytes(value: unknown): number {
|
||||
try { return new TextEncoder().encode(JSON.stringify(value) ?? '').byteLength; }
|
||||
catch { return 0; }
|
||||
}
|
||||
|
||||
function cloneValue(value: unknown): unknown {
|
||||
if (typeof structuredClone === 'function') return structuredClone(value);
|
||||
return value;
|
||||
}
|
||||
|
||||
function recordDiagnostic(category: string, elapsedMs: number, bytes: number, status: number | null, retries: number): void {
|
||||
diagnostics.push({ category, elapsedMs: Math.max(0, elapsedMs), bytes: Math.max(0, bytes), status, retries });
|
||||
if (diagnostics.length > MAX_DIAGNOSTICS) diagnostics.splice(0, diagnostics.length - MAX_DIAGNOSTICS);
|
||||
}
|
||||
|
||||
function isRetryable(error: unknown): boolean {
|
||||
if (!error || typeof error !== 'object') return false;
|
||||
if ((error as { name?: unknown }).name === 'AbortError' || (error as { name?: unknown }).name === 'RequestTimeoutError') return false;
|
||||
const status = readStatus(error);
|
||||
return error instanceof TypeError || status === 0 || status === 502 || status === 503 || status === 504;
|
||||
}
|
||||
|
||||
function readStatus(error: unknown): number | null {
|
||||
if (!error || typeof error !== 'object') return null;
|
||||
const status = (error as { status?: unknown }).status;
|
||||
return typeof status === 'number' && Number.isFinite(status) ? status : null;
|
||||
}
|
||||
|
||||
function readBytes(error: unknown): number {
|
||||
if (!error || typeof error !== 'object') return 0;
|
||||
const bytes = (error as { responseBytes?: unknown }).responseBytes;
|
||||
return typeof bytes === 'number' && Number.isFinite(bytes) ? bytes : 0;
|
||||
}
|
||||
|
||||
function delay(ms: number, signal: AbortSignal): Promise<void> {
|
||||
return new Promise((resolve, reject) => {
|
||||
if (signal.aborted) { reject(createAbortError()); return; }
|
||||
const timer = setTimeout(() => {
|
||||
signal.removeEventListener('abort', onAbort);
|
||||
resolve();
|
||||
}, ms);
|
||||
const onAbort = () => {
|
||||
clearTimeout(timer);
|
||||
signal.removeEventListener('abort', onAbort);
|
||||
reject(createAbortError());
|
||||
};
|
||||
signal.addEventListener('abort', onAbort, { once: true });
|
||||
});
|
||||
}
|
||||
|
||||
function normalizeUrl(value: string): string {
|
||||
const base = typeof location === 'undefined' ? 'http://localhost' : location.origin;
|
||||
const url = new URL(value, base);
|
||||
const params = [...url.searchParams.entries()].sort(([leftKey, leftValue], [rightKey, rightValue]) =>
|
||||
leftKey.localeCompare(rightKey) || leftValue.localeCompare(rightValue));
|
||||
const normalized = new URLSearchParams();
|
||||
for (const [key, item] of params) normalized.append(key, item);
|
||||
return `${url.pathname}${normalized.size ? `?${normalized.toString()}` : ''}`;
|
||||
}
|
||||
|
||||
function serializeScope(value: RequestScope): string {
|
||||
return JSON.stringify([value.userId, value.authRevision, value.dataRevision, value.currentReleaseId]);
|
||||
}
|
||||
|
||||
function categoryFromUrl(value: string): string {
|
||||
const pathname = new URL(value, 'http://localhost').pathname;
|
||||
if (pathname === '/api/workspace/state') return 'workspace';
|
||||
if (pathname.startsWith('/api/auth/')) return 'auth';
|
||||
if (pathname.startsWith('/api/metrics')) return 'metrics';
|
||||
if (pathname.includes('/export')) return 'export';
|
||||
if (pathname.startsWith('/api/analysis/')) return 'analysis';
|
||||
if (pathname.startsWith('/api/governance/')) return 'governance';
|
||||
if (pathname.startsWith('/api/tasks')) return 'tasks';
|
||||
if (pathname.startsWith('/api/sources')) return 'sources';
|
||||
if (pathname.startsWith('/api/analytics/')) return 'analytics';
|
||||
return 'other';
|
||||
}
|
||||
|
||||
function createAbortError(): Error {
|
||||
if (typeof DOMException !== 'undefined') return new DOMException('请求已取消', 'AbortError');
|
||||
const error = new Error('请求已取消');
|
||||
error.name = 'AbortError';
|
||||
return error;
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
/** 仅唤醒依赖这些资源的页面;未知写操作按全局失效处理。 */
|
||||
export function pageUsesResources(page: string, resources?: string[]): boolean {
|
||||
if (!resources?.length || resources.includes('*')) return true;
|
||||
const query = ['overall', 'department', 'group', 'product', 'blackProduct', 'brightProduct'].includes(page);
|
||||
const dependencies = query ? ['metrics', 'trend', 'records', 'options', 'catalog', 'targets', 'query']
|
||||
: page === 'analysis' ? ['analysis', 'options', 'reports', 'catalog']
|
||||
: page === 'sources' || page === 'imports' ? ['sources', 'workflow', 'tasks', 'releases']
|
||||
: page === 'tasks' ? ['tasks', 'workflow', 'backups', 'monitor']
|
||||
: page === 'access' ? ['access', 'users', 'audit', 'policy']
|
||||
: [page, 'configuration', 'workflow'];
|
||||
return resources.some(resource => dependencies.includes(resource));
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import type { DataField, DataStage, WorkbookPreview } from './NoCodeDataTypes';
|
||||
|
||||
type Candidate = { workbook: WorkbookPreview; stage: DataStage; score: number; matched: number };
|
||||
|
||||
function identify(workbook: WorkbookPreview, fields: Record<DataStage, DataField[]>): Candidate {
|
||||
return (['black', 'bright'] as DataStage[]).map(stage => {
|
||||
const required = fields[stage].filter(field => field.required);
|
||||
const matched = required.filter(field => workbook.preview.headers.includes(field.name)).length;
|
||||
return { workbook, stage, matched, score: required.length ? matched / required.length : 0 };
|
||||
}).sort((a, b) => b.score - a.score || b.matched - a.matched)[0];
|
||||
}
|
||||
|
||||
/** 按业务字段比较各工作表,避免把排在明细前面的汇总页当作导入来源。 */
|
||||
export async function detectSourceWorkbook(
|
||||
initial: WorkbookPreview,
|
||||
fields: Record<DataStage, DataField[]>,
|
||||
preview: (uploadId: string, params: { sheetName: string; headerRow: number; stage: DataStage }) => Promise<WorkbookPreview>,
|
||||
): Promise<{ workbook: WorkbookPreview; stage: DataStage }> {
|
||||
let best = identify(initial, fields);
|
||||
const sheets = initial.sheets.filter(sheet => sheet.sheetName !== initial.preview.sheetName)
|
||||
.sort((a, b) => Number(b.sheetName.includes('明细')) - Number(a.sheetName.includes('明细')));
|
||||
for (const sheet of sheets) {
|
||||
if (best.score === 1) break;
|
||||
const workbook = await preview(initial.uploadId, { sheetName: sheet.sheetName, headerRow: 1, stage: best.stage });
|
||||
const candidate = identify(workbook, fields);
|
||||
if (candidate.score > best.score || candidate.score === best.score && candidate.matched > best.matched) best = candidate;
|
||||
}
|
||||
return { workbook: best.workbook, stage: best.stage };
|
||||
}
|
||||
@@ -107,6 +107,14 @@ export interface MetricsResponse {
|
||||
coverage: CoverageSummary;
|
||||
}
|
||||
|
||||
/** 趋势专用响应,不包含汇总表的产品行。 */
|
||||
export interface TrendResponse {
|
||||
release: MetricsResponse['release'];
|
||||
context: Record<string, unknown>;
|
||||
trend: TrendMetricRow[];
|
||||
coverage: CoverageSummary;
|
||||
}
|
||||
|
||||
export interface CoverageSummary {
|
||||
rawRows: number;
|
||||
includedRows: number;
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { api } from './api';
|
||||
import { WORKSPACE_INVALIDATED } from './pageCache';
|
||||
import { WORKSPACE_INVALIDATED, usePageCache } from './pageCache';
|
||||
import type { DataWorkflowOperation } from './NoCodeDataTypes';
|
||||
import { useVisiblePolling } from './useVisiblePolling';
|
||||
|
||||
type StoredOperation = { operationId: string; startedAt: string };
|
||||
const storageKey = (slot: string) => `quality-data-workflow:${slot}`;
|
||||
const isPending = (value: DataWorkflowOperation | null) => value && ['QUEUED', 'RUNNING'].includes(String(value.status).toUpperCase());
|
||||
const delay = (ms: number) => new Promise(resolve => window.setTimeout(resolve, ms));
|
||||
|
||||
export function operationError(value: DataWorkflowOperation | null): string {
|
||||
const errors = Array.isArray(value?.errors) ? value.errors : [];
|
||||
@@ -14,14 +14,25 @@ export function operationError(value: DataWorkflowOperation | null): string {
|
||||
}
|
||||
|
||||
export function useDataWorkflowOperation(slot: string, onComplete?: (value: DataWorkflowOperation) => void) {
|
||||
const { active } = usePageCache();
|
||||
const [operation, setOperation] = useState<DataWorkflowOperation | null>(null);
|
||||
const [operationId, setOperationId] = useState('');
|
||||
const [error, setError] = useState('');
|
||||
const [pollRevision, setPollRevision] = useState(0);
|
||||
const [starting, setStarting] = useState(false);
|
||||
const callbackRef = useRef(onComplete);
|
||||
const activeRef = useRef(0);
|
||||
const startPromiseRef = useRef<Promise<DataWorkflowOperation> | null>(null);
|
||||
const pollRequestRef = useRef<Promise<void> | null>(null);
|
||||
const terminalHandledRef = useRef(new Set<string>());
|
||||
const generationRef = useRef(0);
|
||||
const mountedRef = useRef(false);
|
||||
useEffect(() => { callbackRef.current = onComplete; }, [onComplete]);
|
||||
useEffect(() => {
|
||||
mountedRef.current = true;
|
||||
let pending: StoredOperation | null = null;
|
||||
try { pending = JSON.parse(localStorage.getItem(storageKey(slot)) || 'null') as StoredOperation | null; } catch { pending = null; }
|
||||
if (pending?.operationId) setOperationId(pending.operationId);
|
||||
return () => { mountedRef.current = false; generationRef.current++; };
|
||||
}, [slot]);
|
||||
|
||||
const savePendingId = useCallback((value: StoredOperation | null) => {
|
||||
try {
|
||||
@@ -30,35 +41,36 @@ export function useDataWorkflowOperation(slot: string, onComplete?: (value: Data
|
||||
} catch { /* storage may be unavailable in a restricted browser context */ }
|
||||
}, [slot]);
|
||||
|
||||
const poll = useCallback(async (operationId: string) => {
|
||||
const runId = ++activeRef.current;
|
||||
setError('');
|
||||
while (activeRef.current === runId) {
|
||||
const poll = useCallback((id: string) => {
|
||||
if (!id || terminalHandledRef.current.has(id) || pollRequestRef.current) return pollRequestRef.current || Promise.resolve();
|
||||
const generation = generationRef.current;
|
||||
const attempt = (async () => {
|
||||
try {
|
||||
const current = await api.dataWorkflowOperation(operationId);
|
||||
if (activeRef.current !== runId) return;
|
||||
const current = await api.dataWorkflowOperation(id);
|
||||
if (!mountedRef.current || generation !== generationRef.current) return;
|
||||
setOperation(current);
|
||||
setError('');
|
||||
const status = String(current.status || '').toUpperCase();
|
||||
if (status === 'COMPLETED' || status === 'FAILED') {
|
||||
if (status === 'COMPLETED') { savePendingId(null); window.dispatchEvent(new Event(WORKSPACE_INVALIDATED)); callbackRef.current?.(current); }
|
||||
else setError(operationError(current));
|
||||
return;
|
||||
terminalHandledRef.current.add(id);
|
||||
generationRef.current++;
|
||||
setOperationId('');
|
||||
if (status === 'COMPLETED') {
|
||||
savePendingId(null);
|
||||
window.dispatchEvent(new CustomEvent(WORKSPACE_INVALIDATED, { detail: { resources: ['sources', 'workflow', 'tasks', 'releases', 'metrics', 'trend', 'records', 'options', 'catalog', 'configuration'] } }));
|
||||
callbackRef.current?.(current);
|
||||
} else setError(operationError(current));
|
||||
}
|
||||
} catch (value) {
|
||||
if (activeRef.current !== runId) return;
|
||||
if (!mountedRef.current || generation !== generationRef.current) return;
|
||||
setError(value instanceof Error ? value.message : '处理进度读取失败');
|
||||
return;
|
||||
}
|
||||
await delay(900);
|
||||
}
|
||||
})().finally(() => { if (pollRequestRef.current === attempt) pollRequestRef.current = null; });
|
||||
pollRequestRef.current = attempt;
|
||||
return attempt;
|
||||
}, [savePendingId]);
|
||||
|
||||
useEffect(() => {
|
||||
let pending: StoredOperation | null = null;
|
||||
try { pending = JSON.parse(localStorage.getItem(storageKey(slot)) || 'null') as StoredOperation | null; } catch { pending = null; }
|
||||
if (pending?.operationId) void poll(pending.operationId);
|
||||
return () => { activeRef.current++; };
|
||||
}, [poll, slot, pollRevision]);
|
||||
useVisiblePolling(() => poll(operationId), 2000, active && Boolean(operationId), true);
|
||||
|
||||
const start = useCallback(async (create: () => Promise<DataWorkflowOperation>) => {
|
||||
if (startPromiseRef.current) return startPromiseRef.current;
|
||||
@@ -69,9 +81,11 @@ export function useDataWorkflowOperation(slot: string, onComplete?: (value: Data
|
||||
try {
|
||||
const started = await create();
|
||||
if (!started?.operationId) throw new Error('服务端未返回操作编号');
|
||||
generationRef.current++;
|
||||
setOperation(started);
|
||||
terminalHandledRef.current.delete(started.operationId);
|
||||
setOperationId(started.operationId);
|
||||
savePendingId({ operationId: started.operationId, startedAt: new Date().toISOString() });
|
||||
void poll(started.operationId);
|
||||
return started;
|
||||
} catch (value) {
|
||||
setError(value instanceof Error ? value.message : '操作未能开始');
|
||||
@@ -83,18 +97,19 @@ export function useDataWorkflowOperation(slot: string, onComplete?: (value: Data
|
||||
})();
|
||||
startPromiseRef.current = attempt;
|
||||
return attempt;
|
||||
}, [operation, poll, savePendingId]);
|
||||
}, [operation, savePendingId]);
|
||||
|
||||
const resume = useCallback(() => {
|
||||
if (operation?.operationId) void poll(operation.operationId);
|
||||
else {
|
||||
let pending: StoredOperation | null = null;
|
||||
try { pending = JSON.parse(localStorage.getItem(storageKey(slot)) || 'null') as StoredOperation | null; } catch { pending = null; }
|
||||
if (pending?.operationId) void poll(pending.operationId);
|
||||
else setPollRevision(value => value + 1);
|
||||
}
|
||||
const id = operation?.operationId || (() => {
|
||||
try { return (JSON.parse(localStorage.getItem(storageKey(slot)) || 'null') as StoredOperation | null)?.operationId || ''; }
|
||||
catch { return ''; }
|
||||
})();
|
||||
if (id) { setError(''); setOperationId(id); void poll(id); }
|
||||
}, [operation?.operationId, poll, slot]);
|
||||
|
||||
const clear = useCallback(() => { activeRef.current++; setOperation(null); setError(''); savePendingId(null); }, [savePendingId]);
|
||||
const clear = useCallback(() => {
|
||||
generationRef.current++;
|
||||
setOperation(null); setOperationId(''); setError(''); savePendingId(null);
|
||||
}, [savePendingId]);
|
||||
return { operation, error, busy: starting || Boolean(isPending(operation)), start, resume, clear };
|
||||
}
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
|
||||
/** Shows a loading indicator only when the request has lasted beyond the delay. */
|
||||
export function useDelayedIndicator(active: boolean, delayMs = 150): boolean {
|
||||
const [visible, setVisible] = useState(false);
|
||||
useEffect(() => {
|
||||
if (!active) { setVisible(false); return; }
|
||||
setVisible(false);
|
||||
const timer = window.setTimeout(() => setVisible(true), delayMs);
|
||||
return () => window.clearTimeout(timer);
|
||||
}, [active, delayMs]);
|
||||
return active && visible;
|
||||
}
|
||||
|
||||
/** Wraps reads with a delayed, concurrency-safe busy indicator. */
|
||||
export function useDelayedBusy(delayMs = 150) {
|
||||
const [pendingCount, setPendingCount] = useState(0);
|
||||
const busy = useDelayedIndicator(pendingCount > 0, delayMs);
|
||||
const mounted = useRef(false);
|
||||
useEffect(() => {
|
||||
mounted.current = true;
|
||||
return () => { mounted.current = false; };
|
||||
}, []);
|
||||
const run = useCallback(async <T,>(work: () => Promise<T>): Promise<T> => {
|
||||
setPendingCount(count => count + 1);
|
||||
try { return await work(); }
|
||||
finally { if (mounted.current) setPendingCount(count => Math.max(0, count - 1)); }
|
||||
}, []);
|
||||
return { busy, run };
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import { useEffect, useState, type RefObject } from 'react';
|
||||
|
||||
/** 低频图表接近视口后才读取,页面隐藏时不发起请求。 */
|
||||
export function useResourceVisibility(ref: RefObject<HTMLElement | null>, active: boolean): boolean {
|
||||
const [seen, setSeen] = useState(false);
|
||||
useEffect(() => {
|
||||
if (!active || seen) return;
|
||||
const node = ref.current;
|
||||
if (!node) return;
|
||||
if (typeof IntersectionObserver === 'undefined') { setSeen(true); return; }
|
||||
const observer = new IntersectionObserver(entries => {
|
||||
if (entries.some(entry => entry.isIntersecting)) { setSeen(true); observer.disconnect(); }
|
||||
}, { rootMargin: '240px' });
|
||||
observer.observe(node);
|
||||
return () => observer.disconnect();
|
||||
}, [ref, active, seen]);
|
||||
return active && seen;
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import { useEffect, useRef } from 'react';
|
||||
import { createVisiblePollingController } from './visiblePollingController';
|
||||
|
||||
/** Polls serially while the owning page is active and the browser tab is visible. */
|
||||
export function useVisiblePolling(callback: () => void | Promise<void>, intervalMs: number, enabled: boolean, immediateOnEnable = false) {
|
||||
const callbackRef = useRef(callback);
|
||||
callbackRef.current = callback;
|
||||
|
||||
useEffect(() => {
|
||||
if (!enabled) return;
|
||||
const controller = createVisiblePollingController(() => callbackRef.current(), intervalMs);
|
||||
const syncVisibility = () => controller.setVisible(document.visibilityState === 'visible');
|
||||
controller.start(document.visibilityState === 'visible', immediateOnEnable);
|
||||
document.addEventListener('visibilitychange', syncVisibility);
|
||||
return () => {
|
||||
document.removeEventListener('visibilitychange', syncVisibility);
|
||||
controller.stop();
|
||||
};
|
||||
}, [enabled, intervalMs, immediateOnEnable]);
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
export type PollScheduler = {
|
||||
setTimeout: (callback: () => void, delayMs: number) => unknown;
|
||||
clearTimeout: (handle: unknown) => void;
|
||||
};
|
||||
|
||||
export type VisiblePollingController = {
|
||||
start: (visible: boolean, runImmediately?: boolean) => void;
|
||||
setVisible: (visible: boolean) => void;
|
||||
stop: () => void;
|
||||
};
|
||||
|
||||
/** Runs one request at a time and starts the next delay only after it settles. */
|
||||
export function createVisiblePollingController(
|
||||
callback: () => void | Promise<void>,
|
||||
intervalMs: number,
|
||||
scheduler: PollScheduler = {
|
||||
setTimeout: (run, delay) => window.setTimeout(run, delay),
|
||||
clearTimeout: handle => window.clearTimeout(handle as number),
|
||||
},
|
||||
): VisiblePollingController {
|
||||
let enabled = false;
|
||||
let visible = false;
|
||||
let inFlight = false;
|
||||
let runImmediatelyAfterFlight = false;
|
||||
let timer: unknown = null;
|
||||
|
||||
const clear = () => {
|
||||
if (timer !== null) scheduler.clearTimeout(timer);
|
||||
timer = null;
|
||||
};
|
||||
const schedule = () => {
|
||||
if (!enabled || !visible || inFlight || timer !== null) return;
|
||||
timer = scheduler.setTimeout(() => {
|
||||
timer = null;
|
||||
void run();
|
||||
}, intervalMs);
|
||||
};
|
||||
const run = async () => {
|
||||
if (!enabled || !visible) return;
|
||||
if (inFlight) {
|
||||
runImmediatelyAfterFlight = true;
|
||||
return;
|
||||
}
|
||||
clear();
|
||||
inFlight = true;
|
||||
try { await callback(); } catch { /* Polling errors are rendered by the caller. */ }
|
||||
finally {
|
||||
inFlight = false;
|
||||
if (!enabled || !visible) return;
|
||||
if (runImmediatelyAfterFlight) {
|
||||
runImmediatelyAfterFlight = false;
|
||||
void run();
|
||||
} else schedule();
|
||||
}
|
||||
};
|
||||
|
||||
return {
|
||||
start(nextVisible, runImmediately = false) {
|
||||
enabled = true;
|
||||
visible = nextVisible;
|
||||
if (visible) runImmediately ? void run() : schedule();
|
||||
},
|
||||
setVisible(nextVisible) {
|
||||
if (visible === nextVisible) return;
|
||||
visible = nextVisible;
|
||||
if (!enabled) return;
|
||||
if (!visible) clear();
|
||||
else void run();
|
||||
},
|
||||
stop() {
|
||||
enabled = false;
|
||||
runImmediatelyAfterFlight = false;
|
||||
clear();
|
||||
},
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user