完善:质量分析平台查询与分析功能
This commit is contained in:
+106
-73
@@ -1,5 +1,6 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { Alert, App, Button, Checkbox, Empty, Form, Input, InputNumber, Modal, Progress, Select, Spin, Steps, Table, Tag } from 'antd';
|
||||
import { Alert, App, Button, Checkbox, Empty, Form, Input, InputNumber, Modal, Progress, Select, Spin, Steps, Tag } from 'antd';
|
||||
import { QualityTable as Table } from './QualityTable';
|
||||
import { ArrowRightOutlined, DeleteOutlined, FileExcelOutlined, ReloadOutlined, SwapOutlined, UndoOutlined, UploadOutlined } from '@ant-design/icons';
|
||||
import { api, collectionItems } from './api';
|
||||
import type { AuthUser, SourceItem } from './types';
|
||||
@@ -41,100 +42,131 @@ function WorkflowOperationFeedback({ operation, error, busy, onResume }: { opera
|
||||
</section>;
|
||||
}
|
||||
|
||||
function SimplifiedDataWorkflow({ options, workflowStatus, onUnauthorized, onRefresh }: { options: SourceUploadOptions; workflowStatus: DataWorkflowStatus; onUnauthorized: (error: unknown) => boolean; onRefresh: () => void }) {
|
||||
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 };
|
||||
|
||||
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 }) {
|
||||
const { message } = App.useApp();
|
||||
const input = useRef<HTMLInputElement>(null);
|
||||
const configuredUploadId = useRef<string | null>(null);
|
||||
const [workbook, setWorkbook] = useState<WorkbookPreview | null>(null);
|
||||
const [stage, setStage] = useState<DataStage>('black');
|
||||
const [year, setYear] = useState(new Date().getFullYear()); const [month, setMonth] = useState(new Date().getMonth() + 1);
|
||||
const [sheetName, setSheetName] = useState(''); const [headerRow, setHeaderRow] = useState(1); const [fieldMap, setFieldMap] = useState<Record<string, string>>({});
|
||||
const [mode, setMode] = useState<'ADD' | 'REPLACE'>('ADD'); const [targetId, setTargetId] = useState(''); const [scopeCode, setScopeCode] = useState(options.scopes[0] || 'ALL');
|
||||
const [configuredSourceId, setConfiguredSourceId] = useState(''); const [busy, setBusy] = useState(false); const [error, setError] = useState('');
|
||||
const uploadOperation = useDataWorkflowOperation('source-import', () => { onRefresh(); message.success('来源已导入,报表已更新'); });
|
||||
const recalcOperation = useDataWorkflowOperation('recalculate', () => { onRefresh(); message.success('已按当前来源重新计算并更新报表'); });
|
||||
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 uploadOperation = useDataWorkflowOperation('source-import', () => { setDrafts([]); setActiveId(''); configured.current.clear(); consumed.current.clear(); onRefresh(); message.success('所选来源已统一导入,报表已更新'); });
|
||||
const recalcOperation = useDataWorkflowOperation('recalculate', value => { if (Array.isArray(value.sourceIds)) onDeleted(value.sourceIds.map(String)); onRefresh(); message.success('报表已更新'); });
|
||||
const active = drafts.find(item => item.id === activeId) || drafts[0];
|
||||
const workbook = active?.workbook || null;
|
||||
const stage = active?.stage || 'black'; const year = active?.year || new Date().getFullYear(); const month = active?.month || 1;
|
||||
const sheetName = active?.sheetName || ''; const headerRow = active?.headerRow || 1; const fieldMap = active?.fieldMap || {};
|
||||
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 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 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 target = options.targets.find(item => item.documentId === targetId);
|
||||
const importBusy = busy || uploadOperation.busy;
|
||||
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 needsNewFile = Boolean(workbook && configuredUploadId.current === workbook.uploadId && !configuredSourceId);
|
||||
const canImport = Boolean(hasImportCapability && !needsNewFile && workbook && !missing.length && !duplicate && (mode !== 'REPLACE' || target));
|
||||
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 reportError = (value: unknown) => { if (!onUnauthorized(value)) setError(failure(value)); };
|
||||
const invalidateConfiguredSource = () => {
|
||||
setConfiguredSourceId('');
|
||||
};
|
||||
const readFile = async (file?: File) => {
|
||||
if (!file) return; setBusy(true); setError(''); setConfiguredSourceId('');
|
||||
try {
|
||||
const result = await api.previewSourceWorkbook(file);
|
||||
setWorkbook(result); configuredUploadId.current = null; setSheetName(result.preview.sheetName); setHeaderRow(result.preview.headerRow);
|
||||
const scores = (['black', 'bright'] as DataStage[]).map(value => {
|
||||
const required = (options.fields[value] || []).filter(field => field.required);
|
||||
const matched = matchFields(options.fields[value] || [], result.preview.headers);
|
||||
return { stage: value, score: required.length ? required.filter(field => matched[field.name]).length / required.length : 0 };
|
||||
});
|
||||
const detected = scores.sort((a, b) => b.score - a.score)[0];
|
||||
const nextStage = detected.score > 0 ? detected.stage : stage;
|
||||
setStage(nextStage); setFieldMap(matchFields(options.fields[nextStage] || [], result.preview.headers));
|
||||
if (mode === 'ADD') {
|
||||
const monthMatch = file.name.match(/(?:^|\D)(0?[1-9]|1[0-2])月/);
|
||||
if (monthMatch) setMonth(Number(monthMatch[1]));
|
||||
}
|
||||
} catch (value) { reportError(value); }
|
||||
finally { setBusy(false); if (input.current) input.current.value = ''; }
|
||||
const removeDraft = (id: string) => { setDrafts(previous => previous.filter(item => item.id !== id)); configured.current.delete(id); };
|
||||
const readFiles = async (files: File[]) => {
|
||||
if (!files.length || importBusy) return;
|
||||
if (files.length + drafts.length > 50) { setError('一次最多导入50个文件'); if (input.current) input.current.value = ''; return; }
|
||||
setBusy(true); setError(''); const failures: string[] = [];
|
||||
const known = new Set(drafts.map(item => `${item.file.name}:${item.file.size}:${item.file.lastModified}`));
|
||||
const selected = files.filter(file => { const key = `${file.name}:${file.size}:${file.lastModified}`; if (known.has(key)) return false; known.add(key); return true; });
|
||||
setReading({ done: 0, total: selected.length });
|
||||
for (let index = 0; index < selected.length; index += 2) {
|
||||
const results = await Promise.all(selected.slice(index, index + 2).map(async file => {
|
||||
try {
|
||||
const result = await api.previewSourceWorkbook(file);
|
||||
const scores = (['black', 'bright'] as DataStage[]).map(value => { const required = (options.fields[value] || []).filter(field => field.required); const matched = matchFields(options.fields[value] || [], result.preview.headers); return { stage: value, score: required.length ? required.filter(field => matched[field.name]).length / required.length : 0 }; });
|
||||
const detected = scores.sort((a, b) => b.score - a.score)[0].stage;
|
||||
const 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' };
|
||||
} catch (value) { if (!onUnauthorized(value)) failures.push(`${file.name}:${failure(value)}`); return null; }
|
||||
}));
|
||||
const ready = results.filter(item => item !== null);
|
||||
setDrafts(previous => [...previous, ...ready]);
|
||||
setReading({ done: Math.min(index + 2, selected.length), total: selected.length });
|
||||
}
|
||||
if (failures.length) setError(`以下文件未加入导入列表,可重新选择:${failures.join(';')}`);
|
||||
setReading(null); setBusy(false); if (input.current) input.current.value = '';
|
||||
};
|
||||
const changePreview = async (nextSheet: string, nextHeader = headerRow, nextStage = stage, preferredMap?: Record<string, string>) => {
|
||||
if (!workbook) return; setBusy(true); setError(''); invalidateConfiguredSource();
|
||||
if (!workbook) return; setBusy(true); setError('');
|
||||
try {
|
||||
const result = await api.sourceWorkbookPreview(workbook.uploadId, { sheetName: nextSheet, headerRow: nextHeader, stage: nextStage });
|
||||
setWorkbook(result); setSheetName(result.preview.sheetName); setHeaderRow(result.preview.headerRow);
|
||||
const previous = preferredMap || fieldMap;
|
||||
setFieldMap({ ...matchFields(options.fields[nextStage] || [], result.preview.headers), ...Object.fromEntries(Object.entries(previous).filter(([, header]) => result.preview.headers.includes(header))) });
|
||||
} catch (value) { reportError(value); }
|
||||
finally { setBusy(false); }
|
||||
} catch (value) { reportError(value); } finally { setBusy(false); }
|
||||
};
|
||||
const importAndUpdate = async () => {
|
||||
if (!workbook || !canImport) return; setBusy(true); setError('');
|
||||
if (!canImport || importBusy) return; setBusy(true); setError('');
|
||||
try {
|
||||
let sourceId = configuredSourceId;
|
||||
if (!sourceId) {
|
||||
const configured = await api.configureSourceWorkbook({ uploadId: workbook.uploadId, stage, year, month, sheetName, headerRow, fieldMap, mode, expectedCurrentReleaseId: workflowStatus.currentReleaseId ?? options.currentReleaseId, ...(target ? { targetDocumentId: target.documentId, targetRevisionId: target.revisionId } : {}), reason: mode === 'REPLACE' ? '测试阶段更新来源数据' : '测试阶段导入来源数据', scopeCode });
|
||||
sourceId = configured.source.id; configuredUploadId.current = workbook.uploadId; setConfiguredSourceId(sourceId);
|
||||
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);
|
||||
}
|
||||
await uploadOperation.start(() => api.importDataWorkflow({ sourceIds: [sourceId] }));
|
||||
} catch (value) { reportError(value); }
|
||||
finally { setBusy(false); }
|
||||
await uploadOperation.start(() => api.importDataWorkflow({ sourceIds }));
|
||||
} catch (value) { reportError(value); } finally { setBusy(false); }
|
||||
};
|
||||
const recalculate = async () => {
|
||||
setError('');
|
||||
try { await recalcOperation.start(() => api.recalculateDataWorkflow()); }
|
||||
try { await recalcOperation.start(() => pendingDeletion.ids.length ? api.deleteDataWorkflowSources({ sourceIds: pendingDeletion.ids, expectedCurrentReleaseId: pendingDeletion.releaseId }) : api.recalculateDataWorkflow()); }
|
||||
catch (value) { reportError(value); }
|
||||
};
|
||||
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()}>按当前来源重新计算</Button>}</div></div>
|
||||
<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>
|
||||
{!hasImportCapability && <Alert showIcon type="info" message="当前账号没有导入权限" description="可查看来源;导入和更新报表需要发布权限。" />}
|
||||
{error && <Alert showIcon type="error" message="操作未完成,输入内容已保留" description={error} />}
|
||||
{needsNewFile && <Alert showIcon type="info" message="导入设置已修改" description="这份文件已提交过导入,请点击“更换文件”重新选择文件后再导入。" />}
|
||||
{!workbook ? <div className="nc-file-drop nc-simple-file-drop"><FileExcelOutlined /><h3>选择 Excel 来源文件</h3><p>系统自动识别标准表头,文件年月可在下方设置。</p><input className="visually-hidden-file" ref={input} type="file" accept=".xlsx" onChange={event => void readFile(event.target.files?.[0])} aria-label="选择质量数据Excel文件" />{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={() => { setWorkbook(null); setConfiguredSourceId(''); }}>更换文件</Button>}</div>
|
||||
<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="可继续标记或撤销删除,完成后点击“更新报表”。请先处理待删除文件,再导入新文件。" />}
|
||||
{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: '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> },
|
||||
]} /></>}
|
||||
{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); invalidateConfiguredSource(); }} /></label>
|
||||
<label>数据阶段<Select disabled={importBusy} value={stage} options={[{ value: 'black', label: '黑片' }, { value: 'bright', label: '亮片' }]} onChange={value => { setStage(value); invalidateConfiguredSource(); setFieldMap(matchFields(options.fields[value] || [], headers)); }} /></label>
|
||||
<label>统计年份<InputNumber disabled={importBusy} min={2000} max={2100} value={year} onChange={value => { if (value) setYear(value); invalidateConfiguredSource(); }} /></label>
|
||||
<label>统计月份<Select disabled={importBusy} value={month} options={Array.from({ length: 12 }, (_, index) => ({ value: index + 1, label: `${index + 1}月` }))} onChange={value => { setMonth(value); invalidateConfiguredSource(); }} /></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); invalidateConfiguredSource(); }} /></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); invalidateConfiguredSource(); }} /></label>}
|
||||
<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>}
|
||||
</div>
|
||||
<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); invalidateConfiguredSource(); }} 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); invalidateConfiguredSource(); }} />
|
||||
<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); }} />
|
||||
<h3>原表预览</h3><SampleTable headers={headers} rows={workbook.preview.sampleRows.map(row => row.values)} />
|
||||
</details>
|
||||
{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()}>导入并更新报表</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={recalcOperation.operation} error={recalcOperation.error} busy={recalcOperation.busy} onResume={recalcOperation.resume} />
|
||||
@@ -148,7 +180,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, onUnauthorized, onRefresh }: { user: AuthUser; sources: SourceItem[]; currentReleaseId: string | null; onUnauthorized: (error: unknown) => boolean; onRefresh: () => void }) {
|
||||
export function DataWorkflowHub({ user, sources, currentReleaseId, pendingDeletion, onDeleted, onBusyChange, onUnauthorized, onRefresh }: { user: AuthUser; sources: SourceItem[]; currentReleaseId: string | null; pendingDeletion: PendingSourceDeletion; onDeleted: (ids: string[]) => void; onBusyChange: (busy: boolean) => void; onUnauthorized: (error: unknown) => boolean; onRefresh: () => void }) {
|
||||
const { message } = App.useApp();
|
||||
const [mode, setMode] = useState<'ADD' | 'REPLACE' | 'REBUILD' | null>(null);
|
||||
const [options, setOptions] = useState<SourceUploadOptions | null>(null);
|
||||
@@ -177,7 +209,7 @@ export function DataWorkflowHub({ user, sources, currentReleaseId, onUnauthorize
|
||||
const opened = mode !== null || Boolean(resumeId);
|
||||
const open = (next: 'ADD' | 'REPLACE' | 'REBUILD') => { setMode(next); setResumeId(''); void loadOptions(); };
|
||||
if (!workflowStatusLoaded) return <section className="panel nc-operation-status"><div><strong>读取当前维护模式</strong><span>正在加载可执行操作</span></div><Spin /></section>;
|
||||
if (workflowStatus?.simplified === true && workflowStatus.mode === 'TEST' && options) return <SimplifiedDataWorkflow options={options} workflowStatus={workflowStatus} onUnauthorized={onUnauthorized} onRefresh={onRefresh} />;
|
||||
if (workflowStatus?.simplified === true && workflowStatus.mode === 'TEST' && options) return <SimplifiedDataWorkflow options={options} workflowStatus={workflowStatus} pendingDeletion={pendingDeletion} onDeleted={onDeleted} onBusyChange={onBusyChange} onUnauthorized={onUnauthorized} onRefresh={onRefresh} />;
|
||||
return <>
|
||||
<section className="nc-intake-start panel">
|
||||
<div className="nc-intake-intro"><span className="nc-eyebrow">日常数据维护</span><h2>选择文件,核对后发布</h2><p>文件名可以保持原样。黑片或亮片、统计年月和表头均在下一步选择。</p></div>
|
||||
@@ -191,7 +223,7 @@ export function DataWorkflowHub({ user, sources, currentReleaseId, onUnauthorize
|
||||
</>;
|
||||
}
|
||||
|
||||
export function SourceFilesPanel({ user, sources, loading, onUnauthorized, onRefresh }: { user: AuthUser; sources: SourceItem[]; loading: boolean; onUnauthorized: (error: unknown) => boolean; onRefresh: () => void }) {
|
||||
export function SourceFilesPanel({ user, sources, loading, pendingIds, maintenanceBusy, onToggleDelete, onClearDeletes, onUnauthorized, onRefresh }: { user: AuthUser; sources: SourceItem[]; loading: boolean; pendingIds: string[]; maintenanceBusy: boolean; onToggleDelete: (id: string) => void; onClearDeletes: () => void; onUnauthorized: (error: unknown) => boolean; onRefresh: () => void }) {
|
||||
const { message } = App.useApp();
|
||||
const [showDeleted, setShowDeleted] = useState(false);
|
||||
const [deleted, setDeleted] = useState<SourceDeletionPreview[]>([]);
|
||||
@@ -226,21 +258,22 @@ export function SourceFilesPanel({ user, sources, loading, onUnauthorized, onRef
|
||||
};
|
||||
return <>
|
||||
<section className="panel section-panel nc-source-files">
|
||||
<div className="resource-toolbar"><strong>{showDeleted ? '已删除的来源文件' : '已接收的来源文件'}</strong><span>{showDeleted ? `${deleted.length} 个文件 · 原件和处理记录保留` : simplified ? `${sources.length} 个文件 · 来源变化会自动重算并更新报表` : `${sources.length} 个文件 · 上传或接收不等于已经发布`}</span>{canOperate && <Checkbox checked={showDeleted} onChange={event => setShowDeleted(event.target.checked)}>查看已删除来源</Checkbox>}</div>
|
||||
{simplified && <p className="nc-source-maintenance-note">删除会从当前数据中移除来源并更新报表;恢复会自动重新计算。原文件和处理记录保留。</p>}
|
||||
{deletedError && showDeleted && <Alert showIcon type="error" message="已删除来源读取失败" description={deletedError} action={<Button size="small" onClick={() => void loadDeleted()}>重试</Button>} />}
|
||||
<div className="resource-toolbar"><strong>{showDeleted ? '已删除的来源文件' : '已接收的来源文件'}</strong><span>{showDeleted ? `${deleted.length} 个文件 · 原件和处理记录保留` : simplified ? `${sources.length} 个文件${pendingIds.length ? ` · ${pendingIds.length} 个待删除` : ''}` : `${sources.length} 个文件 · 上传或接收不等于已经发布`}</span>{canOperate && <Checkbox checked={showDeleted} onChange={event => setShowDeleted(event.target.checked)}>查看已删除来源</Checkbox>}</div>
|
||||
{simplified && <p className="nc-source-maintenance-note">删除先标记为待删除,可连续操作和撤销,点击上方“更新报表”后统一生效。原文件和处理记录保留。</p>}
|
||||
{simplified && pendingIds.length > 0 && <div className="nc-source-maintenance-note"><Button disabled={maintenanceBusy} onClick={onClearDeletes}>撤销全部待删除({pendingIds.length})</Button></div>}
|
||||
{deletedError && <Alert showIcon type="error" message="已删除来源读取失败" description={deletedError} action={<Button size="small" onClick={() => void loadDeleted()}>重试</Button>} />}
|
||||
{sourceOperation.operation && <WorkflowOperationFeedback operation={sourceOperation.operation} error={sourceOperation.error} busy={sourceOperation.busy} onResume={sourceOperation.resume} />}
|
||||
<Table<DeletionSource> size="small" bordered loading={showDeleted ? deletedLoading : loading} dataSource={showDeleted ? deleted.map(item => item.source) : sources} rowKey="id" pagination={{ pageSize: 12, showSizeChanger: false }} scroll={{ x: 980 }} columns={[
|
||||
{ title: '来源文件', dataIndex: 'sourceFile', key: 'sourceFile', width: 340, ellipsis: true },
|
||||
{ title: '阶段', dataIndex: 'stage', key: 'stage', align: 'center', width: 90, render: value => <Tag>{stageName(value)}</Tag> },
|
||||
{ title: '统计期间', key: 'period', align: 'center', width: 140, render: (_, row) => period(row) },
|
||||
{ title: showDeleted ? '删除理由' : '文件大小', dataIndex: showDeleted ? 'deletionReason' : 'sizeBytes', key: 'sizeBytes', align: showDeleted ? 'left' : 'right', width: showDeleted ? 220 : 120, ellipsis: true, render: value => showDeleted ? txt(value) : typeof value === 'number' ? `${(value / 1024).toFixed(1)} KB` : '—' },
|
||||
{ title: '接入状态', dataIndex: 'status', key: 'status', align: 'center', width: 130, render: value => showDeleted ? <Tag>已删除</Tag> : ({ DISCOVERED: '已接收', QUEUED: '等待校验', RUNNING: '正在校验', IMPORTED: '已校验', UNIDENTIFIED: '待确认', RETURNED: '已退回', COVERAGE_CONFLICT: '范围待确认', WRITING: '文件写入中' } as Record<string, string>)[String(value)] || value },
|
||||
{ title: '接入状态', dataIndex: 'status', key: 'status', align: 'center', width: 130, render: (value, row) => simplified && pendingIds.includes(row.id) ? <Tag color="orange">待删除</Tag> : showDeleted ? <Tag>已删除</Tag> : ({ DISCOVERED: '已接收', QUEUED: '等待校验', RUNNING: '正在校验', IMPORTED: '已校验', UNIDENTIFIED: '待确认', RETURNED: '已退回', COVERAGE_CONFLICT: '范围待确认', WRITING: '文件写入中' } as Record<string, string>)[String(value)] || value },
|
||||
{ title: '操作', key: 'actions', align: 'center', fixed: 'right', width: 170, render: (_, row) => {
|
||||
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} onClick={() => simplified ? void runSourceOperation(row.id, showDeleted) : setSelected({ id: row.id, restore: showDeleted })}>{simplified ? showDeleted ? '恢复并更新报表' : '删除并更新报表' : showDeleted ? '恢复' : '删除'}</Button>;
|
||||
return <Button type="link" danger={!showDeleted} icon={showDeleted ? <UndoOutlined /> : <DeleteOutlined />} disabled={sourceOperation.busy || maintenanceBusy || loading} onClick={() => simplified ? showDeleted ? void runSourceOperation(row.id, true) : onToggleDelete(row.id) : setSelected({ id: row.id, restore: showDeleted })}>{simplified ? showDeleted ? '恢复并更新报表' : pendingIds.includes(row.id) ? '撤销删除' : '删除' : showDeleted ? '恢复' : '删除'}</Button>;
|
||||
} },
|
||||
]} locale={{ emptyText: showDeleted ? '没有已删除的来源。' : '尚无来源文件,点击“上传新数据”开始。' }} />
|
||||
</section>
|
||||
@@ -420,7 +453,7 @@ 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 && !configuredSourceId && !busy && <Button onClick={() => { setStep(step - 1); setError(''); }}>上一步</Button>}<Button onClick={close}>{published ? '完成' : busy ? '关闭并稍后查看' : '关闭'}</Button>{!published && step === 1 && <Button type="primary" disabled={mode === 'REPLACE' && !target} loading={busy} onClick={() => { setStep(2); void changePreview(sheetName, headerRow); }}>下一步:匹配表头</Button>}{!published && step === 2 && <Button type="primary" loading={busy} disabled={Boolean(missingFields.length) || duplicateColumns || !sheetName} onClick={() => { if (workbook && (workbook.preview.headerRow !== headerRow || workbook.preview.sheetName !== sheetName)) { void changePreview(sheetName, headerRow); return; } setStep(3); }}>下一步:预览验证</Button>}{!published && step === 3 && !runId && mode !== 'REBUILD' && <Button type="primary" loading={busy} disabled={mode === 'REPLACE' && !reason.trim()} onClick={() => void beginImport()}>确认导入并校验</Button>}</div></div>}>
|
||||
<Steps className="nc-steps" current={published ? 5 : step} size="small" items={steps.map(title => ({ title }))} />
|
||||
{error && <Alert showIcon type="error" message="本次操作未完成" description={error} />}
|
||||
{published ? <div className="nc-success"><FileExcelOutlined /><h2>{purpose === 'WITHDRAW' ? '该来源已从当前查询结果移除' : '当前查询数据已更新'}</h2><p>来源原件和本次对账记录均已保留。</p></div> : <>
|
||||
|
||||
Reference in New Issue
Block a user