统一全系统资源加载、轻量趋势与缓存恢复

This commit is contained in:
2026-11-02 09:54:01 +08:00
parent 8b8f9b7728
commit b711327c8e
58 changed files with 3150 additions and 661 deletions
+185 -97
View File
@@ -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 <>