修复:清理导入历史失败提示并识别旧文件年份

This commit is contained in:
2026-11-04 12:06:48 +08:00
parent f04d4e96e3
commit 866ba21bb8
6 changed files with 108 additions and 21 deletions
+11 -8
View File
@@ -8,7 +8,7 @@ import { api, collectionItems } from './api';
import type { AuthUser, SourceItem } from './types'; import type { AuthUser, SourceItem } from './types';
import type { DataField, DataStage, DataWorkflowOperation, DataWorkflowStatus, DeletionSource, MasterWorkbookKeyFormat, MasterWorkbookKind, MasterWorkbookPreview, SourceDeletionPreview, SourceUploadOptions, WorkbookPreview } from './NoCodeDataTypes'; import type { DataField, DataStage, DataWorkflowOperation, DataWorkflowStatus, DeletionSource, MasterWorkbookKeyFormat, MasterWorkbookKind, MasterWorkbookPreview, SourceDeletionPreview, SourceUploadOptions, WorkbookPreview } from './NoCodeDataTypes';
import { useDataWorkflowOperation } from './useDataWorkflowOperation'; import { useDataWorkflowOperation } from './useDataWorkflowOperation';
import { detectSourceWorkbook } from './sourceWorkbookDetection'; import { detectSourceWorkbook, sourceBatchYear, sourceFilenamePeriod } from './sourceWorkbookDetection';
import { readableSelectPopup } from './readableSelectPopup'; import { readableSelectPopup } from './readableSelectPopup';
import { usePageCache } from './pageCache'; import { usePageCache } from './pageCache';
import { useDelayedBusy, useDelayedIndicator } from './useDelayedBusy'; import { useDelayedBusy, useDelayedIndicator } from './useDelayedBusy';
@@ -39,10 +39,11 @@ function ColumnMatching({ fields, headers, value, onChange, disabled = false }:
const workflowStageLabel: Record<string, string> = { QUEUED: '等待处理', VALIDATING: '检查来源与配置', VERSION_CREATED: '保存更新', REBUILDING: '重新计算报表', PUBLISHING: '更新当前报表', RESTORING_SOURCE: '恢复来源并重算', SOURCE_RESTORED: '来源已恢复并更新报表', COMPLETED: '已完成', FAILED: '处理失败' }; const workflowStageLabel: Record<string, string> = { QUEUED: '等待处理', VALIDATING: '检查来源与配置', VERSION_CREATED: '保存更新', REBUILDING: '重新计算报表', PUBLISHING: '更新当前报表', RESTORING_SOURCE: '恢复来源并重算', SOURCE_RESTORED: '来源已恢复并更新报表', COMPLETED: '已完成', FAILED: '处理失败' };
function WorkflowOperationFeedback({ operation, error, busy, onResume }: { operation: DataWorkflowOperation | null; error: string; busy: boolean; onResume: () => void }) { function WorkflowOperationFeedback({ operation, error, busy, onResume, onDismiss }: { operation: DataWorkflowOperation | null; error: string; busy: boolean; onResume: () => void; onDismiss: () => void }) {
if (!operation && !error) return null; if (!operation && !error) return null;
const status = String(operation?.status || '').toUpperCase(); const status = String(operation?.status || '').toUpperCase();
const errors = Array.isArray(operation?.errors) ? operation.errors.map(item => item.message).filter(Boolean) : []; const errors = Array.isArray(operation?.errors) ? operation.errors.map(item => item.message).filter(Boolean) : [];
if (status === 'FAILED') return <section className="nc-operation-status panel"><Alert showIcon type={operation?.restoredFromPreviousVisit ? 'warning' : 'error'} message={operation?.restoredFromPreviousVisit ? '上次操作未完成' : '本次操作未完成'} description={<>{[...new Set([...errors, error].filter(Boolean))].join(';')}{operation?.restoredFromPreviousVisit && <p>这是上次操作的历史结果,当前报表以已发布数据为准。详细记录可在“导入记录”中查看。</p>}</>} closable onClose={onDismiss} /></section>;
return <section className="nc-operation-status panel"> return <section className="nc-operation-status panel">
{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} />} {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> <div><strong>{workflowStageLabel[String(operation?.stage || operation?.status)] || (busy ? '正在处理' : status === 'COMPLETED' ? '报表已更新' : '操作状态')}</strong></div>
@@ -104,14 +105,16 @@ function SimplifiedDataWorkflow({ options, workflowStatus, pendingDeletion, onBu
setBusy(true); setError(''); const failures: string[] = []; setBusy(true); setError(''); const failures: string[] = [];
const known = new Set(drafts.map(item => `${item.file.name}:${item.file.size}:${item.file.lastModified}`)); const known = new Set(drafts.map(item => `${item.file.name}:${item.file.size}:${item.file.lastModified}`));
const selected = files.filter(file => { const key = `${file.name}:${file.size}:${file.lastModified}`; if (known.has(key)) return false; known.add(key); return true; }); const selected = files.filter(file => { const key = `${file.name}:${file.size}:${file.lastModified}`; if (known.has(key)) return false; known.add(key); return true; });
const batchYear = sourceBatchYear([...drafts.map(item => item.file.name), ...selected.map(file => file.name)], new Date().getFullYear());
setReading({ done: 0, total: selected.length }); setReading({ done: 0, total: selected.length });
for (let index = 0; index < selected.length; index += 2) { for (let index = 0; index < selected.length; index += 2) {
const results = await Promise.all(selected.slice(index, index + 2).map(async file => { const results = await Promise.all(selected.slice(index, index + 2).map(async file => {
try { try {
const uploaded = await api.previewSourceWorkbook(file); const uploaded = await api.previewSourceWorkbook(file);
const { workbook: result, stage: detected } = await detectSourceWorkbook(uploaded, options.fields, api.sourceWorkbookPreview); 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 period = sourceFilenamePeriod(file.name);
const nextYear = Number(file.name.match(/(20\d{2})年/)?.[1] || new Date().getFullYear()); const nextMonth = period.month || new Date().getMonth() + 1;
const nextYear = period.year || batchYear;
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' }; 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; } } catch (value) { if (!onUnauthorized(value)) failures.push(`${file.name}:${failure(value)}`); return null; }
})); }));
@@ -186,8 +189,8 @@ function SimplifiedDataWorkflow({ options, workflowStatus, pendingDeletion, onBu
{missing.length > 0 && <Alert showIcon type="warning" message="有必填列尚未识别" description={`请展开“列识别与预览”完成:${missing.map(item => item.name).join('、')}`} />} {missing.length > 0 && <Alert showIcon type="warning" message="有必填列尚未识别" description={`请展开“列识别与预览”完成:${missing.map(item => item.name).join('、')}`} />}
<div className="nc-simple-submit-row"><span>{mode === 'REPLACE' ? '替换后会按当前规则重算并更新对应报表。' : `${year}年${String(month).padStart(2, '0')}月 · ${stageName(stage)} · 完成后自动刷新报表`}</span>{hasImportCapability && <Button type="primary" size="large" loading={busy || uploadOperation.busy} disabled={!canImport || busy || uploadOperation.busy} onClick={() => void importAndUpdate()}>{`导入 ${drafts.length} 个文件并更新报表`}</Button>}</div> <div className="nc-simple-submit-row"><span>{mode === 'REPLACE' ? '替换后会按当前规则重算并更新对应报表。' : `${year}年${String(month).padStart(2, '0')}月 · ${stageName(stage)} · 完成后自动刷新报表`}</span>{hasImportCapability && <Button type="primary" size="large" loading={busy || uploadOperation.busy} disabled={!canImport || busy || uploadOperation.busy} onClick={() => void importAndUpdate()}>{`导入 ${drafts.length} 个文件并更新报表`}</Button>}</div>
</>} </>}
<WorkflowOperationFeedback operation={uploadOperation.operation} error={uploadOperation.error} busy={uploadOperation.busy} onResume={uploadOperation.resume} /> <WorkflowOperationFeedback operation={uploadOperation.operation} error={uploadOperation.error} busy={uploadOperation.busy} onResume={uploadOperation.resume} onDismiss={uploadOperation.clear} />
<WorkflowOperationFeedback operation={recalcOperation.operation} error={recalcOperation.error} busy={recalcOperation.busy} onResume={recalcOperation.resume} /> <WorkflowOperationFeedback operation={recalcOperation.operation} error={recalcOperation.error} busy={recalcOperation.busy} onResume={recalcOperation.resume} onDismiss={recalcOperation.clear} />
</section> </section>
</div>; </div>;
} }
@@ -322,7 +325,7 @@ export function SourceFilesPanel({ user, sources, sourcesLoaded, loading, pendin
{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>} {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>} />} {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>} />} {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 || sourceOperation.error) && <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} onDismiss={sourceOperation.clear} />}
{(!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={[ {(!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: 'sourceFile', key: 'sourceFile', width: 340, ellipsis: true },
{ title: '阶段', dataIndex: 'stage', key: 'stage', align: 'center', width: 90, render: value => <Tag>{stageName(value)}</Tag> }, { title: '阶段', dataIndex: 'stage', key: 'stage', align: 'center', width: 90, render: value => <Tag>{stageName(value)}</Tag> },
@@ -711,7 +714,7 @@ export function MasterWorkbookUpload({ kind, base, onUnauthorized, onComplete, s
<Modal className="management-modal nc-workflow-modal" open={open} title={`上传${kind === 'masterData' ? '基础数据表' : '对应关系表'}`} width={1040} onCancel={() => setOpen(false)} footer={<div className="nc-modal-footer"><span>{simplified ? '导入后自动保存配置、重算并更新报表。' : result ? '草稿经过校验并启用后,再重新计算和发布数据。' : '导入只创建新草稿,先预览、再确认。'}</span><div><Button onClick={() => setOpen(false)}>{result ? '完成' : '取消'}</Button>{(!result || simplified && Boolean(error || workflowOperation.error)) && <Button type="primary" disabled={!canSubmit || workflowOperation.busy} loading={busy || workflowOperation.busy} onClick={() => void submit()}>{simplified && result ? '重试保存并更新报表' : simplified ? '导入并更新报表' : '确认导入为草稿'}</Button>}</div></div>}> <Modal className="management-modal nc-workflow-modal" open={open} title={`上传${kind === 'masterData' ? '基础数据表' : '对应关系表'}`} width={1040} onCancel={() => setOpen(false)} footer={<div className="nc-modal-footer"><span>{simplified ? '导入后自动保存配置、重算并更新报表。' : result ? '草稿经过校验并启用后,再重新计算和发布数据。' : '导入只创建新草稿,先预览、再确认。'}</span><div><Button onClick={() => setOpen(false)}>{result ? '完成' : '取消'}</Button>{(!result || simplified && Boolean(error || workflowOperation.error)) && <Button type="primary" disabled={!canSubmit || workflowOperation.busy} loading={busy || workflowOperation.busy} onClick={() => void submit()}>{simplified && result ? '重试保存并更新报表' : simplified ? '导入并更新报表' : '确认导入为草稿'}</Button>}</div></div>}>
{error && <Alert type="error" showIcon message="表格导入未完成" description={error} />} {error && <Alert type="error" showIcon message="表格导入未完成" description={error} />}
{workflowOperation.error && <Alert type="error" showIcon message="导入或报表更新失败" description={workflowOperation.error} action={workflowOperation.operation?.operationId ? <Button size="small" onClick={workflowOperation.resume}>重试读取进度</Button> : undefined} />} {workflowOperation.error && <Alert type="error" showIcon message="导入或报表更新失败" description={workflowOperation.error} action={workflowOperation.operation?.operationId ? <Button size="small" onClick={workflowOperation.resume}>重试读取进度</Button> : undefined} />}
{workflowOperation.operation && <WorkflowOperationFeedback operation={workflowOperation.operation} error={workflowOperation.error} busy={workflowOperation.busy} onResume={workflowOperation.resume} />} {workflowOperation.operation && <WorkflowOperationFeedback operation={workflowOperation.operation} error={workflowOperation.error} busy={workflowOperation.busy} onResume={workflowOperation.resume} onDismiss={workflowOperation.clear} />}
{result ? <> {result ? <>
<Alert type={simplified ? workflowOperation.error ? 'error' : workflowOperation.busy ? 'info' : 'success' : 'success'} showIcon message={simplified ? workflowOperation.error ? '本次更新未完成' : workflowOperation.busy ? `正在更新:${txt(draft.name || name)}` : '基础数据和报表已更新' : `已生成草稿:${txt(draft.name || name)}`} description={simplified ? workflowOperation.error || (workflowOperation.busy ? '系统正在保存更新并重新计算报表。' : '配置已更新,报表已刷新。') : '当前数据未改变。可关闭此窗口,查看、校验并启用已保存的配置。'} /> <Alert type={simplified ? workflowOperation.error ? 'error' : workflowOperation.busy ? 'info' : 'success' : 'success'} showIcon message={simplified ? workflowOperation.error ? '本次更新未完成' : workflowOperation.busy ? `正在更新:${txt(draft.name || name)}` : '基础数据和报表已更新' : `已生成草稿:${txt(draft.name || name)}`} description={simplified ? workflowOperation.error || (workflowOperation.busy ? '系统正在保存更新并重新计算报表。' : '配置已更新,报表已刷新。') : '当前数据未改变。可关闭此窗口,查看、校验并启用已保存的配置。'} />
<div className="nc-review-facts"><div><small>新增</small><strong>{txt(summary.added)}</strong></div><div><small>更新</small><strong>{txt(summary.updated)}</strong></div><div><small>停用</small><strong>{txt(summary.disabled)}</strong></div><div><small>合计</small><strong>{txt(summary.total)}</strong></div></div> <div className="nc-review-facts"><div><small>新增</small><strong>{txt(summary.added)}</strong></div><div><small>更新</small><strong>{txt(summary.updated)}</strong></div><div><small>停用</small><strong>{txt(summary.disabled)}</strong></div><div><small>合计</small><strong>{txt(summary.total)}</strong></div></div>
+15
View File
@@ -2,6 +2,21 @@ import type { DataField, DataStage, WorkbookPreview } from './NoCodeDataTypes';
type Candidate = { workbook: WorkbookPreview; stage: DataStage; score: number; matched: number }; type Candidate = { workbook: WorkbookPreview; stage: DataStage; score: number; matched: number };
/** 兼容历史文件的“25.1”年份写法;不把“3.16~3.31”等日期范围当作年份。 */
export function sourceFilenamePeriod(name: string): { year?: number; month?: number } {
const month = Number(name.match(/(?:^|\D)(0?[1-9]|1[0-2])月/)?.[1]) || undefined;
const full = name.match(/(?:^|\D)(20\d{2})(?:年|[-_.])/);
if (full) return { year: Number(full[1]), month };
const short = name.match(/统计表[^\d]*([2-9]\d)[..](0?[1-9]|1[0-2])(?:\D|$)/);
return { year: short && month === Number(short[2]) ? 2000 + Number(short[1]) : undefined, month };
}
/** 同批文件只有一个明确年份时,将其用于没有年份的其余文件,仍可在列表逐项核对。 */
export function sourceBatchYear(names: string[], fallback: number): number {
const years = new Set(names.map(name => sourceFilenamePeriod(name).year).filter((year): year is number => year !== undefined));
return years.size === 1 ? [...years][0] : fallback;
}
function identify(workbook: WorkbookPreview, fields: Record<DataStage, DataField[]>): Candidate { function identify(workbook: WorkbookPreview, fields: Record<DataStage, DataField[]>): Candidate {
return (['black', 'bright'] as DataStage[]).map(stage => { return (['black', 'bright'] as DataStage[]).map(stage => {
const required = fields[stage].filter(field => field.required); const required = fields[stage].filter(field => field.required);
+20 -7
View File
@@ -25,19 +25,24 @@ export function useDataWorkflowOperation(slot: string, onComplete?: (value: Data
const terminalHandledRef = useRef(new Set<string>()); const terminalHandledRef = useRef(new Set<string>());
const generationRef = useRef(0); const generationRef = useRef(0);
const mountedRef = useRef(false); const mountedRef = useRef(false);
const restoredIdRef = useRef('');
useEffect(() => { callbackRef.current = onComplete; }, [onComplete]); useEffect(() => { callbackRef.current = onComplete; }, [onComplete]);
useEffect(() => { useEffect(() => {
mountedRef.current = true; mountedRef.current = true;
let pending: StoredOperation | null = null; let pending: StoredOperation | null = null;
try { pending = JSON.parse(localStorage.getItem(storageKey(slot)) || 'null') as StoredOperation | null; } catch { pending = null; } try { pending = JSON.parse(localStorage.getItem(storageKey(slot)) || 'null') as StoredOperation | null; } catch { pending = null; }
if (pending?.operationId) setOperationId(pending.operationId); if (pending?.operationId) { restoredIdRef.current = pending.operationId; setOperationId(pending.operationId); }
return () => { mountedRef.current = false; generationRef.current++; }; return () => { mountedRef.current = false; generationRef.current++; };
}, [slot]); }, [slot]);
const savePendingId = useCallback((value: StoredOperation | null) => { const savePendingId = useCallback((value: StoredOperation | null, expectedId?: string) => {
try { try {
if (value) localStorage.setItem(storageKey(slot), JSON.stringify(value)); if (value) localStorage.setItem(storageKey(slot), JSON.stringify(value));
else localStorage.removeItem(storageKey(slot)); else {
// 另一个标签页可能已经启动新任务,旧任务结束不能清掉它的恢复入口。
const stored = JSON.parse(localStorage.getItem(storageKey(slot)) || 'null') as StoredOperation | null;
if (!expectedId || stored?.operationId === expectedId) localStorage.removeItem(storageKey(slot));
}
} catch { /* storage may be unavailable in a restricted browser context */ } } catch { /* storage may be unavailable in a restricted browser context */ }
}, [slot]); }, [slot]);
@@ -48,15 +53,16 @@ export function useDataWorkflowOperation(slot: string, onComplete?: (value: Data
try { try {
const current = await api.dataWorkflowOperation(id); const current = await api.dataWorkflowOperation(id);
if (!mountedRef.current || generation !== generationRef.current) return; if (!mountedRef.current || generation !== generationRef.current) return;
setOperation(current); setOperation(restoredIdRef.current === id ? { ...current, restoredFromPreviousVisit: true } : current);
setError(''); setError('');
const status = String(current.status || '').toUpperCase(); const status = String(current.status || '').toUpperCase();
if (status === 'COMPLETED' || status === 'FAILED') { if (status === 'COMPLETED' || status === 'FAILED') {
terminalHandledRef.current.add(id); terminalHandledRef.current.add(id);
generationRef.current++; generationRef.current++;
setOperationId(''); setOperationId('');
// 只有未完成任务需要跨刷新恢复;失败详情仍留在本页和服务端历史记录。
savePendingId(null, id);
if (status === 'COMPLETED') { if (status === 'COMPLETED') {
savePendingId(null);
window.dispatchEvent(new CustomEvent(WORKSPACE_INVALIDATED, { detail: { resources: ['sources', 'workflow', 'tasks', 'releases', 'metrics', 'trend', 'records', 'options', 'catalog', 'configuration'] } })); window.dispatchEvent(new CustomEvent(WORKSPACE_INVALIDATED, { detail: { resources: ['sources', 'workflow', 'tasks', 'releases', 'metrics', 'trend', 'records', 'options', 'catalog', 'configuration'] } }));
callbackRef.current?.(current); callbackRef.current?.(current);
} else setError(operationError(current)); } else setError(operationError(current));
@@ -76,6 +82,12 @@ export function useDataWorkflowOperation(slot: string, onComplete?: (value: Data
if (startPromiseRef.current) return startPromiseRef.current; if (startPromiseRef.current) return startPromiseRef.current;
if (isPending(operation)) return operation; if (isPending(operation)) return operation;
const attempt = (async () => { const attempt = (async () => {
const previousId = operation?.operationId || restoredIdRef.current;
if (previousId) savePendingId(null, previousId);
generationRef.current++;
restoredIdRef.current = '';
setOperation(null);
setOperationId('');
setStarting(true); setStarting(true);
setError(''); setError('');
try { try {
@@ -109,7 +121,8 @@ export function useDataWorkflowOperation(slot: string, onComplete?: (value: Data
const clear = useCallback(() => { const clear = useCallback(() => {
generationRef.current++; generationRef.current++;
setOperation(null); setOperationId(''); setError(''); savePendingId(null); restoredIdRef.current = '';
}, [savePendingId]); setOperation(null); setOperationId(''); setError(''); savePendingId(null, operation?.operationId);
}, [savePendingId, operation?.operationId]);
return { operation, error, busy: starting || Boolean(isPending(operation)), start, resume, clear }; return { operation, error, busy: starting || Boolean(isPending(operation)), start, resume, clear };
} }
@@ -0,0 +1,20 @@
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/sourceWorkbookDetection.ts',import.meta.url),'utf8'),{compilerOptions:{target:ts.ScriptTarget.ES2022,module:ts.ModuleKind.ESNext}}).outputText.replace(/^import .*;\n/gm,'').replace(/export /g,'');
const {sourceFilenamePeriod:period,sourceBatchYear:year}=new Function(source+';return {sourceFilenamePeriod,sourceBatchYear};')();
test('actual historical quality workbook names identify 2025 without confusing split-date ranges',()=>{
assert.deepEqual(period('1月亮片质量数据统计表25.1.xlsx'),{year:2025,month:1});
assert.deepEqual(period('2月黑片质量数据统计表25.2上.xlsx'),{year:2025,month:2});
assert.deepEqual(period('7月亮片质量数据统计表25.7.29-7.31.xlsx'),{year:2025,month:7});
assert.deepEqual(period('3月黑片质量数据统计表3.16~3.31.xlsx'),{year:undefined,month:3});
assert.deepEqual(period('2025年12月黑片.xlsx'),{year:2025,month:12});
assert.deepEqual(period('6月质量数据统计表25.5.xlsx'),{year:undefined,month:6});
});
test('a consistent batch year also applies to same-batch files without a year; mixed explicit years keep individual identities',()=>{
assert.equal(year(['1月亮片质量数据统计表25.1.xlsx','12月黑片质量数据统计表12月1日-12月31日.xlsx'],2026),2025);
assert.equal(year(['2025年1月黑片.xlsx','2026年1月黑片.xlsx'],2026),2026);
assert.equal(year(['3月黑片质量数据统计表3.16~3.31.xlsx'],2026),2026);
assert.equal(period('2025年1月黑片.xlsx').year,2025);
});
@@ -7,15 +7,16 @@ const source = ts.transpileModule(readFileSync(new URL('../src/useDataWorkflowOp
const tick = () => new Promise(resolve => setImmediate(resolve)); const tick = () => new Promise(resolve => setImmediate(resolve));
const deferred = () => { let resolve; const promise = new Promise(done => { resolve = done; }); return { promise, resolve }; }; const deferred = () => { let resolve; const promise = new Promise(done => { resolve = done; }); return { promise, resolve }; };
function operationHook(api) { function operationHook(api, restoredOperationId = '') {
const events = [], callbacks = [], storage = new Map(); const events = [], callbacks = [], storage = new Map(), state = [];
if (restoredOperationId) storage.set('quality-data-workflow:project', JSON.stringify({ operationId: restoredOperationId, startedAt: '2026-11-04T00:00:00Z' }));
const window = { localStorage: storage, dispatchEvent: event => events.push(event) }; const window = { localStorage: storage, dispatchEvent: event => events.push(event) };
const localStorage = { getItem: key => storage.get(key) ?? null, setItem: (key, value) => storage.set(key, value), removeItem: key => storage.delete(key) }; const localStorage = { getItem: key => storage.get(key) ?? null, setItem: (key, value) => storage.set(key, value), removeItem: key => storage.delete(key) };
const hooks = { useState: value => [value, () => {}], useRef: current => ({ current }), useCallback: fn => fn, useEffect: fn => { fn(); } }; const hooks = { useState: value => { const index = state.length; state.push(value); return [value, next => { state[index] = next; }]; }, useRef: current => ({ current }), useCallback: fn => fn, useEffect: fn => { fn(); } };
const load = new Function('api', 'window', 'localStorage', 'WORKSPACE_INVALIDATED', 'usePageCache', 'useVisiblePolling', 'hooks', `const {useState,useRef,useCallback,useEffect}=hooks;${source};return useDataWorkflowOperation;`); const load = new Function('api', 'window', 'localStorage', 'WORKSPACE_INVALIDATED', 'usePageCache', 'useVisiblePolling', 'hooks', `const {useState,useRef,useCallback,useEffect}=hooks;${source};return useDataWorkflowOperation;`);
const useDataWorkflowOperation = load(api, window, localStorage, 'quality-workspace-invalidated', () => ({ active: true }), () => {}, hooks); const useDataWorkflowOperation = load(api, window, localStorage, 'quality-workspace-invalidated', () => ({ active: true }), () => {}, hooks);
const hook = useDataWorkflowOperation('project', value => callbacks.push(value)); const hook = useDataWorkflowOperation('project', value => callbacks.push(value));
return { hook, events, callbacks, storage }; return { hook, events, callbacks, storage, state };
} }
test('a completed workflow invalidates retained data exactly once after the server marks it complete', async () => { test('a completed workflow invalidates retained data exactly once after the server marks it complete', async () => {
@@ -39,14 +40,34 @@ test('a completed workflow invalidates retained data exactly once after the serv
assert.equal(events.length, 1, 'a terminal result cannot invalidate a second time'); assert.equal(events.length, 1, 'a terminal result cannot invalidate a second time');
}); });
test('failed workflows never invalidate published data and keep the operation id available for recovery', async () => { test('a cached failed operation is explicitly marked as historical and is not restored again on the next visit', async () => {
const { hook, storage, state } = operationHook({ dataWorkflowOperation: async () => ({ operationId: 'old-job', status: 'FAILED', errors: [{ message: 'old failure' }] }) }, 'old-job');
hook.resume(); await tick(); await tick();
assert.equal(state[0].status, 'FAILED');
assert.equal(state[0].restoredFromPreviousVisit, true);
assert.equal(state[2], 'old failure');
assert.equal(storage.size, 0);
});
test('an old terminal response cannot remove a newer task saved by another tab', async () => {
const final = deferred();
const { hook, storage } = operationHook({ dataWorkflowOperation: async () => final.promise });
await hook.start(async () => ({ operationId: 'old-job', status: 'QUEUED' }));
hook.resume(); await tick();
storage.set('quality-data-workflow:project', JSON.stringify({ operationId: 'new-job' }));
final.resolve({ operationId: 'old-job', status: 'FAILED', errors: [{ message: 'old failure' }] });
await tick(); await tick();
assert.equal(JSON.parse(storage.get('quality-data-workflow:project')).operationId, 'new-job');
});
test('failed workflows keep their visible error but remove the pending pointer so another visit does not revive an old failure', async () => {
let calls = 0; let calls = 0;
const { hook, events, callbacks, storage } = operationHook({ dataWorkflowOperation: async () => { calls++; return { operationId: 'job', status: 'FAILED', errors: [{ message: 'rejected' }] }; } }); const { hook, events, callbacks, storage } = operationHook({ dataWorkflowOperation: async () => { calls++; return { operationId: 'job', status: 'FAILED', errors: [{ message: 'rejected' }] }; } });
await hook.start(async () => ({ operationId: 'job', status: 'QUEUED' })); await hook.start(async () => ({ operationId: 'job', status: 'QUEUED' }));
hook.resume(); await tick(); await tick(); hook.resume(); await tick(); await tick();
assert.deepEqual(events, []); assert.deepEqual(events, []);
assert.deepEqual(callbacks, []); assert.deepEqual(callbacks, []);
assert.equal(storage.size, 1); assert.equal(storage.size, 0, 'only unfinished operations belong in reload recovery storage');
hook.resume(); await tick(); hook.resume(); await tick();
assert.equal(calls, 1, 'a terminal failure is not polled repeatedly'); assert.equal(calls, 1, 'a terminal failure is not polled repeatedly');
assert.deepEqual(events, []); assert.deepEqual(events, []);
@@ -0,0 +1,15 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {readFileSync} from 'node:fs';
import ts from 'typescript';
import React from 'react';
const source=readFileSync(new URL('../src/NoCodeDataWorkflow.tsx',import.meta.url),'utf8');
const body=source.slice(source.indexOf('function WorkflowOperationFeedback('),source.indexOf('export type PendingSourceDeletion'));
const code=ts.transpileModule(body+'\nreturn WorkflowOperationFeedback;', {compilerOptions:{target:ts.ScriptTarget.ES2022,jsx:ts.JsxEmit.React}}).outputText;
const Feedback=new Function('React','Alert','Button','Progress','workflowStageLabel',code)(React,'Alert','Button','Progress',{FAILED:'处理失败'});
function nodes(element){if(!React.isValidElement(element))return [];return [element,...React.Children.toArray(element.props.children).flatMap(nodes)];}
for(const restored of [false,true])test(restored?'historical failure is labelled and dismissible without a misleading processing progress bar':'new failure retains its concrete reason and can be dismissed',()=>{
let dismissed=false;
const tree=Feedback({operation:{operationId:'job',status:'FAILED',stage:'FAILED',restoredFromPreviousVisit:restored,errors:[{message:'具体校验原因'}]},error:'具体校验原因',busy:false,onResume(){throw Error('terminal failure must not offer progress retry');},onDismiss(){dismissed=true;}});
const all=nodes(tree),alerts=all.filter(n=>n.type==='Alert');assert.equal(alerts.length,1);assert.equal(alerts[0].props.message,restored?'上次操作未完成':'本次操作未完成');assert.ok(JSON.stringify(alerts[0].props.description).includes('具体校验原因'));assert.equal(all.filter(n=>n.type==='Progress').length,0);alerts[0].props.onClose();assert.equal(dismissed,true);
});