完善:同月多文件导入与当前用户离线迁移更新

This commit is contained in:
2026-11-04 11:35:24 +08:00
parent 147b56d0fd
commit f04d4e96e3
89 changed files with 6634 additions and 201 deletions
+2 -2
View File
@@ -291,8 +291,8 @@ function SourcesPage({ onUnauthorized, user }: { onUnauthorized: (error: unknown
return <div className="management-page">
{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} sourcesLoaded={sourcesLoaded} loading={sourceRead.busy} pendingIds={pendingDeletion.ids} maintenanceBusy={maintenanceBusy} onToggleDelete={toggleDelete} onClearDeletes={() => setPendingDeletion({ ids: [], releaseId: null })} onUnauthorized={onUnauthorized} onRefresh={() => void load()} /> },
{ key: 'intake', label: '数据接入', children: <DataWorkflowHub user={user} sources={sources} currentReleaseId={currentReleaseId} pendingDeletion={pendingDeletion} onBusyChange={setMaintenanceBusy} onUnauthorized={onUnauthorized} onRefresh={() => void load()} /> },
{ key: 'files', label: '来源文件', children: <SourceFilesPanel user={user} sources={sources} sourcesLoaded={sourcesLoaded} loading={sourceRead.busy} pendingIds={pendingDeletion.ids} pendingReleaseId={pendingDeletion.releaseId} maintenanceBusy={maintenanceBusy} onDeleted={onDeleted} onBusyChange={setMaintenanceBusy} 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} /> },
]} />
+2 -2
View File
@@ -7,9 +7,9 @@ export type WorkbookPreview = {
preview: { sheetName: string; headerRow: number; headers: string[]; sampleRows: { rowNumber: number; values: Record<string, unknown> }[] };
fields: Record<DataStage, DataField[]>;
};
export type PublishedSourceTarget = { documentId: string; revisionId: string; sourceSlot: string; stage: DataStage; year: number; month: number; scopeCode: string; sourceFile: string };
export type PublishedSourceTarget = { documentId: string; revisionId: string; sourceSlot: string; stage: DataStage; year: number; month: number; scopeCode: string; sourceFile: string; fileId?: string | null; sourceMode?: 'MAIN' | 'SHARD_SNAPSHOT' | string };
export type SourceUploadOptions = { currentReleaseId: string | null; targets: PublishedSourceTarget[]; fields: Record<DataStage, DataField[]>; scopes: string[]; currentSourceIds?: string[]; currentSourcesComplete?: boolean };
export type ConfigureSourceBody = { uploadId: string; stage: DataStage; year: number; month: number; sheetName: string; headerRow: number; fieldMap: Record<string, string>; mode: 'ADD' | 'REPLACE'; expectedCurrentReleaseId: string | null; targetDocumentId?: string; targetRevisionId?: string; reason: string; scopeCode: string };
export type ConfigureSourceBody = { uploadId: string; stage: DataStage; year: number; month: number; sheetName: string; headerRow: number; fieldMap: Record<string, string>; mode: 'ADD' | 'APPEND' | 'REPLACE'; fileId?: string; expectedCurrentReleaseId: string | null; targetDocumentId?: string; targetRevisionId?: string; reason: string; scopeCode: string };
export type MasterWorkbookKind = 'departments' | 'groups' | 'products' | 'projectGroups' | 'categoryLookup' | 'projectGroupLookup' | 'departmentLookup' | 'productLookup' | 'standardBundle';
export type MasterWorkbookKeyFormat = 'SEPARATE_COLUMNS' | 'PDT_REGION_COMBINED';
export type MasterWorkbookPreview = {
+109 -65
View File
@@ -14,6 +14,7 @@ import { usePageCache } from './pageCache';
import { useDelayedBusy, useDelayedIndicator } from './useDelayedBusy';
import { useVisiblePolling } from './useVisiblePolling';
import { runImportPollFollowup } from './importLifecycleGuards';
import { configureSourceBatch } from './sourceBatchConfigure';
import './no-code-data-workflow.css';
type Row = Record<string, unknown>;
@@ -43,28 +44,28 @@ function WorkflowOperationFeedback({ operation, error, busy, onResume }: { opera
const status = String(operation?.status || '').toUpperCase();
const errors = Array.isArray(operation?.errors) ? operation.errors.map(item => item.message).filter(Boolean) : [];
return <section className="nc-operation-status panel">
{error && <Alert showIcon type="error" message={status === 'FAILED' ? '操作未完成' : '进度读取失败'} description={[...errors, error].filter(Boolean).join(';')} action={operation?.operationId ? <Button size="small" onClick={onResume}>重试读取进度</Button> : undefined} />}
{error && <Alert showIcon type="error" message={status === 'FAILED' || !operation ? '操作未完成' : '进度读取失败'} description={[...new Set([...errors, error].filter(Boolean))].join(';')} action={operation?.operationId ? <Button size="small" onClick={onResume}>重试读取进度</Button> : undefined} />}
<div><strong>{workflowStageLabel[String(operation?.stage || operation?.status)] || (busy ? '正在处理' : status === 'COMPLETED' ? '报表已更新' : '操作状态')}</strong></div>
<Progress percent={busy ? undefined : status === 'COMPLETED' ? 100 : 0} status={status === 'FAILED' ? 'exception' : status === 'COMPLETED' ? 'success' : 'active'} />
</section>;
}
export type PendingSourceDeletion = { ids: string[]; releaseId: string | null };
type SourceDraft = { id: string; file: File; workbook: WorkbookPreview; stage: DataStage; year: number; month: number; sheetName: string; headerRow: number; fieldMap: Record<string, string>; mode: 'ADD' | 'REPLACE'; targetId: string; scopeCode: string };
type SourceDraft = { id: string; file: File; workbook: WorkbookPreview; stage: DataStage; year: number; month: number; sheetName: string; headerRow: number; fieldMap: Record<string, string>; mode: 'APPEND' | 'REPLACE'; fileId: string; targetId: string; scopeCode: string };
type WizardFileDraft = { id: string; file: File; workbook: WorkbookPreview; sheetName: string; headerRow: number; fieldMap: Record<string, string>; fileId: string };
function SimplifiedDataWorkflow({ options, workflowStatus, pendingDeletion, onDeleted, onBusyChange, onUnauthorized, onRefresh }: { options: SourceUploadOptions; workflowStatus: DataWorkflowStatus; pendingDeletion: PendingSourceDeletion; onDeleted: (ids: string[]) => void; onBusyChange: (busy: boolean) => void; onUnauthorized: (error: unknown) => boolean; onRefresh: () => void }) {
function SimplifiedDataWorkflow({ options, workflowStatus, pendingDeletion, onBusyChange, onUnauthorized, onRefresh }: { options: SourceUploadOptions; workflowStatus: DataWorkflowStatus; pendingDeletion: PendingSourceDeletion; onBusyChange: (busy: boolean) => void; onUnauthorized: (error: unknown) => boolean; onRefresh: () => void }) {
const confirmDelete = useDeleteConfirmation();
const { message } = App.useApp();
const input = useRef<HTMLInputElement>(null);
const configured = useRef(new Map<string, { signature: string; sourceId: string }>());
const consumed = useRef(new Set<string>());
const [drafts, setDrafts] = useState<SourceDraft[]>([]);
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 uploadOperation = useDataWorkflowOperation('source-import', () => { setDrafts([]); setActiveId(''); configured.current.clear(); onRefresh(); message.success('所选来源已统一导入,报表已更新'); });
const recalcOperation = useDataWorkflowOperation('recalculate', () => { onRefresh(); message.success('报表已更新'); });
const active = drafts.find(item => item.id === activeId) || drafts[0];
const workbook = active?.workbook || null;
const stage = active?.stage || 'black'; const year = active?.year || new Date().getFullYear(); const month = active?.month || 1;
@@ -72,19 +73,28 @@ function SimplifiedDataWorkflow({ options, workflowStatus, pendingDeletion, onDe
const mode = active?.mode || 'ADD'; const targetId = active?.targetId || ''; const scopeCode = active?.scopeCode || options.scopes[0] || 'ALL';
const patch = (values: Partial<SourceDraft>) => { if (active) setDrafts(previous => previous.map(item => item.id === active.id ? { ...item, ...values } : item)); };
const setWorkbook = (value: WorkbookPreview) => patch({ workbook: value });
const setStage = (value: DataStage) => patch({ stage: value }); const setYear = (value: number) => patch({ year: value }); const setMonth = (value: number) => patch({ month: value });
const setStage = (value: DataStage) => patch({ stage: value, targetId: '' }); const setYear = (value: number) => patch({ year: value, targetId: '' }); const setMonth = (value: number) => patch({ month: value, targetId: '' });
const setSheetName = (value: string) => patch({ sheetName: value }); const setHeaderRow = (value: number) => patch({ headerRow: value });
const setFieldMap = (value: Record<string, string>) => patch({ fieldMap: value }); const setMode = (value: 'ADD' | 'REPLACE') => patch({ mode: value });
const setTargetId = (value: string) => patch({ targetId: value }); const setScopeCode = (value: string) => patch({ scopeCode: value });
const setFieldMap = (value: Record<string, string>) => patch({ fieldMap: value }); const setMode = (value: 'APPEND' | 'REPLACE') => patch({ mode: value, targetId: '' });
const setTargetId = (value: string) => patch({ targetId: value }); const setScopeCode = (value: string) => patch({ scopeCode: value, targetId: '' });
const fields = options.fields[stage] || []; const headers = workbook?.preview.headers || [];
const missing = fields.filter(field => field.required && !fieldMap[field.name]); const duplicate = Object.values(fieldMap).length !== new Set(Object.values(fieldMap)).size;
const importBusy = busy || uploadOperation.busy || recalcOperation.busy;
useEffect(() => { onBusyChange(importBusy); return () => onBusyChange(false); }, [importBusy, onBusyChange]);
const hasImportCapability = workflowStatus.capabilities?.canImport !== false;
const draftReady = (item: SourceDraft) => (options.fields[item.stage] || []).filter(field => field.required).every(field => item.fieldMap[field.name]) && Object.values(item.fieldMap).length === new Set(Object.values(item.fieldMap)).size && (item.mode !== 'REPLACE' || options.targets.some(target => target.documentId === item.targetId));
const slots = drafts.map(item => `${item.year}:${item.month}:${item.stage}:${item.scopeCode}`);
const duplicateSlots = new Set(slots).size !== slots.length;
const canImport = hasImportCapability && drafts.length > 0 && drafts.every(draftReady) && !duplicateSlots && !pendingDeletion.ids.length;
const targetFor = (item: SourceDraft) => options.targets.find(target => target.documentId === item.targetId && target.year === item.year && target.month === item.month && target.stage === item.stage && target.scopeCode === item.scopeCode);
const hasMainSource = (item: Pick<SourceDraft, 'year' | 'month' | 'stage' | 'scopeCode'>) => options.targets.some(target => !target.fileId && target.sourceMode !== 'MONTHLY_SNAPSHOT' && target.year === item.year && target.month === item.month && target.stage === item.stage && target.scopeCode === item.scopeCode);
const draftReady = (item: SourceDraft) => {
const target = targetFor(item);
const matched = (options.fields[item.stage] || []).filter(field => field.required).every(field => item.fieldMap[field.name]) && Object.values(item.fieldMap).length === new Set(Object.values(item.fieldMap)).size;
return matched && (item.mode === 'APPEND' ? !hasMainSource(item) : Boolean(target) && (target?.sourceMode !== 'APPEND_SNAPSHOT' || Boolean(target.fileId)));
};
const replacementTargets = active ? options.targets.filter(item => item.year === year && item.month === month && item.stage === stage && item.scopeCode === scopeCode) : [];
const activeHasMainSource = active ? hasMainSource(active) : false;
const configuredActive = Boolean(active && configured.current.has(active.id));
const configuredReplacement = configuredActive && mode === 'REPLACE';
const repeatedReplacement = drafts.filter(item => item.mode === 'REPLACE' && item.targetId).length !== new Set(drafts.filter(item => item.mode === 'REPLACE' && item.targetId).map(item => item.targetId)).size;
const canImport = hasImportCapability && drafts.length > 0 && drafts.every(draftReady) && !repeatedReplacement && !pendingDeletion.ids.length;
const reportError = (value: unknown) => { if (!onUnauthorized(value)) setError(failure(value)); };
const removeDraft = (id: string) => confirmDelete({title:`移除文件“${drafts.find(item=>item.id===id)?.workbook.sourceFile || "选中的文件"}”?`,description:"仅从本次导入列表移除,此文件的字段对应设置也将移除。电脑上的原文件及已接收来源保留。",confirmText:"确认移除",onConfirm:()=>{setDrafts(previous => previous.filter(item => item.id !== id));configured.current.delete(id);}});
const readFiles = async (files: File[]) => {
@@ -102,7 +112,7 @@ function SimplifiedDataWorkflow({ options, workflowStatus, pendingDeletion, onDe
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' };
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: 'APPEND' as const, fileId: crypto.randomUUID(), targetId: '', scopeCode: options.scopes[0] || 'ALL' };
} catch (value) { if (!onUnauthorized(value)) failures.push(`${file.name}:${failure(value)}`); return null; }
}));
const ready = results.filter(item => item !== null);
@@ -124,58 +134,50 @@ function SimplifiedDataWorkflow({ options, workflowStatus, pendingDeletion, onDe
const importAndUpdate = async () => {
if (!canImport || importBusy || actionLock.current) return; actionLock.current = true; setBusy(true); setError('');
try {
const sourceIds: string[] = [];
for (const draft of drafts) {
const target = options.targets.find(item => item.documentId === draft.targetId);
const body = { stage: draft.stage, year: draft.year, month: draft.month, sheetName: draft.sheetName, headerRow: draft.headerRow, fieldMap: draft.fieldMap, mode: draft.mode, expectedCurrentReleaseId: workflowStatus.currentReleaseId ?? options.currentReleaseId, ...(draft.mode === 'REPLACE' && target ? { targetDocumentId: target.documentId, targetRevisionId: target.revisionId } : {}), reason: '批量导入来源数据', scopeCode: draft.scopeCode };
const signature = JSON.stringify(body); const prior = configured.current.get(draft.id);
if (prior?.signature === signature) { sourceIds.push(prior.sourceId); continue; }
let uploadId = draft.workbook.uploadId;
if (consumed.current.has(uploadId)) uploadId = (await api.previewSourceWorkbook(draft.file)).uploadId;
const result = await api.configureSourceWorkbook({ ...body, uploadId });
consumed.current.add(uploadId); configured.current.set(draft.id, { signature, sourceId: result.source.id }); sourceIds.push(result.source.id);
}
const items = drafts.map(draft => {
const target = targetFor(draft);
return { id: draft.id, body: { uploadId: draft.workbook.uploadId, stage: draft.stage, year: draft.year, month: draft.month, sheetName: draft.sheetName, headerRow: draft.headerRow, fieldMap: draft.fieldMap, mode: draft.mode, ...(draft.mode === 'APPEND' ? { fileId: draft.fileId } : target?.fileId ? { fileId: target.fileId } : {}), expectedCurrentReleaseId: workflowStatus.currentReleaseId ?? options.currentReleaseId, ...(draft.mode === 'REPLACE' && target ? { targetDocumentId: target.documentId, targetRevisionId: target.revisionId } : {}), reason: draft.mode === 'APPEND' ? '按独立批次追加,不覆盖旧文件' : '替换所选来源文件', scopeCode: draft.scopeCode } };
});
const sourceIds = await configureSourceBatch(items, configured.current, body => api.configureSourceWorkbook(body));
await uploadOperation.start(() => api.importDataWorkflow({ sourceIds }));
} catch (value) { reportError(value); } finally { actionLock.current = false; setBusy(false); }
};
const performRecalculation = async () => {
if (actionLock.current) return; actionLock.current = true;
if (actionLock.current || pendingDeletion.ids.length) return; actionLock.current = true;
setError('');
try { await recalcOperation.start(() => pendingDeletion.ids.length ? api.deleteDataWorkflowSources({ sourceIds: pendingDeletion.ids, expectedCurrentReleaseId: pendingDeletion.releaseId }) : api.recalculateDataWorkflow()); }
try { await recalcOperation.start(() => api.recalculateDataWorkflow()); }
catch (value) { reportError(value); }
finally { actionLock.current = false; }
};
const recalculate = () => {
if (actionLock.current) return;
if (!pendingDeletion.ids.length) return performRecalculation();
confirmDelete({title:`删除 ${pendingDeletion.ids.length} 个来源并更新报表?`,description:<><p>将从当前查询结果移除以下来源并更新报表,原文件和处理记录保留。</p><ul>{pendingDeletion.ids.slice(0,10).map((id,index)=><li key={id}>{options.targets.find(item=>item.documentId===id)?.sourceFile || `第 ${index+1} 个待删除来源`}</li>)}</ul>{pendingDeletion.ids.length>10&&<p>另有 {pendingDeletion.ids.length-10} 个待删除来源。</p>}</>,confirmText:'确认删除并更新',onConfirm:performRecalculation});
};
return <div className="nc-simplified-intake">
<section className="panel nc-simple-upload-panel">
<div className="nc-simple-upload-heading"><div><span className="nc-eyebrow">测试数据维护</span><h2>导入来源并更新报表</h2><p>支持一次选择多个 Excel 文件,分别核对年月与阶段后统一导入。</p></div><div className="nc-simple-upload-actions">{workflowStatus.capabilities?.canRecalculate !== false && <Button icon={<ReloadOutlined />} disabled={importBusy} loading={recalcOperation.busy} onClick={() => void recalculate()}>{pendingDeletion.ids.length ? `更新报表(${pendingDeletion.ids.length}项删除)` : '更新报表'}</Button>}</div></div>
<div className="nc-simple-upload-heading"><div><span className="nc-eyebrow">测试数据维护</span><h2>导入来源并更新报表</h2><p>同一月份可分批添加多个文件;相同文件内容不会重复计入。</p></div><div className="nc-simple-upload-actions">{workflowStatus.capabilities?.canRecalculate !== false && <Button icon={<ReloadOutlined />} disabled={importBusy || pendingDeletion.ids.length > 0} loading={recalcOperation.busy} onClick={() => void performRecalculation()}>更新报表</Button>}</div></div>
{!hasImportCapability && <Alert showIcon type="info" message="当前账号没有导入权限" description="可查看来源;导入和更新报表需要发布权限。" />}
{error && <Alert showIcon type="error" message="操作未完成,输入内容已保留" description={error} />}
<input className="visually-hidden-file" ref={input} type="file" multiple accept=".xlsx" onChange={event => void readFiles(Array.from(event.target.files || []))} aria-label="选择质量数据Excel文件" />
{pendingDeletion.ids.length > 0 && <Alert type="warning" showIcon message={`有 ${pendingDeletion.ids.length} 个来源待删除,报表尚未改变`} description="可继续标记或撤销删除,完成后点击“更新报表”。请先处理待删除文件,再导入新文件。" />}
{pendingDeletion.ids.length > 0 && <Alert type="warning" showIcon message={`有 ${pendingDeletion.ids.length} 个来源待删除,报表尚未改变`} description="请到“来源文件”页确认或撤销删除,再导入新文件。" />}
{reading && <div className="nc-section-title"><Spin size="small" /><span>正在上传并识别文件 {reading.done} / {reading.total}</span></div>}
{drafts.length > 0 && <><div className="nc-section-title"><strong>待导入文件 · {drafts.length} 个</strong><Button disabled={importBusy} icon={<UploadOutlined />} onClick={() => input.current?.click()}>继续添加文件</Button></div><Table size="small" rowKey="id" pagination={false} scroll={{ x: 700 }} dataSource={drafts} columns={[
{ title: '文件', key: 'file', render: (_, item) => <Button type="link" onClick={() => setActiveId(item.id)}>{item.workbook.sourceFile}</Button> },
{ title: '文件', key: 'file', render: (_, item) => <Button type="link" onClick={() => setActiveId(item.id)}>{item.workbook.sourceFile} · {item.id.slice(0, 8)}</Button> },
{ title: '阶段', key: 'stage', render: (_, item) => stageName(item.stage) },
{ title: '统计期间', key: 'period', render: (_, item) => `${item.year}年${item.month}月` },
{ title: '识别结果', key: 'validation', render: (_, item) => draftReady(item) ? <Tag color="green">已识别</Tag> : <Tag color="orange">需核对列或替换对象</Tag> },
{ title: '操作', key: 'action', render: (_, item) => <Button type="link" disabled={importBusy} onClick={() => removeDraft(item.id)}>移除</Button> },
{ title: '操作', key: 'action', render: (_, item) => configured.current.has(item.id) ? <Tag color="blue">已接收待导入</Tag> : <Button type="link" disabled={importBusy} onClick={() => removeDraft(item.id)}>移除</Button> },
]} /></>}
{duplicateSlots && <Alert type="warning" showIcon message="多个文件对应同一期间、阶段和范围,请调整或移除重复文件后再导入" />}
{!workbook ? <div className="nc-file-drop nc-simple-file-drop"><FileExcelOutlined /><h3>选择 Excel 来源文件</h3><p>可多选文件;系统自动识别阶段和月份,每个文件都可单独调整。</p>{hasImportCapability && <Button type="primary" icon={<UploadOutlined />} loading={busy} onClick={() => input.current?.click()}>选择 Excel 文件</Button>}</div> : <>
<div className="nc-simple-file-line"><FileExcelOutlined /><strong>{workbook.sourceFile}</strong>{hasImportCapability && <Button type="link" disabled={importBusy} onClick={() => { if (active) removeDraft(active.id); }}>移除此文件</Button>}</div>
<div className="nc-simple-upload-fields">
<label>导入方式<Select disabled={importBusy} value={mode} options={[{ value: 'ADD', label: '新增数据' }, { value: 'REPLACE', label: '替换已有数据' }]} onChange={value => { setMode(value); }} /></label>
<label>数据阶段<Select disabled={importBusy} value={stage} options={[{ value: 'black', label: '黑片' }, { value: 'bright', label: '亮片' }]} onChange={value => { setStage(value); setFieldMap(matchFields(options.fields[value] || [], headers)); }} /></label>
<label>统计年份<InputNumber disabled={importBusy} min={2000} max={2100} value={year} onChange={value => { if (value) setYear(value); }} /></label>
<label>统计月份<Select disabled={importBusy} value={month} options={Array.from({ length: 12 }, (_, index) => ({ value: index + 1, label: `${index + 1}月` }))} onChange={value => { setMonth(value); }} /></label>
{options.scopes.length > 1 && <label>数据范围<Select disabled={importBusy} value={scopeCode} options={options.scopes.map(value => ({ value, label: value === 'ALL' ? '全部范围' : value }))} onChange={value => { setScopeCode(value); }} /></label>}
{mode === 'REPLACE' && <label className="nc-simple-replace-target">替换对象<Select {...readableSelectPopup} disabled={importBusy} 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={value => { setTargetId(value); }} /></label>}
<label>导入方式<Select disabled={importBusy || configuredActive} value={mode} options={[{ value: 'APPEND', label: '追加文件并合并统计' }, { value: 'REPLACE', label: '替换一份已有文件' }]} onChange={setMode} /></label>
<label>数据阶段<Select disabled={importBusy || configuredReplacement} value={stage} options={[{ value: 'black', label: '黑片' }, { value: 'bright', label: '亮片' }]} onChange={value => { setStage(value); setFieldMap(matchFields(options.fields[value] || [], headers)); }} /></label>
<label>统计年份<InputNumber disabled={importBusy || configuredReplacement} min={2000} max={2100} value={year} onChange={value => { if (value) setYear(value); }} /></label>
<label>统计月份<Select disabled={importBusy || configuredReplacement} value={month} options={Array.from({ length: 12 }, (_, index) => ({ value: index + 1, label: `${index + 1}月` }))} onChange={value => { setMonth(value); }} /></label>
{options.scopes.length > 1 && <label>数据范围<Select disabled={importBusy || configuredReplacement} value={scopeCode} options={options.scopes.map(value => ({ value, label: value === 'ALL' ? '全部范围' : value }))} onChange={value => { setScopeCode(value); }} /></label>}
{mode === 'REPLACE' && <label className="nc-simple-replace-target">替换对象<Select {...readableSelectPopup} disabled={importBusy || configuredReplacement} showSearch optionFilterProp="label" value={targetId || undefined} placeholder="选择同期间的一份文件" options={replacementTargets.map(item => ({ value: item.documentId, label: `${item.sourceFile} · ${item.fileId ? `分批文件 ${item.fileId.slice(0, 8)}` : '整月文件'}` }))} onChange={setTargetId} /></label>}
</div>
{mode === 'APPEND' && activeHasMainSource && <Alert type="warning" showIcon message="该月份目前是整月文件,不能与分批文件混合累计" description="如需修订,请改用“替换一份已有文件”;整月文件替换会替换该月份的完整数据。" />}
{mode === 'REPLACE' && replacementTargets.length === 0 && <Alert type="info" showIcon message="这个年月、阶段和范围没有可替换的已发布文件" />}
{repeatedReplacement && <Alert type="warning" showIcon message="同一份已有文件只能替换一次,请为每个待替换文件选择不同目标。" />}
<p className="nc-note">请确保文件范围内的记录不重叠;相同文件内容会被系统阻止,不同文件里的重复业务行无法自动识别。</p>
<details className="nc-advanced-import-settings"><summary>列识别与预览</summary>
<div className="nc-form-grid"><label>工作表<Select disabled={importBusy} value={sheetName} options={workbook.sheets.map(item => ({ value: item.sheetName, label: item.sheetName }))} onChange={value => void changePreview(value)} /></label><label>表头所在行<InputNumber disabled={importBusy} min={1} max={100} value={headerRow} onChange={value => { if (value) setHeaderRow(value); }} onBlur={() => { if (workbook.preview.headerRow !== headerRow) void changePreview(sheetName, headerRow); }} /></label></div>
<div className="nc-section-title"><h3>业务字段对应 Excel 列</h3><span>{missing.length ? `还有 ${missing.length} 个必填字段待匹配` : duplicate ? '同一 Excel 列不能重复对应' : '已匹配'}</span></div><ColumnMatching disabled={importBusy} fields={fields} headers={headers} value={fieldMap} onChange={value => { setFieldMap(value); }} />
@@ -196,7 +198,7 @@ function ValidationNotice({ value }: { value: unknown }) {
return errors.length ? <Alert showIcon type="warning" message="校验仍有需要处理的事项" description={<ul className="nc-issue-list">{errors.map((item, index) => <li key={index}>{txt(item)}</li>)}</ul>} /> : result.complete === true ? <Alert showIcon type="success" message="来源及对应关系校验通过" /> : result.complete === false ? <Alert showIcon type="warning" message="候选校验尚未通过" description="请核对来源是否齐备,以及基础数据和对应关系是否完整。" /> : null;
}
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 }) {
export function DataWorkflowHub({ user, sources, currentReleaseId, pendingDeletion, onBusyChange, onUnauthorized, onRefresh }: { user: AuthUser; sources: SourceItem[]; currentReleaseId: string | null; pendingDeletion: PendingSourceDeletion; 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);
@@ -238,7 +240,7 @@ export function DataWorkflowHub({ user, sources, currentReleaseId, pendingDeleti
const opened = mode !== null || Boolean(resumeId);
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} />;
if (workflowStatus?.simplified === true && workflowStatus.mode === 'TEST' && options) return <SimplifiedDataWorkflow options={options} workflowStatus={workflowStatus} pendingDeletion={pendingDeletion} onBusyChange={onBusyChange} onUnauthorized={onUnauthorized} onRefresh={onRefresh} />;
return <>
<section className="nc-intake-start panel">
<div className="nc-intake-intro"><span className="nc-eyebrow">日常数据维护</span><h2>选择文件,核对后发布</h2><p>文件名可以保持原样。黑片或亮片、统计年月和表头均在下一步选择。</p></div>
@@ -255,7 +257,7 @@ export function DataWorkflowHub({ user, sources, currentReleaseId, pendingDeleti
</>;
}
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 }) {
export function SourceFilesPanel({ user, sources, sourcesLoaded, loading, pendingIds, pendingReleaseId, maintenanceBusy, onDeleted, onBusyChange, onToggleDelete, onClearDeletes, onUnauthorized, onRefresh }: { user: AuthUser; sources: SourceItem[]; sourcesLoaded: boolean; loading: boolean; pendingIds: string[]; pendingReleaseId: string | null; maintenanceBusy: boolean; onDeleted: (ids: string[]) => void; onBusyChange: (busy: boolean) => void; onToggleDelete: (id: string) => void; onClearDeletes: () => void; onUnauthorized: (error: unknown) => boolean; onRefresh: () => void }) {
const confirmDelete = useDeleteConfirmation();
const { message } = App.useApp();
const { active } = usePageCache();
@@ -276,9 +278,11 @@ export function SourceFilesPanel({ user, sources, sourcesLoaded, loading, pendin
catch (value) { if (!onUnauthorized(value)) setDeletedError(failure(value)); }
}), [deletedRead.run, onUnauthorized]);
const sourceOperation = useDataWorkflowOperation('source-maintenance', value => {
if (Array.isArray(value.sourceIds)) onDeleted(value.sourceIds.map(String));
onRefresh(); if (showDeleted) void loadDeleted();
message.success(String(value.operationType || '').toUpperCase().includes('RESTORE') ? '来源已恢复,报表已更新' : '来源已删除,报表已更新');
});
useEffect(() => { onBusyChange(sourceOperation.busy); return () => onBusyChange(false); }, [sourceOperation.busy, onBusyChange]);
const loadMetadata = useCallback(async () => {
const [status, options] = await Promise.allSettled([api.dataWorkflowStatus(), api.sourceUploadOptions()]);
const errors: string[] = [];
@@ -301,14 +305,24 @@ export function SourceFilesPanel({ user, sources, sourcesLoaded, loading, pendin
try { await sourceOperation.start(() => restore ? api.restoreDataWorkflowSource(id) : api.deleteDataWorkflowSource(id)); }
catch (value) { if (!onUnauthorized(value)) setDeletedError(failure(value)); }
};
const confirmPendingDeletion = () => {
if (!pendingIds.length || sourceOperation.busy || maintenanceBusy || loading) return;
const sourceIds = [...pendingIds];
confirmDelete({
title: `确认删除 ${sourceIds.length} 个来源并更新报表?`,
description: <><p>将从当前查询结果移除以下来源,原文件和处理记录保留。</p><ul>{sourceIds.slice(0, 10).map(id => <li key={id}>{sources.find(source => source.id === id)?.sourceFile || id}</li>)}</ul>{sourceIds.length > 10 && <p>另有 {sourceIds.length - 10} 个待删除来源。</p>}</>,
confirmText: '确认删除并更新',
onConfirm: () => sourceOperation.start(() => api.deleteDataWorkflowSources({ sourceIds, expectedCurrentReleaseId: pendingReleaseId })),
});
};
return <>
<section className="panel section-panel nc-source-files">
<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>}
{simplified && <p className="nc-source-maintenance-note">删除先标记为待删除,可连续操作和撤销,点击“确认删除并更新报表”后统一生效。原文件和处理记录保留。</p>}
{simplified && !showDeleted && canOperate && pendingIds.length > 0 && <div className="nc-source-maintenance-actions"><Button type="primary" danger icon={<DeleteOutlined />} disabled={maintenanceBusy || loading || workflowStatus?.capabilities?.canDeleteSource === false} loading={sourceOperation.busy} onClick={confirmPendingDeletion}>确认删除并更新报表({pendingIds.length})</Button><Button disabled={sourceOperation.busy || maintenanceBusy || loading} onClick={onClearDeletes}>撤销全部待删除({pendingIds.length})</Button></div>}
{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} />}
{(sourceOperation.operation || sourceOperation.error) && <WorkflowOperationFeedback operation={sourceOperation.operation} error={sourceOperation.error} busy={sourceOperation.busy} onResume={sourceOperation.resume} />}
{(!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> },
@@ -319,7 +333,7 @@ export function SourceFilesPanel({ user, sources, sourcesLoaded, loading, pendin
const onCurrentRelease = currentSourceIds?.includes(row.id) ?? false;
const permitted = !simplified || (showDeleted ? workflowStatus?.capabilities?.canRestoreSource !== false : currentSourceIds !== null && workflowStatus?.capabilities?.canDeleteSource !== false && (!onCurrentRelease || workflowStatus?.capabilities?.canDeleteCurrentSource !== false));
if (!workflowStatusLoaded || !canOperate || !permitted) return null;
return <Button type="link" danger={!showDeleted} icon={showDeleted ? <UndoOutlined /> : <DeleteOutlined />} disabled={sourceOperation.busy || maintenanceBusy || loading} onClick={() => {if(!simplified){setSelected({id:row.id,restore:showDeleted});return;}if(showDeleted){void runSourceOperation(row.id,true);return;}if(pendingIds.includes(row.id)){onToggleDelete(row.id);return;}confirmDelete({title:`删除来源“${row.sourceFile}”?`,description:"将标记为待删除,当前报表暂不改变。点击“更新报表”后才生效,原文件和处理记录保留。",confirmText:"标记删除",onConfirm:()=>onToggleDelete(row.id)});}}>{simplified ? showDeleted ? '恢复并更新报表' : pendingIds.includes(row.id) ? '撤销删除' : '删除' : showDeleted ? '恢复' : '删除'}</Button>;
return <Button type="link" danger={!showDeleted} icon={showDeleted ? <UndoOutlined /> : <DeleteOutlined />} disabled={sourceOperation.busy || maintenanceBusy || loading} onClick={() => {if(!simplified){setSelected({id:row.id,restore:showDeleted});return;}if(showDeleted){void runSourceOperation(row.id,true);return;}if(pendingIds.includes(row.id)){onToggleDelete(row.id);return;}confirmDelete({title:`删除来源“${row.sourceFile}”?`,description:"将标记为待删除,当前报表暂不改变。在本页点击“确认删除并更新报表”后才生效,原文件和处理记录保留。",confirmText:"标记删除",onConfirm:()=>onToggleDelete(row.id)});}}>{simplified ? showDeleted ? '恢复并更新报表' : pendingIds.includes(row.id) ? '撤销删除' : '删除' : showDeleted ? '恢复' : '删除'}</Button>;
} },
]} locale={{ emptyText: showDeleted ? '没有已删除的来源。' : '尚无来源文件,点击“上传新数据”开始。' }} /> : null}
</section>
@@ -416,11 +430,15 @@ function DataUploadWizard({ user, mode, purpose, handoffSourceId, initialReason,
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 [wizardFiles, setWizardFiles] = useState<WizardFileDraft[]>([]); const [wizardFileId, setWizardFileId] = useState(''); 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 activeWizardFile = wizardFiles.find(item => item.id === wizardFileId) || wizardFiles[0];
const workbook = activeWizardFile?.workbook || null;
const sheetName = activeWizardFile?.sheetName || ''; const headerRow = activeWizardFile?.headerRow || 1; const fieldMap = activeWizardFile?.fieldMap || {};
const patchWizardFile = (values: Partial<WizardFileDraft>, id = activeWizardFile?.id) => { if (id) setWizardFiles(previous => previous.map(item => item.id === id ? { ...item, ...values } : item)); };
const setHeaderRow = (value: number) => patchWizardFile({ headerRow: value }); const setFieldMap = (value: Record<string, string>) => patchWizardFile({ fieldMap: value });
const configuredByFile = useRef(new Map<string, { signature: string; sourceId: string }>());
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>());
@@ -492,25 +510,49 @@ function DataUploadWizard({ user, mode, purpose, handoffSourceId, initialReason,
}
}, [loadCandidate, onComplete, reportError, runId, runStorageKey]);
useVisiblePolling(pollRun, 2000, active && Boolean(runId) && runTerminalId !== runId, true);
const readFile = async (file?: File) => {
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); }
const readFiles = async (selected: File[]) => {
if (!selected.length || actionLock.current) return; actionLock.current = true; setBusy(true); setError(''); const ownGeneration = generation.current;
try {
if (mode === 'REPLACE' && (selected.length > 1 || wizardFiles.length > 0)) throw new Error('替换时请选择一份文件;要追加多份文件,请返回“上传新数据”。');
if (selected.length + wizardFiles.length > 50) throw new Error('一次最多选择50个文件。');
const known = new Set(wizardFiles.map(item => `${item.file.name}:${item.file.size}:${item.file.lastModified}`));
const files = selected.filter(file => { const key = `${file.name}:${file.size}:${file.lastModified}`; if (known.has(key)) return false; known.add(key); return true; });
const ready: WizardFileDraft[] = []; const failures: string[] = []; let detectedStage: DataStage | null = wizardFiles.length ? stage : null;
for (const file of files) {
try {
const uploaded = await api.previewSourceWorkbook(file);
const detected = await detectSourceWorkbook(uploaded, options.fields, api.sourceWorkbookPreview);
if (!detectedStage) detectedStage = detected.stage;
ready.push({ id: crypto.randomUUID(), file, workbook: detected.workbook, sheetName: detected.workbook.preview.sheetName, headerRow: detected.workbook.preview.headerRow, fieldMap: matchFields(options.fields[detectedStage] || [], detected.workbook.preview.headers), fileId: crypto.randomUUID() });
} catch (value) { if (!onUnauthorized(value)) failures.push(`${file.name}:${failure(value)}`); }
}
if (ownGeneration !== generation.current) return;
if (ready.length) {
setWizardFiles(previous => [...previous, ...ready]);
setWizardFileId(previous => previous || ready[0].id);
if (detectedStage) setStage(detectedStage);
setStep(1);
}
if (failures.length) setError(`以下文件未加入本次导入,可重新选择:${failures.join(';')}`);
else if (!ready.length && !wizardFiles.length) setError('没有可加入的文件。');
}
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 || 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))) }); }
try { const result = await api.sourceWorkbookPreview(workbook.uploadId, { sheetName: nextSheet, headerRow: nextHeader, stage: nextStage }); const chosen = preferredMap || fieldMap; patchWizardFile({ workbook: result, sheetName: result.preview.sheetName, headerRow: result.preview.headerRow, fieldMap: { ...matchFields(options.fields[nextStage] || [], result.preview.headers), ...Object.fromEntries(Object.entries(chosen).filter(([, header]) => result.preview.headers.includes(header))) } }); }
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 removeWizardFile = (id: string) => { const next = wizardFiles.filter(item => item.id !== id); setWizardFiles(next); if (wizardFileId === id) setWizardFileId(next[0]?.id || ''); if (!next.length) setStep(0); configuredByFile.current.delete(id); };
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); setWizardFiles(previous => previous.map(item => ({ ...item, fieldMap: matchFields(options.fields[selected.stage] || [], item.workbook.preview.headers) }))); } };
const beginImport = async () => {
if (!active || !workbook || missingFields.length || (mode === 'REPLACE' && !target) || actionLock.current) return;
if (!active || !wizardFiles.length || wizardFiles.some(item => (options.fields[stage] || []).some(field => field.required && !item.fieldMap[field.name]) || Object.values(item.fieldMap).length !== new Set(Object.values(item.fieldMap)).size) || (mode === 'REPLACE' && (!target || wizardFiles.length !== 1)) || 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);
const items = wizardFiles.map(item => ({ id: item.id, body: { uploadId: item.workbook.uploadId, stage, year, month, sheetName: item.sheetName, headerRow: item.headerRow, fieldMap: item.fieldMap, mode: mode === 'REPLACE' ? 'REPLACE' as const : 'APPEND' as const, ...(mode === 'REPLACE' && target?.fileId ? { fileId: target.fileId } : mode === 'ADD' ? { fileId: item.fileId } : {}), expectedCurrentReleaseId: options.currentReleaseId, ...(mode === 'REPLACE' && target ? { targetDocumentId: target.documentId, targetRevisionId: target.revisionId } : {}), reason: reason.trim() || `${mode === 'REPLACE' ? '替换' : '追加'}${year}年${month}月${stageName(stage)}文件`, scopeCode } }));
const sourceIds = await configureSourceBatch(items, configuredByFile.current, body => api.configureSourceWorkbook(body));
const created = asRow(await api.startImport({ sourceIds, 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); }
@@ -549,13 +591,15 @@ function DataUploadWizard({ user, mode, purpose, handoffSourceId, initialReason,
const publishReady = release?.complete === true && reconciliation?.publishReady === true;
const steps = purpose === 'WITHDRAW' ? ['确认来源', '提交申请', '审批与候选', '来源校验', '对账与发布'] : mode === 'REBUILD' ? ['确认重算', '选择期间', '表头匹配', '计算校验', '对账与发布'] : ['选择文件', '确认期间', '工作表与表头', '预览与校验', '对账与发布'];
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>}>
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 && !busy && <Button onClick={() => { setStep(step - 1); setError(''); }}>上一步</Button>}<Button onClick={close}>{published ? '完成' : busy ? '关闭并稍后查看' : '关闭'}</Button>{!published && step === 1 && <Button type="primary" disabled={(mode === 'REPLACE' && !target) || !wizardFiles.length} loading={busy} onClick={() => { setStep(2); if (workbook) void changePreview(sheetName, headerRow); }}>下一步:匹配表头</Button>}{!published && step === 2 && <Button type="primary" loading={busy} disabled={wizardFiles.some(item => (options.fields[stage] || []).some(field => field.required && !item.fieldMap[field.name]) || Object.values(item.fieldMap).length !== new Set(Object.values(item.fieldMap)).size) || !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()) || !wizardFiles.length} onClick={() => void beginImport()}>确认导入并校验</Button>}</div></div>}>
<Steps className="nc-steps" current={published ? 5 : step} size="small" items={steps.map(title => ({ title }))} />
{mode !== 'REBUILD' && !purpose && <input className="visually-hidden-file" ref={input} type="file" multiple={mode === 'ADD'} accept=".xlsx" onChange={event => void readFiles(Array.from(event.target.files || []))} aria-label={mode === 'REPLACE' ? '选择要替换的质量数据Excel文件' : '选择要追加的质量数据Excel文件'} />}
{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>)}
{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>{mode === 'REPLACE' ? '替换一份已发布文件,其他来源保留。' : '文件会作为独立来源加入所选月份,并与已有来源合并统计。'} 请确保业务记录不与其他文件重叠。</p><Button type="primary" icon={<UploadOutlined />} loading={busy} onClick={() => input.current?.click()}>{mode === 'REPLACE' ? '选择替换文件' : '选择文件(可多选)'}</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>}
{wizardFiles.length > 0 && step > 0 && step < 4 && <><div className="nc-section-title"><strong>本次文件 · {wizardFiles.length} 份</strong>{mode === 'ADD' && step === 1 && <Button disabled={busy} icon={<UploadOutlined />} onClick={() => input.current?.click()}>继续添加本月文件</Button>}</div><Table size="small" rowKey="id" pagination={false} scroll={{ x: 600 }} dataSource={wizardFiles} columns={[{ title: '文件', key: 'file', render: (_, item) => <Button type="link" onClick={() => setWizardFileId(item.id)}>{item.workbook.sourceFile} · {item.fileId.slice(0, 8)}</Button> }, { title: '字段匹配', key: 'mapping', render: (_, item) => (options.fields[stage] || []).filter(field => field.required).every(field => item.fieldMap[field.name]) ? <Tag color="green">已完成</Tag> : <Tag color="orange">需核对</Tag> }, { title: '操作', key: 'action', render: (_, item) => configuredByFile.current.has(item.id) ? <Tag color="blue">已接收待导入</Tag> : <Button type="link" disabled={busy || mode === 'REPLACE'} onClick={() => removeWizardFile(item.id)}>移除</Button> }]} /></>}
{step === 1 && <Form layout="vertical"><div className="nc-form-grid">{mode === 'REPLACE' ? <Form.Item className="nc-full-width" label="选择要替换的具体文件" required><Select {...readableSelectPopup} aria-label="选择要替换的具体文件" disabled={Boolean(activeWizardFile && configuredByFile.current.has(activeWizardFile.id))} showSearch optionFilterProp="label" value={targetId || undefined} placeholder="选择年月、阶段、范围和文件" options={options.targets.map(item => ({ value: item.documentId, label: `${item.year}年${item.month}月 · ${stageName(item.stage)} · ${item.scopeCode} · ${item.sourceFile} · ${item.fileId ? `分批 ${item.fileId.slice(0, 8)}` : '整月文件'} (${item.documentId.slice(-6)})` }))} onChange={chooseTarget} /></Form.Item> : <><Form.Item label="数据阶段" required><Select aria-label="数据阶段" value={stage} options={[{ value: 'black', label: '黑片' }, { value: 'bright', label: '亮片' }]} onChange={value => { setStage(value); setWizardFiles(previous => previous.map(item => ({ ...item, fieldMap: matchFields(options.fields[value] || [], item.workbook.preview.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} · {target.fileId ? `分批 ${target.fileId.slice(0, 8)}` : '整月文件'}</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 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>}
+107
View File
@@ -0,0 +1,107 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import { Alert, Button, Spin, Tag } from 'antd';
import { ReloadOutlined } from '@ant-design/icons';
import { api, type SystemUpdateStatus } from './api';
import { configurationDateTime } from './configurationName';
import { usePageCache } from './pageCache';
import { useVisiblePolling } from './useVisiblePolling';
const runningStates = new Set(['queued', 'downloading', 'backingUp', 'installing', 'restarting', 'rollingBack']);
function errorStatus(error: unknown): number | undefined {
return error && typeof error === 'object' && 'status' in error && typeof error.status === 'number' ? error.status : undefined;
}
function reconnectable(error: unknown): boolean {
const status = errorStatus(error);
return status === 0 || status === 408 || (status !== undefined && status >= 500 && status <= 599);
}
export function SystemUpdatePanel({ onUnauthorized }: { onUnauthorized: (error: unknown) => boolean }) {
const { active } = usePageCache();
const [status, setStatus] = useState<SystemUpdateStatus>();
const [busy, setBusy] = useState(false);
const [error, setError] = useState('');
const [reconnecting, setReconnecting] = useState(false);
const [permissionDenied, setPermissionDenied] = useState(false);
const inFlight = useRef(false);
const restarting = useRef(false);
const running = !!status && runningStates.has(status.state);
const load = useCallback(async () => {
try {
const next = await api.systemUpdateStatus();
setStatus(next);
setError('');
setReconnecting(false);
setPermissionDenied(false);
restarting.current = runningStates.has(next.state);
} catch (failure) {
const denied = [401, 403].includes(errorStatus(failure) ?? -1);
const handled = onUnauthorized(failure);
if (handled || denied) {
restarting.current = false;
setReconnecting(false);
setPermissionDenied(true);
if (!handled) setError(failure instanceof Error ? failure.message : '无权查看更新状态');
} else if (restarting.current && reconnectable(failure)) {
setReconnecting(true);
} else {
restarting.current = false;
setReconnecting(false);
setError(failure instanceof Error ? failure.message : '更新状态读取失败');
}
}
}, [onUnauthorized]);
useEffect(() => { if (active) void load(); }, [active, load]);
useVisiblePolling(load, running || reconnecting ? 4_000 : 30_000, active && !permissionDenied);
const run = async (apply: boolean) => {
if (inFlight.current) return;
inFlight.current = true;
setBusy(true);
setError('');
try {
if (apply) restarting.current = true;
const next = await (apply ? api.applySystemUpdate() : api.checkSystemUpdate());
setStatus(next);
restarting.current = runningStates.has(next.state);
} catch (failure) {
// A successful updater intentionally takes the server offline. A lost
// response is resolved by polling the persisted task after restart.
if (apply && reconnectable(failure)) {
setReconnecting(true);
} else {
restarting.current = false;
const denied = [401, 403].includes(errorStatus(failure) ?? -1);
setPermissionDenied(denied);
if (!onUnauthorized(failure)) setError(failure instanceof Error ? failure.message : '更新操作失败');
if (!denied) void load();
}
} finally {
setBusy(false);
inFlight.current = false;
}
};
return <section className="panel section-panel">
<div className="completion-panel-heading">
<strong>系统更新</strong>
<div className="completion-actions">
<Button icon={<ReloadOutlined />} loading={busy && !restarting.current} disabled={!status?.enabled || running || reconnecting || busy} onClick={() => void run(false)}>检查更新</Button>
{status?.available && !running && !reconnecting && <Button type="primary" loading={busy && restarting.current} disabled={busy} onClick={() => void run(true)}>更新并重启</Button>}
</div>
</div>
{!status && !error && <Spin />}
{error && <Alert showIcon type="error" message={error} action={<Button size="small" onClick={() => void load()}>重试</Button>} />}
{reconnecting ? <Alert showIcon type="info" icon={<Spin size="small" />} message="正在重新启动,完成后将自动连接。" />
: status && <>
{status.enabled && <div className="governance-monitor-grid">
<div><small>当前版本</small><strong>{status.currentVersion || '—'}</strong></div>
{status.version && <div><small>{status.available ? '可用版本' : '最近检查版本'}</small><strong>{status.version}</strong></div>}
{status.checkedAt && <div><small>检查时间</small><strong>{configurationDateTime(status.checkedAt)}</strong></div>}
</div>}
<Alert showIcon type={status.state === 'failed' ? 'error' : status.state === 'completed' ? 'success' : 'info'}
message={<>{running && <Tag color="processing">更新中</Tag>}{status.message || '点击检查更新获取最新版本。'}</>} />
</>}
</section>;
}
+2 -1
View File
@@ -12,6 +12,7 @@ import { configurationDateTime } from './configurationName';
import { backupSummary, isActive, isFailed, monitorLabel, orderedTasks, taskFailure, taskPercent, type MonitorRow } from './taskMonitorModel';
import { useDelayedBusy } from './useDelayedBusy';
import { useVisiblePolling } from './useVisiblePolling';
import { SystemUpdatePanel } from './SystemUpdatePanel';
export function TasksMonitorPage({user,onUnauthorized}:{user:AuthUser;onUnauthorized:(error:unknown)=>boolean}) {
const {message}=App.useApp();
@@ -72,7 +73,7 @@ export function TasksMonitorPage({user,onUnauthorized}:{user:AuthUser;onUnauthor
{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}/> }] : []),
...(canManage ? [{ key:'monitor', label:'运行监控与告警', children:<OperationsMonitorPanel user={user} onUnauthorized={onUnauthorized}/> },{ key:'backups', label:'备份管理', children:<BackupOperationsPanel user={user} onUnauthorized={onUnauthorized}/> },{ key:'systemUpdate', label:'系统更新', children:<SystemUpdatePanel onUnauthorized={onUnauthorized}/> }] : []),
]} />
<Drawer open={!!selected} title="任务详情" width={Math.min(620,window.innerWidth)} onClose={()=>setSelected(null)}>{selected&&<dl className="nc-form-grid"><dt>任务</dt><dd>{monitorLabel(selected.type,'后台任务')}</dd><dt>状态</dt><dd>{monitorLabel(selected.status)}</dd><dt>阶段</dt><dd>{monitorLabel(selected.stage,monitorLabel(selected.status))}</dd>{Number(selected.total)>0&&<><dt>已处理 / 总数</dt><dd>{String(selected.processed??0)} / {String(selected.total)}</dd></>}<dt>提交时间</dt><dd>{configurationDateTime(selected.createdAt)}</dd>{isFailed(selected)&&<><dt>失败原因</dt><dd style={{whiteSpace:'pre-wrap',overflowWrap:'anywhere'}}>{taskFailure(selected)}</dd></>}<dt>任务编号</dt><dd style={{overflowWrap:'anywhere'}}>{String(selected.id)}</dd></dl>}{selected?.sourceKind==='TASK'&&<div className="completion-actions">{selected.status==='FAILED'&&!!selected.importRunId&&user.roles.some(role=>['SYSTEM_ADMIN', 'DATA_ADMIN'].includes(role))&&<Button loading={busy} onClick={()=>void runAction(selected,'retry')}>重试导入</Button>}{selected.status==='QUEUED'&&user.roles.some(role=>['SYSTEM_ADMIN', 'DATA_ADMIN'].includes(role))&&<Button danger loading={busy} onClick={()=>void runAction(selected,'cancel')}>取消排队任务</Button>}</div>}{selected?.sourceKind==='ANALYSIS'&&!!selected.sessionId&&<Button href={`?page=analysis&sessionId=${encodeURIComponent(String(selected.sessionId))}&turnId=${encodeURIComponent(String(selected.id))}`}>查看分析记录</Button>}</Drawer>
</>;
+15
View File
@@ -29,6 +29,18 @@ import type { ConfigureSourceBody, DataStage, DataWorkflowOperation, DataWorkflo
export { configureRequestScope, getRequestDiagnostics, invalidateReadResources, resetRequestScope };
export interface SystemUpdateStatus {
enabled: boolean;
currentVersion?: string;
state: string;
message?: string;
checkedAt?: string;
version?: string;
available?: boolean;
startedAt?: string;
finishedAt?: string;
}
export class ApiError extends Error {
status: number;
details: unknown;
@@ -206,6 +218,9 @@ async function mutateForm<T>(path: string, body: FormData): Promise<T> {
}
export const api = {
systemUpdateStatus() { return request<SystemUpdateStatus>('/api/system-update', {}, 12_000); },
checkSystemUpdate() { return mutate<SystemUpdateStatus>('/api/system-update/check', undefined, 'POST', 55_000); },
applySystemUpdate() { return mutate<SystemUpdateStatus>('/api/system-update/apply', undefined, 'POST', 55_000); },
exportSalesOrderTypes(signal?:AbortSignal) { return requestBlob('/api/sales-order-types/export',signal); },
salesOrderTypeStatus() { return request<SalesOrderTypeStatus>('/api/sales-order-types'); },
async salesOrderTypePreview(file:File,mode:string) {
+2
View File
@@ -16,6 +16,7 @@
.nc-workflow-modal { top: 24px; padding-bottom: 24px; }
.nc-workflow-modal .ant-modal-container, .nc-workflow-modal .ant-modal-content, .nc-workflow-modal .ant-input, .nc-workflow-modal .ant-input-number, .nc-workflow-modal .ant-select-selector, .nc-workflow-modal .ant-btn, .nc-workflow-modal .ant-alert { border-radius: 0 !important; }
.nc-workflow-modal .ant-modal-body { display: flex; flex-direction: column; gap: 18px; max-height: calc(var(--viewport-height) - 240px); overflow-y: auto; overflow-x: hidden; padding-right: 4px; color: var(--ink); }
.nc-workflow-modal .ant-modal-body > .quality-table-frame { flex-shrink: 0; }
.nc-workflow-modal .ant-modal-title { font-size: var(--font-dialog-title); color: var(--ink); }
.nc-workflow-modal h3 { font-size: var(--font-section); margin: 4px 0 12px; color: var(--ink); }
.nc-workflow-modal .ant-form-item { margin-bottom: 16px; }
@@ -156,3 +157,4 @@
@media (max-width: 1050px) { .nc-intake-start { grid-template-columns: 1fr; } .nc-primary-actions { margin-top: 20px; } .nc-intake-links { flex-wrap: wrap; gap: 0 16px; padding: 8px 0; } .nc-intake-links > span { margin-left: 0; width: 100%; padding: 5px 0; } .nc-column-matching { grid-template-columns: 1fr; } .nc-pending-strip { align-items: flex-start; flex-direction: column; } .nc-pending-strip .ant-select { min-width: 0; width: 100%; } }
@media (max-width: 680px) { .nc-intake-start { padding: 20px 18px 0; } .nc-intake-intro h2 { font-size: var(--font-page-title); } .nc-primary-actions { flex-wrap: wrap; } .nc-form-grid { grid-template-columns: 1fr; } .nc-modal-footer { flex-direction: column; align-items: stretch; } .nc-modal-footer > div { justify-content: flex-end; flex-wrap: wrap; } .nc-file-summary { flex-wrap: wrap; } .nc-file-summary > span:last-child { margin-left: 0; } .nc-workbook-upload-intro { flex-direction: column; align-items: flex-start; } .nc-pending-strip > div:first-child { align-items: flex-start; flex-direction: column; gap: 6px; } .nc-review-facts { grid-template-columns: 1fr 1fr; } }
@media (max-width: 680px) { .nc-source-delete-modal .nc-deletion-impact { grid-template-columns: 1fr 1fr; } }
.nc-source-maintenance-actions { display: flex; flex-wrap: wrap; gap: 10px; margin: 0 16px 16px; }
+32
View File
@@ -0,0 +1,32 @@
export type SourceConfigureBody = { uploadId: string; fileId?: string };
export type ConfiguredSourceCandidate = { signature: string; sourceId: string };
type ConfigureItem<TBody extends SourceConfigureBody> = { id: string; body: TBody };
type ConfigureResult = { source: { id: string } };
/** Reuses confirmed candidate IDs and retries changed discovered candidates with the same upload/file identity. */
export async function configureSourceBatch<TBody extends SourceConfigureBody>(
items: ConfigureItem<TBody>[],
configured: Map<string, ConfiguredSourceCandidate>,
configure: (body: TBody) => Promise<ConfigureResult>,
onConfigured?: (candidate: ConfiguredSourceCandidate) => void,
): Promise<string[]> {
const sourceIds: string[] = [];
for (const item of items) {
const signature = JSON.stringify(item.body);
const prior = configured.get(item.id);
if (prior?.signature === signature) {
sourceIds.push(prior.sourceId);
continue;
}
// The server updates an existing DISCOVERED candidate in place when the same
// uploadId/fileId is sent again. Do not mint another upload or logical file ID.
const result = await configure(item.body);
const candidate = { signature, sourceId: result.source.id };
configured.set(item.id, candidate);
onConfigured?.(candidate);
sourceIds.push(candidate.sourceId);
}
return sourceIds;
}
+78
View File
@@ -0,0 +1,78 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { configureSourceBatch } from '../src/sourceBatchConfigure.ts';
type Body = { uploadId: string; fileId: string; year: number; fieldMap: Record<string, string> };
type Candidate = { id: string; status: 'DISCOVERED' | 'RUNNING'; body: Body };
function candidateService() {
const byIdentity = new Map<string, Candidate>();
const calls: Body[] = [];
const configure = async (body: Body) => {
calls.push(body);
const identity = `${body.uploadId}:${body.fileId}`;
const previous = byIdentity.get(identity);
if (previous && previous.status !== 'DISCOVERED') throw new Error('409 candidate is no longer editable');
const candidate = previous || { id: `candidate-${body.fileId}`, status: 'DISCOVERED' as const, body };
candidate.body = body;
byIdentity.set(identity, candidate);
return { source: { id: candidate.id } };
};
return { byIdentity, calls, configure };
}
const item = (id: string, fileId = id, year = 2026): { id: string; body: Body } => ({
id,
body: { uploadId: `upload-${id}`, fileId, year, fieldMap: { weight: '重量' } },
});
test('keeps the confirmed source ID when a later file fails, then retries only the failed file', async () => {
const service = candidateService();
const configured = new Map();
const files = [item('A'), item('B')];
let bAttempts = 0;
const configure = async (body: Body) => {
if (body.fileId === 'B' && ++bAttempts === 1) throw new Error('temporary configure failure');
return service.configure(body);
};
await assert.rejects(configureSourceBatch(files, configured, configure), /temporary configure failure/);
assert.equal(configured.get('A').sourceId, 'candidate-A');
assert.equal(configured.has('B'), false);
const sourceIds = await configureSourceBatch(files, configured, configure);
assert.deepEqual(sourceIds, ['candidate-A', 'candidate-B']);
assert.equal(service.calls.filter(body => body.fileId === 'A').length, 1);
assert.equal(service.calls.filter(body => body.fileId === 'B').length, 1);
});
test('reconfigures changed metadata with the original uploadId and fileId while preserving the candidate ID', async () => {
const service = candidateService();
const configured = new Map();
const first = item('A', 'logical-A', 2025);
const second = item('A', 'logical-A', 2026);
const [initialId] = await configureSourceBatch([first], configured, service.configure);
const [updatedId] = await configureSourceBatch([second], configured, service.configure);
assert.equal(initialId, updatedId);
assert.equal(service.calls.length, 2);
assert.equal(service.calls[0].uploadId, service.calls[1].uploadId);
assert.equal(service.calls[0].fileId, service.calls[1].fileId);
assert.equal(service.byIdentity.get('upload-A:logical-A')?.body.year, 2026);
});
test('does not replace the cached candidate when the server rejects edits after processing starts', async () => {
const service = candidateService();
const configured = new Map();
const first = item('A', 'logical-A', 2025);
const changed = item('A', 'logical-A', 2026);
await configureSourceBatch([first], configured, service.configure);
const candidate = service.byIdentity.get('upload-A:logical-A');
assert.ok(candidate);
candidate.status = 'RUNNING';
await assert.rejects(configureSourceBatch([changed], configured, service.configure), /409 candidate is no longer editable/);
assert.equal(configured.get('A').signature, JSON.stringify(first.body));
});
+1 -1
View File
@@ -8,7 +8,7 @@ function fixture() {
const end=source.includes('export function TrendTable(')?source.indexOf('export function TrendTable('):source.indexOf('function TrendTable(');
const code=source.slice(source.indexOf('export function TrendChart('),end).replace('export function','function');
const slots=new Map(),effects=new Map(),observers=[],charts=[];let cursor=0,dirty=false,queued=[],active=true,visible=true;
const node={clientWidth:900,clientHeight:380};
const node={clientWidth:900,clientHeight:380,closest(){return null;}};
const hooks={useRef(initial){const i=cursor++;if(!slots.has(i))slots.set(i,{current:initial});return slots.get(i);},useState(initial){const i=cursor++;if(!slots.has(i))slots.set(i,initial);return [slots.get(i),v=>{const next=typeof v==='function'?v(slots.get(i)):v;if(!Object.is(next,slots.get(i))){slots.set(i,next);dirty=true;}}];},useCallback(fn,deps){const i=cursor++;const old=slots.get(i);if(!old||deps.some((d,j)=>!Object.is(d,old.deps[j])))slots.set(i,{fn,deps});return slots.get(i).fn;},useEffect(fn,deps){const i=cursor++,old=effects.get(i);if(!old||deps.some((d,j)=>!Object.is(d,old.deps[j])))queued.push(()=>{old?.cleanup?.();effects.set(i,{deps,cleanup:fn()});});}};
hooks.useLayoutEffect=hooks.useEffect;
const ec={init(_node,_theme,opts){const c={opts,options:[],resizes:[],disposed:false,getWidth:()=>c.opts.width??100,getHeight:()=>c.opts.height??380,on(){},resize(o){c.resizes.push(o);},setOption(o){c.options.push(o);},convertToPixel:()=>0,dispose(){c.disposed=true;}};charts.push(c);return c;}};
@@ -10,7 +10,7 @@ function fixture(){
const source=fs.readFileSync(process.env.QUERY_PARETO_SOURCE || new URL('../src/QueryPage.tsx',import.meta.url),'utf8');
const component=source.slice(source.indexOf('export function DefectParetoPanel('),source.indexOf('export function SectionHeading(')).replace('export function','function');
const requests=[],options=[],effects=new Map(),states=new Map(),refs=new Map();let cursor=0,dirty=false,queued=[],tree,creates=0,clears=0;
const node={clientWidth:900,clientHeight:470};
const node={clientWidth:900,clientHeight:470,closest(){return null;}};
const hooks={useState(initial){const i=cursor++;if(!states.has(i))states.set(i,initial);return [states.get(i),v=>{states.set(i,typeof v==='function'?v(states.get(i)):v);dirty=true;}];},useRef(initial){const i=cursor++;if(!refs.has(i))refs.set(i,{current:initial});return refs.get(i);},useMemo(fn){cursor++;return fn();},useEffect(fn,deps){const i=cursor++,old=effects.get(i);if(!old||deps.some((x,j)=>!Object.is(x,old.deps[j])))queued.push(()=>{old?.cleanup?.();effects.set(i,{deps,cleanup:fn()});});}};
const api={fineDefectTop(params,signal){const d=deferred();requests.push({...d,params,signal});return d.promise;}};
const chart={setOption:(value,config)=>options.push({value,config}),clear(){clears++;},resize(){},dispose(){}};
@@ -0,0 +1,32 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import ts from 'typescript';
const deferred=()=>{let resolve,reject;const promise=new Promise((r,j)=>{resolve=r;reject=j;});return{promise,resolve,reject};};
function fixture(){
const source=fs.readFileSync(new URL('../src/useDeleteConfirmation.ts',import.meta.url),'utf8').replace(/^import .*;\n/gm,'').replace('export function','function');
const dialogs=[],cleanups=[];
const App={useApp:()=>({modal:{confirm(options){const dialog={options,updates:[],destroyed:false,update(value){this.updates.push(value);},destroy(){this.destroyed=true;options.afterClose();}};dialogs.push(dialog);return dialog;}}})};
const compiled=ts.transpileModule(source,{compilerOptions:{target:ts.ScriptTarget.ES2022,module:ts.ModuleKind.None}}).outputText;
const open=new Function('App','useCallback','useEffect','useRef',compiled+'\nreturn useDeleteConfirmation();')(App,fn=>fn,effect=>cleanups.push(effect()),value=>({current:value}));
return{open,dialogs,unmount:()=>cleanups.forEach(fn=>fn?.())};
}
test('opening or cancelling a deletion never changes data, including a late confirm callback',async()=>{
const f=fixture(),rows=['a','b'];f.open({title:'删除a?',description:'仅修改草稿',onConfirm:()=>rows.splice(0,1)});
assert.deepEqual(rows,['a','b']);const d=f.dialogs[0];assert.equal(d.options.autoFocusButton,'cancel');assert.equal(d.options.maskClosable,false);assert.equal(d.options.okButtonProps.danger,true);
d.options.onCancel();await d.options.onOk();assert.deepEqual(rows,['a','b']);d.destroy();
});
test('explicit confirmation performs an async action only once and disables cancellation while running',async()=>{
const f=fixture(),work=deferred();let writes=0;f.open({title:'删除a?',description:'立即生效',onConfirm:()=>{writes++;return work.promise;}});
const d=f.dialogs[0],first=d.options.onOk();await d.options.onOk();assert.equal(writes,1);assert.equal(d.updates.at(-1).cancelButtonProps.disabled,true);work.resolve();await first;d.destroy();
});
test('a failed confirmed request can be retried without losing the active confirmation',async()=>{
const f=fixture();let writes=0;f.open({title:'删除a?',description:'立即生效',onConfirm:()=>{if(++writes===1)throw Error('request failed');}});
const d=f.dialogs[0];await assert.rejects(d.options.onOk(),/request failed/);assert.equal(d.destroyed,false);assert.equal(d.updates.at(-1).cancelButtonProps.disabled,false);await d.options.onOk();assert.equal(writes,2);
});
test('leaving the component closes its confirmation and cannot trigger deletion afterwards',async()=>{
const f=fixture();let writes=0;f.open({title:'删除a?',description:'立即生效',onConfirm:()=>writes++});const d=f.dialogs[0];f.unmount();assert.equal(d.destroyed,true);await d.options.onOk();assert.equal(writes,0);
});
test('repeated delete clicks show one confirmation, and closing it allows a different target',async()=>{
const f=fixture();const writes=[];f.open({title:'a',description:'a',onConfirm:()=>writes.push('a')});f.open({title:'b',description:'b',onConfirm:()=>writes.push('b')});assert.equal(f.dialogs.length,1);f.dialogs[0].destroy();f.open({title:'b',description:'b',onConfirm:()=>writes.push('b')});assert.equal(f.dialogs.length,2);await f.dialogs[1].options.onOk();assert.deepEqual(writes,['b']);
});
@@ -0,0 +1,64 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import ts from 'typescript';
import React from 'react';
const tick = () => new Promise(resolve => setImmediate(resolve));
function fixture() {
const source = fs.readFileSync(new URL('../src/SystemUpdatePanel.tsx', import.meta.url), 'utf8')
.replace(/^import[\s\S]*?;\n/gm, '').replace(/export /g, '');
let cursor = 0, dirty = false, queued = [], polling, pollingEnabled, tree, failure;
const states = new Map(), refs = new Map(), memo = new Map(), effects = new Map(), authHandled = [];
let server = { enabled: true, state: 'available', available: true, version: '2', currentVersion: '1' };
const props = { onUnauthorized(error) { if ([401, 403].includes(error?.status)) authHandled.push(error.status); return error?.status === 401; } };
const hooks = {
useState(initial) { const i = cursor++; if (!states.has(i)) states.set(i, initial); return [states.get(i), next => { states.set(i, next); dirty = true; }]; },
useRef(initial) { const i = cursor++; if (!refs.has(i)) refs.set(i, { current: initial }); return refs.get(i); },
useCallback(fn, deps) { const i = cursor++, old = memo.get(i); if (!old || deps.some((value, j) => value !== old.deps[j])) memo.set(i, { fn, deps }); return memo.get(i).fn; },
useEffect(fn, deps) { const i = cursor++, old = effects.get(i); if (!old || deps.some((value, j) => value !== old.deps[j])) queued.push(() => { effects.set(i, { deps }); fn(); }); },
};
const api = {
async systemUpdateStatus() { if (failure !== undefined) { const status = failure; failure = undefined; throw Object.assign(Error('connection-or-session-error'), { status }); } return { ...server }; },
async applySystemUpdate() { server = { ...server, state: 'queued', available: false }; return { ...server }; },
async checkSystemUpdate() { return { ...server }; },
};
const prelude = 'const {useState,useRef,useCallback,useEffect}=hooks;';
const compiled = ts.transpileModule(prelude + source + '\nreturn SystemUpdatePanel;',
{ fileName: 'fixture.tsx', compilerOptions: { target: ts.ScriptTarget.ES2022, jsx: ts.JsxEmit.React } }).outputText;
const component = new Function('React', 'hooks', 'api', 'usePageCache', 'useVisiblePolling', 'configurationDateTime',
'Alert', 'Button', 'Spin', 'Tag', 'ReloadOutlined', compiled)(React, hooks, api, () => ({ active: true }),
(callback, interval, enabled) => { polling = callback; pollingEnabled = enabled; }, value => value, 'Alert', 'Button', 'Spin', 'Tag', 'ReloadOutlined');
const render = () => { let attempts = 0; do { cursor = 0; dirty = false; queued = []; tree = component(props); queued.forEach(fn => fn()); assert.ok(++attempts < 15); } while (dirty); return tree; };
const buttons = () => { const result = []; function walk(node) { if (!node || typeof node !== 'object') return; if (node.type === 'Button') result.push(node); React.Children.forEach(node.props?.children, walk); } walk(tree); return result; };
return {
authHandled, reconnecting: () => states.get(3), error: () => states.get(2), pollingEnabled: () => pollingEnabled,
async start() { render(); await tick(); render(); },
async apply() { const button = buttons().find(node => node.props.children === '更新并重启'); assert.ok(button); button.props.onClick(); await tick(); render(); },
async failPoll(status) { failure = status; await polling(); render(); },
async complete() { server = { ...server, state: 'completed', message: '更新完成。', currentVersion: '2' }; await polling(); render(); },
};
}
for (const status of [401, 403]) test(`restart polling forwards ${status} to authentication handling`, async () => {
const ui = fixture(); await ui.start(); await ui.apply(); await ui.failPoll(status);
assert.deepEqual(ui.authHandled, [status]);
assert.equal(ui.reconnecting(), false);
assert.equal(ui.pollingEnabled(), false);
if (status === 403) assert.equal(ui.error(), 'connection-or-session-error');
});
test('temporary restart connection loss reconnects and clears after completion', async () => {
const ui = fixture(); await ui.start(); await ui.apply(); await ui.failPoll(503);
assert.equal(ui.reconnecting(), true);
assert.deepEqual(ui.authHandled, []);
await ui.complete();
assert.equal(ui.reconnecting(), false);
});
test('a permanent route failure is displayed rather than treated as a restart connection loss', async () => {
const ui = fixture(); await ui.start(); await ui.apply(); await ui.failPoll(404);
assert.equal(ui.reconnecting(), false);
assert.equal(ui.error(), 'connection-or-session-error');
});
@@ -5,6 +5,7 @@ import ts from 'typescript';
import React from 'react';
import { readQueryLocation } from '../src/queryLoadingScope.ts';
import { pageUsesResources } from '../src/resourceInvalidation.ts';
import { canAccessWorkspacePage } from '../src/userRoles.ts';
const tick = () => new Promise(resolve => setImmediate(resolve));
const deferred = () => { let resolve, reject; const promise = new Promise((a, b) => { resolve = a; reject = b; }); return { promise, resolve, reject }; };
@@ -15,8 +16,8 @@ function fixture() {
const values = new Map(), refs = new Map(), effects = new Map(), events = new Map(), navigations = [], scopes = [];
let cursor = 0, dirty = false, queued = [], tree;
let state = { authRevision: 'a1', dataRevision: 'd1', currentReleaseId: 'r1' }, failState = false, failStatus, me, optionReads=0, optionDenied=false;
const props = { page: 'overall', user: { id: 'A' }, onUnauthorized: () => false,
onPageChange(page) { props.page = page; dirty = true; }, onUserChange(user) { props.user = user; dirty = true; } };
const props = { page: 'overall', user: { id: 'A', roles: ['USER'] }, onUnauthorized: () => false,
onPageChange(page) { props.page = page; dirty = true; }, onUserChange(user) { props.user = { roles: ['USER'], ...user }; dirty = true; } };
const ref = { current: null };
const hooks = {
useState(initial) { const i = cursor++; if (!values.has(i)) values.set(i, typeof initial === 'function' ? initial() : initial); return [values.get(i), next => { values.set(i, typeof next === 'function' ? next(values.get(i)) : next); dirty = true; }]; },
@@ -26,6 +27,7 @@ function fixture() {
};
const api = { async options() { optionReads++; if(optionDenied) { events.get('quality-permission-recheck')?.(); throw Object.assign(Error('denied'),{status:403}); } return {}; }, async sourceColumnCatalog() { return {}; }, async workspaceState() { if (failState) { failState = false; throw Object.assign(Error('temporary-offline'), { status: failStatus }); } return { ...state }; }, async me() { return me ? me.promise : props.user; } };
const env = {
canAccessWorkspacePage,
location: { search: '?page=overall', pathname: '/' },
window: { scrollY: 0, scrollTo() {}, matchMedia: () => ({ matches: false }), addEventListener: (name, fn) => events.set(name, fn), removeEventListener: name => events.delete(name) },
document: { visibilityState: 'visible', addEventListener: (name, fn) => events.set(name, fn), removeEventListener: name => events.delete(name), querySelector() {} },
@@ -43,7 +45,7 @@ function fixture() {
const render = () => { let attempts = 0; do { cursor = 0; dirty = false; queued = []; tree = component(props, ref); queued.forEach(fn => fn()); assert.ok(++attempts < 15); } while (dirty); return tree; };
const pages = () => { const result = []; function walk(node) { if (!node || typeof node !== 'object') return; if (node.props?.['data-page']) result.push(node.props['data-page']); React.Children.forEach(node.props?.children, walk); } walk(tree); return result; };
return { render, pages, props, scopes, ref, async start() { render(); await tick(); render(); }, async settle() { await Promise.all(navigations); await tick(); render(); },
getOptionReads:()=>optionReads,denyOptions(){optionDenied=true;},failNextState(status) { failState = true; failStatus = status; }, changeIdentity() { state = { ...state, authRevision: 'b2' }; me = deferred(); return me; },
locationSearch:()=>env.location.search,getOptionReads:()=>optionReads,denyOptions(){optionDenied=true;},failNextState(status) { failState = true; failStatus = status; }, changeIdentity() { state = { ...state, authRevision: 'b2' }; me = deferred(); return me; },
async focus() { events.get('focus')?.(); await tick(); render(); }, cleanup() { effects.forEach(effect => effect.cleanup?.()); } };
}
@@ -86,3 +88,20 @@ test('a forbidden options resource does not trigger repeated warm reads during p
const ui=fixture();ui.denyOptions();await ui.start();await tick();ui.render();const count=ui.getOptionReads();
await ui.focus();await tick();ui.render();assert.equal(ui.getOptionReads(),count);assert.ok(count<=1);ui.cleanup();
});
test('sales order type survives cross-stage navigation and clearing without copying stage source filters',async()=>{
const ui=fixture();await ui.start();
ui.ref.current.navigate('blackProduct',{year:2026,view:'product',extraFilters:{salesOrderType:['样品销售订单']},columnFilters:[{field:'blackOnly',stages:['black'],operator:'in',values:['A']}]});await ui.settle();
ui.ref.current.navigate('brightProduct');await ui.settle();
const bright=readQueryLocation(ui.locationSearch());assert.deepEqual(bright.extraFilters,{salesOrderType:['样品销售订单']});assert.equal(bright.columnFilters,undefined);
ui.ref.current.navigate('brightProduct',{year:2026,view:'product',extraFilters:{}});await ui.settle();
ui.ref.current.navigate('blackProduct');await ui.settle();
const black=readQueryLocation(ui.locationSearch());assert.deepEqual(black.extraFilters,{});assert.equal(black.columnFilters[0].field,'blackOnly');ui.cleanup();
});
test('sales order exclusions retain their mode on navigation',async()=>{
const ui=fixture();await ui.start();
ui.ref.current.navigate('overall',{year:2026,view:'overall',extraFilters:{salesOrderTypeNotIn:['样品销售订单']}});await ui.settle();
ui.ref.current.navigate('blackProduct');await ui.settle();
assert.deepEqual(readQueryLocation(ui.locationSearch()).extraFilters,{salesOrderTypeNotIn:['样品销售订单']});ui.cleanup();
});
+29
View File
@@ -0,0 +1,29 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import ts from 'typescript';
const source = ts.transpileModule(readFileSync(new URL('../src/userRoles.ts', import.meta.url), 'utf8'), {
compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.ESNext },
}).outputText.replace(/export /g, '');
const { USER_ROLE_OPTIONS, canAccessWorkspacePage } = new Function(`${source};return { USER_ROLE_OPTIONS, canAccessWorkspacePage };`)();
test('only three assigned roles are exposed with the agreed names', () => {
assert.deepEqual(USER_ROLE_OPTIONS, [{ value: 'USER', label: '用户' }, { value: 'DATA_ADMIN', label: '数据管理员' }, { value: 'SYSTEM_ADMIN', label: '系统管理员' }]);
});
test('higher roles inherit business pages while system settings stay system-only', () => {
for (const role of ['USER', 'DATA_ADMIN', 'SYSTEM_ADMIN']) {
const user = { roles: [role] };
for (const page of ['overall', 'department', 'product', 'blackProduct', 'brightProduct', 'analysis'])
assert.equal(canAccessWorkspacePage(user, page), true, `${role}: ${page}`);
for (const page of ['sources', 'imports', 'rules', 'mappings', 'masterData', 'tasks'])
assert.equal(canAccessWorkspacePage(user, page), role !== 'USER', `${role}: ${page}`);
assert.equal(canAccessWorkspacePage(user, 'access'), role === 'SYSTEM_ADMIN');
}
});
test('unexpected or multiple role assignments do not expose management pages', () => {
for (const roles of [[], ['QUALITY_VIEWER'], ['USER', 'SYSTEM_ADMIN']])
assert.equal(canAccessWorkspacePage({ roles }, 'access'), false);
});