755 lines
112 KiB
TypeScript
755 lines
112 KiB
TypeScript
import { useDeleteConfirmation } from './useDeleteConfirmation';
|
||
import { configurationDateTime } from './configurationName';
|
||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||
import { Alert, App, Button, Checkbox, Empty, Form, Input, InputNumber, Modal, Progress, Select, Spin, Steps, Tag } from 'antd';
|
||
import { QualityTable as Table } from './QualityTable';
|
||
import { ArrowRightOutlined, DeleteOutlined, FileExcelOutlined, ReloadOutlined, SwapOutlined, UndoOutlined, UploadOutlined } from '@ant-design/icons';
|
||
import { api, collectionItems } from './api';
|
||
import type { AuthUser, SourceItem } from './types';
|
||
import type { DataField, DataStage, DataWorkflowOperation, DataWorkflowStatus, DeletionSource, MasterWorkbookKeyFormat, MasterWorkbookKind, MasterWorkbookPreview, SourceDeletionPreview, SourceUploadOptions, WorkbookPreview } from './NoCodeDataTypes';
|
||
import { useDataWorkflowOperation } from './useDataWorkflowOperation';
|
||
import { detectSourceWorkbook } from './sourceWorkbookDetection';
|
||
import { readableSelectPopup } from './readableSelectPopup';
|
||
import { usePageCache } from './pageCache';
|
||
import { useDelayedBusy, useDelayedIndicator } from './useDelayedBusy';
|
||
import { useVisiblePolling } from './useVisiblePolling';
|
||
import { runImportPollFollowup } from './importLifecycleGuards';
|
||
import { configureSourceBatch } from './sourceBatchConfigure';
|
||
import './no-code-data-workflow.css';
|
||
|
||
type Row = Record<string, unknown>;
|
||
const asRow = (value: unknown): Row => value && typeof value === 'object' && !Array.isArray(value) ? value as Row : {};
|
||
const asRows = (value: unknown): Row[] => Array.isArray(value) ? value.filter(item => item && typeof item === 'object') as Row[] : [];
|
||
const txt = (value: unknown): string => value === null || value === undefined || value === '' ? '—' : typeof value === 'object' ? Object.values(asRow(value)).map(txt).join(';') : String(value);
|
||
const failure = (value: unknown) => value instanceof Error ? value.message : '操作未完成,请重试';
|
||
const stageName = (stage: unknown) => stage === 'black' ? '黑片' : stage === 'bright' ? '亮片' : txt(stage);
|
||
const metricLabel = (value: unknown) => String(value || '').split('.').map(part => ({ black: '黑片', bright: '亮片', totalWeight: '总重量', qualifiedWeight: '合格重量', scrapWeight: '报废重量', compositeRate: '综合合格率', rate: '合格率', rateWithoutHeadquartersScrap: '剔除本部报废后合格率', headquartersScrapWeight: '本部报废重量', objectPresence: '对象是否存在', applicability: '适用状态' } as Record<string, string>)[part] || part).join(' / ');
|
||
const ratio = (value: unknown) => typeof value === 'number' ? `${(value * 100).toFixed(2)}%` : '—';
|
||
const rolesAllow = (user: AuthUser, roles: string[]) => user.roles.some(role => roles.includes(role));
|
||
const matchFields = (fields: DataField[], headers: string[]) => Object.fromEntries(fields.filter(field => headers.includes(field.name)).map(field => [field.name, field.name]));
|
||
const statusLabel: Record<string, string> = { QUEUED: '等待处理', RUNNING: '正在处理', COMPLETED: '校验完成', FAILED: '处理失败', CANCELLED: '已取消', CANDIDATE_READY: '候选已生成', AUTO_PASSED: '对账通过', CONFIRMED: '差异已确认', REVIEW_REQUIRED: '差异待确认', BLOCKED: '存在阻断问题' };
|
||
|
||
function SampleTable({ headers, rows }: { headers: string[]; rows: Row[] }) {
|
||
return <Table size="small" bordered dataSource={rows.map((row, index) => ({ ...row, __previewKey: index }))} rowKey="__previewKey" pagination={{ pageSize: 15, showSizeChanger: false }} scroll={{ x: 'max-content' }} columns={headers.map(header => ({ title: header, dataIndex: header, key: header, width: 150, render: txt }))} locale={{ emptyText: '当前工作表没有可预览数据' }} />;
|
||
}
|
||
|
||
function ColumnMatching({ fields, headers, value, onChange, disabled = false }: { fields: DataField[]; headers: string[]; value: Record<string, string>; onChange: (value: Record<string, string>) => void; disabled?: boolean }) {
|
||
return <div className="nc-column-matching">{fields.map(field => <label key={field.name} className="nc-field-match"><span>{field.name}{field.required ? <b>必填</b> : <small>选填</small>}</span><Select {...readableSelectPopup} disabled={disabled} aria-label={`${field.name}对应的Excel列`} allowClear showSearch optionFilterProp="label" placeholder="选择 Excel 中的列" value={value[field.name] || undefined} options={headers.map(header => ({ value: header, label: header }))} onChange={selected => { const next = { ...value }; if (selected) next[field.name] = selected; else delete next[field.name]; onChange(next); }} /></label>)}</div>;
|
||
}
|
||
|
||
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 }) {
|
||
if (!operation && !error) return null;
|
||
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' || !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: '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, 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 [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(); 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;
|
||
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, 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: '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 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[]) => {
|
||
if (!files.length || importBusy || actionLock.current) return;
|
||
actionLock.current = true;
|
||
if (files.length + drafts.length > 50) { setError('一次最多导入50个文件'); actionLock.current = false; if (input.current) input.current.value = ''; return; }
|
||
setBusy(true); setError(''); const failures: string[] = [];
|
||
const known = new Set(drafts.map(item => `${item.file.name}:${item.file.size}:${item.file.lastModified}`));
|
||
const selected = files.filter(file => { const key = `${file.name}:${file.size}:${file.lastModified}`; if (known.has(key)) return false; known.add(key); return true; });
|
||
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 uploaded = await api.previewSourceWorkbook(file);
|
||
const { workbook: result, stage: detected } = await detectSourceWorkbook(uploaded, options.fields, api.sourceWorkbookPreview);
|
||
const nextMonth = Number(file.name.match(/(?:^|\D)(0?[1-9]|1[0-2])月/)?.[1] || new Date().getMonth() + 1);
|
||
const nextYear = Number(file.name.match(/(20\d{2})年/)?.[1] || new Date().getFullYear());
|
||
return { id: crypto.randomUUID(), file, workbook: result, stage: detected, year: nextYear, month: nextMonth, sheetName: result.preview.sheetName, headerRow: result.preview.headerRow, fieldMap: matchFields(options.fields[detected] || [], result.preview.headers), mode: '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);
|
||
setDrafts(previous => [...previous, ...ready]);
|
||
setReading({ done: Math.min(index + 2, selected.length), total: selected.length });
|
||
}
|
||
if (failures.length) setError(`以下文件未加入导入列表,可重新选择:${failures.join(';')}`);
|
||
setReading(null); actionLock.current = false; setBusy(false); if (input.current) input.current.value = '';
|
||
};
|
||
const changePreview = async (nextSheet: string, nextHeader = headerRow, nextStage = stage, preferredMap?: Record<string, string>) => {
|
||
if (!workbook || actionLock.current) return; actionLock.current = true; setBusy(true); setError('');
|
||
try {
|
||
const result = await api.sourceWorkbookPreview(workbook.uploadId, { sheetName: nextSheet, headerRow: nextHeader, stage: nextStage });
|
||
setWorkbook(result); setSheetName(result.preview.sheetName); setHeaderRow(result.preview.headerRow);
|
||
const previous = preferredMap || fieldMap;
|
||
setFieldMap({ ...matchFields(options.fields[nextStage] || [], result.preview.headers), ...Object.fromEntries(Object.entries(previous).filter(([, header]) => result.preview.headers.includes(header))) });
|
||
} catch (value) { reportError(value); } finally { actionLock.current = false; setBusy(false); }
|
||
};
|
||
const importAndUpdate = async () => {
|
||
if (!canImport || importBusy || actionLock.current) return; actionLock.current = true; setBusy(true); setError('');
|
||
try {
|
||
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 || pendingDeletion.ids.length) return; actionLock.current = true;
|
||
setError('');
|
||
try { await recalcOperation.start(() => api.recalculateDataWorkflow()); }
|
||
catch (value) { reportError(value); }
|
||
finally { actionLock.current = false; }
|
||
};
|
||
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>同一月份可分批添加多个文件;相同文件内容不会重复计入。</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="请到“来源文件”页确认或撤销删除,再导入新文件。" />}
|
||
{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} · {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) => configured.current.has(item.id) ? <Tag color="blue">已接收待导入</Tag> : <Button type="link" disabled={importBusy} onClick={() => removeDraft(item.id)}>移除</Button> },
|
||
]} /></>}
|
||
{!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 || 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); }} />
|
||
<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()}>{`导入 ${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} />
|
||
</section>
|
||
</div>;
|
||
}
|
||
|
||
function ValidationNotice({ value }: { value: unknown }) {
|
||
const result = asRow(value); const missing = asRows(result.missingStages);
|
||
const errors = [...(Array.isArray(result.errors) ? result.errors : []), ...missing.map(item => { const monthValue = String(item.month || ''); const match = monthValue.match(/^(\d{4})[-/](\d{1,2})$/); return `${txt(item.year || match?.[1])}年${txt(match?.[2] || item.month)}月${stageName(item.stage)}尚未到齐`; }), ...(Number(result.missingExpectedSlots) > 0 ? [`尚缺 ${Number(result.missingExpectedSlots)} 个应到来源`] : []), ...(Number(result.coverageOverlapCount) > 0 ? ['同一期间的数据范围重叠'] : []), ...(Array.isArray(result.blockingMappingIssues) ? result.blockingMappingIssues : Number(result.blockingMappingIssues) > 0 ? [`有 ${Number(result.blockingMappingIssues)} 项对应关系需要处理`] : [])];
|
||
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, 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);
|
||
const [options, setOptions] = useState<SourceUploadOptions | null>(null);
|
||
const [workflowStatus, setWorkflowStatus] = useState<DataWorkflowStatus | null>(null);
|
||
const [workflowStatusLoaded, setWorkflowStatusLoaded] = useState(false);
|
||
const [workflowStatusError, setWorkflowStatusError] = useState('');
|
||
const statusRead = useDelayedBusy();
|
||
const optionsRead = useDelayedBusy();
|
||
const candidatesRead = useDelayedBusy();
|
||
const [optionError, setOptionError] = useState('');
|
||
const [candidateError, setCandidateError] = useState('');
|
||
const [candidates, setCandidates] = useState<Row[]>([]);
|
||
const [candidatesLoaded, setCandidatesLoaded] = useState(false);
|
||
const optionsAttempted = useRef(false);
|
||
const candidatesAttempted = useRef(false);
|
||
const [resumeId, setResumeId] = useState('');
|
||
const canMaintain = rolesAllow(user, ['SYSTEM_ADMIN', 'DATA_ADMIN']);
|
||
const canPublish = rolesAllow(user, ['SYSTEM_ADMIN', 'DATA_ADMIN']);
|
||
const loadOptions = useCallback(() => optionsRead.run(async () => {
|
||
try { setOptions(await api.sourceUploadOptions()); setOptionError(''); }
|
||
catch (error) { if (!onUnauthorized(error)) setOptionError(failure(error)); }
|
||
}), [onUnauthorized, optionsRead.run]);
|
||
const loadWorkflowStatus = useCallback(() => statusRead.run(async () => {
|
||
try { setWorkflowStatus(await api.dataWorkflowStatus()); setWorkflowStatusLoaded(true); setWorkflowStatusError(''); }
|
||
catch (error) { if (!onUnauthorized(error)) setWorkflowStatusError(failure(error)); }
|
||
}), [onUnauthorized, statusRead.run]);
|
||
const loadCandidates = useCallback(() => candidatesRead.run(async () => {
|
||
try { const result = await api.releases(); setCandidates(collectionItems(result).filter(row => String(row.status).toUpperCase() === 'CANDIDATE')); setCandidatesLoaded(true); setCandidateError(''); }
|
||
catch (error) { if (!onUnauthorized(error)) setCandidateError(failure(error)); }
|
||
}), [candidatesRead.run, onUnauthorized]);
|
||
useEffect(() => {
|
||
if (!active) return;
|
||
if (!options && !optionsAttempted.current) { optionsAttempted.current = true; void loadOptions(); }
|
||
if (!candidatesLoaded && !candidatesAttempted.current) { candidatesAttempted.current = true; void loadCandidates(); }
|
||
if (!workflowStatusLoaded && !workflowStatusError) void loadWorkflowStatus();
|
||
}, [active, currentReleaseId, sources, options, candidatesLoaded, workflowStatusLoaded, workflowStatusError, loadOptions, loadCandidates, loadWorkflowStatus]);
|
||
useEffect(() => { const candidate = new URLSearchParams(window.location.search).get('candidateReleaseId'); if (candidate) setResumeId(candidate); }, []);
|
||
const opened = mode !== null || Boolean(resumeId);
|
||
const open = (next: 'ADD' | 'REPLACE' | 'REBUILD') => { setMode(next); setResumeId(''); 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} 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>
|
||
<div className="nc-primary-actions"><Button type="primary" size="large" icon={<UploadOutlined />} disabled={!canMaintain || !options} onClick={() => open('ADD')}>上传新数据</Button><Button size="large" icon={<SwapOutlined />} disabled={!canMaintain || !options || !options.targets.length} onClick={() => open('REPLACE')}>替换已有数据</Button></div>
|
||
<div className="nc-intake-links"><Button type="link" disabled={!canMaintain || !options?.targets.length} onClick={() => open('REBUILD')}>按当前来源重新计算</Button><span>上传 → 选择年月 → 匹配列 → 校验 → 发布</span></div>
|
||
</section>
|
||
{optionError && <Alert type="error" message="上传选项读取失败" showIcon description={options ? `${optionError};已成功读取的选项仍保留。` : optionError} action={<Button size="small" onClick={() => { optionsAttempted.current = true; void loadOptions(); }}>重试</Button>} />}
|
||
{candidateError && <Alert type="error" message="候选数据读取失败" showIcon description={candidatesLoaded ? `${candidateError};上次成功读取的候选仍保留。` : candidateError} action={<Button size="small" onClick={() => { candidatesAttempted.current = true; void loadCandidates(); }}>重试</Button>} />}
|
||
{!options && optionsRead.busy && <div className="completion-loading"><Spin />读取上传选项…</div>}
|
||
{!candidatesLoaded && candidatesRead.busy && <div className="completion-loading"><Spin />读取候选数据…</div>}
|
||
{!canMaintain && <Alert showIcon type="info" message={canPublish ? '当前账号可以核对和发布已有候选数据' : '上传和替换需要数据维护权限'} description="已授权的操作会按账号权限显示。" />}
|
||
{candidatesLoaded && candidates.length > 0 && <section className="nc-pending-strip panel"><div><strong>待完成的数据</strong><span>已保存的候选可继续校验、对账和发布。</span></div><Select {...readableSelectPopup} aria-label="选择待完成候选数据" placeholder="选择候选数据" value={resumeId || undefined} options={candidates.map(row => ({ value: String(row.id), label: `${txt(row.name || row.id)}${row.complete === false ? ' · 校验未通过' : ''}` }))} onChange={value => { setMode(null); setResumeId(value); }} /></section>}
|
||
{opened && options && <DataUploadWizard key={`${mode}:${resumeId}`} user={user} mode={mode || 'ADD'} options={options} sources={sources} resumeId={resumeId} onUnauthorized={onUnauthorized} onClose={() => { setMode(null); setResumeId(''); }} onComplete={() => { onRefresh(); void loadOptions(); void loadCandidates(); message.success('操作结果已刷新'); }} />}
|
||
</>;
|
||
}
|
||
|
||
export function SourceFilesPanel({ user, sources, 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();
|
||
const [showDeleted, setShowDeleted] = useState(false);
|
||
const [deleted, setDeleted] = useState<SourceDeletionPreview[]>([]);
|
||
const [deletedLoaded, setDeletedLoaded] = useState(false);
|
||
const deletedRead = useDelayedBusy();
|
||
const [metadataError, setMetadataError] = useState('');
|
||
const metadataAttempted = useRef(false);
|
||
const [workflowStatus, setWorkflowStatus] = useState<DataWorkflowStatus | null>(null);
|
||
const [currentSourceIds, setCurrentSourceIds] = useState<string[] | null>(null);
|
||
const [deletedError, setDeletedError] = useState('');
|
||
const [workflowStatusLoaded, setWorkflowStatusLoaded] = useState(false);
|
||
const [selected, setSelected] = useState<{ id: string; restore: boolean } | null>(() => { const id = new URLSearchParams(window.location.search).get('sourceDeleteId'); return id ? { id, restore: false } : null; });
|
||
const canOperate = rolesAllow(user, ['SYSTEM_ADMIN', 'DATA_ADMIN']);
|
||
const loadDeleted = useCallback(() => deletedRead.run(async () => {
|
||
try { const result = await api.deletedSources(); setDeleted(result.items); setDeletedLoaded(true); setDeletedError(''); }
|
||
catch (value) { if (!onUnauthorized(value)) setDeletedError(failure(value)); }
|
||
}), [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[] = [];
|
||
if (status.status === 'fulfilled') { setWorkflowStatus(status.value); setWorkflowStatusLoaded(true); }
|
||
else if (!onUnauthorized(status.reason)) errors.push(`维护状态:${failure(status.reason)}`);
|
||
if (options.status === 'fulfilled') setCurrentSourceIds(options.value.currentSourceIds || []);
|
||
else if (!onUnauthorized(options.reason)) errors.push(`来源范围:${failure(options.reason)}`);
|
||
setMetadataError(errors.join(';'));
|
||
}, [onUnauthorized]);
|
||
useEffect(() => {
|
||
if (!active || metadataAttempted.current) return;
|
||
metadataAttempted.current = true;
|
||
void loadMetadata();
|
||
}, [active, sources, loadMetadata]);
|
||
useEffect(() => { if (active && showDeleted && canOperate && !deletedLoaded) void loadDeleted(); }, [active, showDeleted, canOperate, deletedLoaded, loadDeleted, sources]);
|
||
const period = (source: DeletionSource) => source.year && source.month ? `${source.year}年${String(source.month).padStart(2, '0')}月` : '尚未确认';
|
||
const close = () => { setSelected(null); const url = new URL(window.location.href); if (url.searchParams.has('sourceDeleteId')) { url.searchParams.delete('sourceDeleteId'); window.history.replaceState({}, '', `${url.pathname}${url.search}${url.hash}`); } };
|
||
const simplified = workflowStatus?.simplified === true && workflowStatus.mode === 'TEST';
|
||
const runSourceOperation = async (id: string, restore: boolean) => {
|
||
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 && !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 || 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> },
|
||
{ 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, 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 || 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>
|
||
{selected && !simplified && <SourceDeletionDialog key={`${selected.id}:${selected.restore}`} user={user} sourceId={selected.id} restoring={selected.restore} sources={sources} onUnauthorized={onUnauthorized} onClose={close} onRefresh={() => { onRefresh(); if (showDeleted) void loadDeleted(); }} />}
|
||
</>;
|
||
}
|
||
|
||
function SourceDeletionDialog({ user, sourceId, restoring, sources, onUnauthorized, onClose, onRefresh }: { user: AuthUser; sourceId: string; restoring: boolean; sources: SourceItem[]; onUnauthorized: (error: unknown) => boolean; onClose: () => void; onRefresh: () => void }) {
|
||
const { message } = App.useApp(); const { active } = usePageCache();
|
||
const [preview, setPreview] = useState<SourceDeletionPreview | null>(null);
|
||
const [busy, setBusy] = useState(true); const [error, setError] = useState(''); const [notice, setNotice] = useState('');
|
||
const [reason, setReason] = useState(''); const [confirmed, setConfirmed] = useState(false); const [finished, setFinished] = useState(false);
|
||
const [candidateId, setCandidateId] = useState(''); const [options, setOptions] = useState<SourceUploadOptions | null>(null);
|
||
const requestKey = useRef(crypto.randomUUID()); const buildKey = useRef(crypto.randomUUID());
|
||
const actionLock = useRef(false); const candidateLock = useRef(false);
|
||
const showBusy = useDelayedIndicator(busy, 150);
|
||
const reportError = useCallback((value: unknown) => { if (!onUnauthorized(value)) setError(failure(value)); }, [onUnauthorized]);
|
||
const load = useCallback(async () => { if (!active || actionLock.current) return; setBusy(true); try { const result = await api.sourceDeletionPreview(sourceId); setPreview(result); setError(''); if (restoring && !result.hidden) { setFinished(true); setNotice('此来源已在日常清单中,无需重复恢复。'); } } catch (value) { reportError(value); } finally { setBusy(false); } }, [active, reportError, restoring, sourceId]);
|
||
useEffect(() => { if (active) void load(); }, [active, load]);
|
||
const request = preview?.changeRequest; const requestStatus = String(request?.status || '');
|
||
const isRequested = preview?.nextAction === 'REVIEW_WITHDRAWAL'; const isApproved = preview?.nextAction === 'BUILD_WITHDRAWAL_CANDIDATE'; const isBuilt = preview?.nextAction === 'RECONCILE_CANDIDATE';
|
||
const withdrawing = preview?.mode === 'WITHDRAW_CURRENT' || isRequested || isApproved || isBuilt;
|
||
const canPublish = rolesAllow(user, ['SYSTEM_ADMIN', 'DATA_ADMIN']);
|
||
const canReview = preview?.canReview ?? canPublish; const canBuild = preview?.canBuild ?? canPublish;
|
||
const awaitingTask = preview?.nextAction === 'WAIT_FOR_TASK';
|
||
const canStart = Boolean(preview?.canDelete && !awaitingTask && !preview.hidden && !isRequested && !isApproved && !isBuilt);
|
||
const canRestore = Boolean(preview?.canRestore && preview.hidden);
|
||
const actualRestore = Boolean((restoring || preview?.hidden) && !finished);
|
||
const reasonLabel = actualRestore ? '恢复理由' : isRequested ? '审批说明' : '删除理由';
|
||
const act = async (kind: 'delete' | 'restore' | 'approve' | 'reject' | 'build') => {
|
||
if (!active || !preview || actionLock.current) return; actionLock.current = true; setBusy(true); setError('');
|
||
try {
|
||
if (kind === 'delete') {
|
||
const result = await api.deleteSource(sourceId, { expectedCurrentReleaseId: preview.currentReleaseId, expectedDeleteVersion: preview.deleteVersion, ...(preview.currentUsage ? { expectedRevisionId: preview.currentUsage.revisionId } : {}), reason: reason.trim(), idempotencyKey: requestKey.current });
|
||
setPreview(result); requestKey.current = crypto.randomUUID(); setNotice(result.hidden ? '来源已从日常清单删除,可在“查看已删除来源”中恢复。' : '删除申请已提交,当前正式数据保持不变;下一步由发布者审批。'); setFinished(result.hidden);
|
||
} else if (kind === 'restore') {
|
||
const result = await api.restoreSource(sourceId, { expectedCurrentReleaseId: preview.currentReleaseId, expectedDeleteVersion: preview.deleteVersion, reason: reason.trim() });
|
||
setPreview(result); setNotice('来源已恢复到日常清单。恢复文件清单不会修改已发布的数据结果。'); setFinished(true);
|
||
} else if (kind === 'approve' || kind === 'reject') {
|
||
if (!request?.id) throw new Error('删除申请已变化,请刷新后重试');
|
||
await api.reviewSourceChange(request.id, { approve: kind === 'approve', expectedRowVersion: request.rowVersion, reason: reason.trim() });
|
||
setPreview(await api.sourceDeletionPreview(sourceId)); setNotice(kind === 'approve' ? '删除申请已批准,下一步生成候选数据。' : '删除申请已驳回,当前正式数据未改变。');
|
||
} else {
|
||
if (!request?.id) throw new Error('删除申请已变化,请刷新后重试');
|
||
const result = await api.buildSourceChange(request.id, { expectedCurrentReleaseId: preview.currentReleaseId, idempotencyKey: buildKey.current });
|
||
const updated = await api.sourceDeletionPreview(sourceId); setPreview(updated);
|
||
const releaseId = String(result.releaseId || asRow(result.request).resultReleaseId || updated.changeRequest?.resultReleaseId || '');
|
||
if (releaseId) { setNotice('删除候选已生成,请核对差异后发布。'); await openCandidate(releaseId); }
|
||
else { const run = asRow(result.run); throw new Error(String(run.errorMessage || '候选尚未生成,请刷新查看任务结果')); }
|
||
}
|
||
setReason(''); setConfirmed(false); onRefresh();
|
||
} catch (value) { reportError(value); }
|
||
finally { actionLock.current = false; setBusy(false); }
|
||
};
|
||
const openCandidate = async (releaseId: string) => {
|
||
if (!active || candidateLock.current) return; candidateLock.current = true; setBusy(true); setError('');
|
||
try { const support = await api.sourceUploadOptions(); setOptions(support); setCandidateId(releaseId); }
|
||
catch (value) { reportError(value); } finally { candidateLock.current = false; setBusy(false); }
|
||
};
|
||
const handoff = async () => {
|
||
const url = new URL(window.location.href); url.searchParams.set('page', 'sources'); url.searchParams.set('sourceDeleteId', sourceId); url.searchParams.delete('candidateReleaseId');
|
||
try { await navigator.clipboard.writeText(url.toString()); message.success('处理链接已复制,可交由有权限的同事继续'); } catch (value) { reportError(value); }
|
||
};
|
||
const waitingForColleague = !finished && Boolean(preview && (actualRestore ? !canRestore : isRequested ? !canReview : isApproved ? !canBuild : isBuilt ? false : !canStart));
|
||
const deletionStep = preview?.hidden ? 4 : isBuilt ? 3 : isApproved ? 2 : isRequested ? 1 : 0;
|
||
return <>
|
||
<Modal className="management-modal nc-workflow-modal nc-source-delete-modal" open={!candidateId} width={960} title={finished ? preview?.hidden ? '来源已删除' : '操作已完成' : actualRestore ? '恢复来源' : withdrawing ? '删除当前使用的来源' : '删除来源'} maskClosable={!busy} onCancel={onClose} footer={<div className="nc-modal-footer"><span>原文件及处理记录持续保留,删除操作可追溯。</span><div><Button onClick={onClose}>{finished ? '完成' : '关闭'}</Button>{!finished && preview && <>
|
||
<Button icon={<ReloadOutlined />} disabled={busy} onClick={() => void load()}>刷新状态</Button>
|
||
{actualRestore ? <Button type="primary" loading={busy} disabled={!canRestore || !confirmed || !reason.trim()} onClick={() => void act('restore')}>确认恢复来源</Button> : isRequested ? <>{canReview && <><Button danger disabled={busy || !reason.trim()} onClick={() => void act('reject')}>驳回申请</Button><Button type="primary" loading={busy} disabled={!confirmed || !reason.trim()} onClick={() => void act('approve')}>批准删除申请</Button></>}</> : isApproved ? <Button type="primary" loading={busy} disabled={!canBuild || !confirmed} onClick={() => void act('build')}>生成删除候选</Button> : isBuilt ? <Button type="primary" loading={busy} disabled={!request?.resultReleaseId} onClick={() => { if (request?.resultReleaseId) void openCandidate(request.resultReleaseId); }}>核对并发布删除候选</Button> : <Button type="primary" danger loading={busy} disabled={!canStart || !confirmed || !reason.trim()} onClick={() => void act('delete')}>{withdrawing ? '提交删除申请' : '确认删除来源'}</Button>}
|
||
</>}</div></div>}>
|
||
{error && <Alert type="error" showIcon message="操作未完成" description={preview ? `${error};已成功读取的来源信息仍保留。` : error} action={!preview ? <Button size="small" onClick={() => void load()}>重试</Button> : undefined} />}
|
||
{notice && <Alert type={finished ? 'success' : 'info'} showIcon message={notice} />}
|
||
<Spin spinning={showBusy}>{preview ? <>
|
||
<div className="nc-file-summary"><FileExcelOutlined /><strong>{preview.source.sourceFile}</strong><span>{preview.source.year && preview.source.month ? `${preview.source.year}年${preview.source.month}月` : '期间待确认'} · {stageName(preview.source.stage)}</span></div>
|
||
{withdrawing && !actualRestore && <Steps className="nc-delete-steps" current={deletionStep} size="small" items={[{ title: '确认影响' }, { title: '审批申请' }, { title: '生成候选' }, { title: '对账与发布' }, { title: '移入已删除' }]} />}
|
||
<div className="nc-review-facts nc-deletion-impact"><div><small>当前正式数据</small><strong>{preview.currentUsage ? '正在使用此来源' : '未使用此来源'}</strong></div><div><small>归档来源记录</small><strong>{preview.history.revisionCount} 个</strong></div><div><small>正式处理记录</small><strong>{preview.history.publishedReleaseCount} 个</strong></div><div><small>候选处理记录</small><strong>{preview.history.candidateReleaseCount} 个</strong></div></div>
|
||
{!finished && <Alert showIcon type={preview.currentUsage ? 'warning' : 'info'} message={actualRestore ? '恢复到来源清单' : preview.currentUsage ? '此文件参与了当前正式结果,须完成审批、候选和发布' : '仅从日常来源清单删除'} description={actualRestore ? '恢复后可重新选择此来源;已有查询结果和处理记录保持原样。' : preview.currentUsage ? '提交申请和批准均不会改变当前查询结果。生成候选后须核对差异并明确发布,发布成功才从当前结果移除此来源,并转入已删除清单。' : '不会删除磁盘原文件,不会影响已有结果或处理记录;可从“查看已删除来源”恢复。'} />}
|
||
{preview.source.deletionReason && !request && <section className="nc-delete-request"><p><span>删除理由</span>{preview.source.deletionReason}</p></section>}{request && <section className="nc-delete-request"><div><strong>删除申请</strong><Tag>{({ REQUESTED: '等待审批', APPROVED: '已批准,等待候选', REJECTED: '已驳回', BUILT: '候选已生成' } as Record<string, string>)[requestStatus] || requestStatus}</Tag></div><p><span>申请理由</span>{txt(request.reason)}</p>{request.reviewReason && <p><span>审批说明</span>{request.reviewReason}</p>}</section>}
|
||
{!finished && awaitingTask && <Alert type="info" showIcon message="来源仍在校验或计算中" description="任务完成后再删除,点击“刷新状态”重新检查。" />}
|
||
{!finished && !isBuilt && !awaitingTask && <>
|
||
{actualRestore || canStart || (isRequested && canReview) ? <Form layout="vertical"><Form.Item label={reasonLabel} required><Input.TextArea aria-label={reasonLabel} rows={3} value={reason} maxLength={1000} placeholder={actualRestore ? '说明恢复此来源的原因' : isRequested ? '填写批准或驳回的依据' : '说明删除此来源的原因'} onChange={event => setReason(event.target.value)} /></Form.Item></Form> : null}
|
||
{(actualRestore && canRestore || canStart || isRequested && canReview || isApproved && canBuild) && <Checkbox checked={confirmed} onChange={event => setConfirmed(event.target.checked)}>{actualRestore ? '我已核对文件和期间,确认恢复来源清单。' : isApproved ? '我已核对批准的删除范围,确认生成候选;正式数据在发布前保持不变。' : isRequested ? '我已核对该来源及删除影响,确认批准此申请。' : preview.currentUsage ? '我已核对删除影响,确认提交申请并保留原件及历史记录。' : '我确认将此文件从日常清单删除,并保留原件及历史记录。'}</Checkbox>}
|
||
</>}
|
||
{waitingForColleague && !awaitingTask && <Alert type="info" showIcon message={isRequested ? '等待有审批权限的发布者继续' : isApproved ? '等待有权限的发布者生成候选' : actualRestore ? '此账号没有恢复权限' : '此账号没有本次删除操作权限'} description={<>{preview.blockedReason && <p>{preview.blockedReason}</p>}<span>可复制当前处理链接交接;对方打开后会看到相同来源、申请和下一步。</span><Button type="link" onClick={() => void handoff()}>复制处理链接</Button></>} />}
|
||
{!finished && isBuilt && <Alert type="info" showIcon message="删除候选已保存,等待核对与发布" description="点击“核对并发布删除候选”继续查看差异;没有发布权限的账号可在候选窗口复制交接链接。" />}
|
||
</> : showBusy ? <div className="loading-panel">正在核对来源及影响…</div> : null}</Spin>
|
||
</Modal>
|
||
{candidateId && options && <DataUploadWizard key={`deletion:${candidateId}`} user={user} mode="ADD" purpose="WITHDRAW" handoffSourceId={sourceId} initialReason={request?.reason} options={options} sources={sources} resumeId={candidateId} onUnauthorized={onUnauthorized} onClose={() => { setCandidateId(''); void load(); }} onComplete={() => { setFinished(true); setNotice('删除候选已发布,该来源已从当前结果移除;原件和处理记录保留。'); onRefresh(); void load(); }} />}
|
||
</>;
|
||
}
|
||
|
||
function DataUploadWizard({ user, mode, purpose, handoffSourceId, initialReason, options, sources, resumeId, onUnauthorized, onClose, onComplete }: { user: AuthUser; mode: 'ADD' | 'REPLACE' | 'REBUILD'; purpose?: 'WITHDRAW'; handoffSourceId?: string; initialReason?: string; options: SourceUploadOptions; sources: SourceItem[]; resumeId: string; onUnauthorized: (error: unknown) => boolean; onClose: () => void; onComplete: () => void }) {
|
||
const { message } = App.useApp(); const { active } = usePageCache(); const activeRef = useRef(active); activeRef.current = active; const input = useRef<HTMLInputElement>(null); const generation = useRef(0); const importKey = useRef(crypto.randomUUID()); const publishKey = useRef(crypto.randomUUID());
|
||
const runStorageKey = `quality-import-run:${user.id}`;
|
||
const [storedRunId] = useState(() => { try { return localStorage.getItem(runStorageKey) || ''; } catch { return ''; } });
|
||
const [step, setStep] = useState(resumeId ? 4 : storedRunId ? 3 : 0); const [busy, setBusy] = useState(Boolean(storedRunId)); const [error, setError] = useState('');
|
||
const [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 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>());
|
||
const actionLock = useRef(false); const pollLock = useRef(false); const pollAgainAfterCurrent = useRef(false); const candidateReadLock = useRef(false);
|
||
const runIdRef = useRef('');
|
||
const [reconciliation, setReconciliation] = useState<Row | null>(null); const [issues, setIssues] = useState<Row[]>([]);
|
||
const [differenceReason, setDifferenceReason] = useState(''); const [confirmDifferences, setConfirmDifferences] = useState(false); const [publishConfirmed, setPublishConfirmed] = useState(false); const [published, setPublished] = useState(false);
|
||
const target = options.targets.find(item => item.documentId === targetId); const fields = options.fields[stage] || [];
|
||
const headers = workbook?.preview.headers || []; const missingFields = fields.filter(field => field.required && !fieldMap[field.name]); const duplicateColumns = Object.values(fieldMap).length !== new Set(Object.values(fieldMap)).size;
|
||
const canPublish = rolesAllow(user, ['SYSTEM_ADMIN', 'DATA_ADMIN']);
|
||
const reportError = useCallback((value: unknown) => { if (!onUnauthorized(value)) setError(failure(value)); }, [onUnauthorized]);
|
||
const loadCandidate = async (id: string, isCurrent: () => boolean = () => activeRef.current) => {
|
||
if (!activeRef.current || !isCurrent()) return false;
|
||
const inspected = await api.governanceReleaseInspect(id);
|
||
if (!activeRef.current || !isCurrent()) return false;
|
||
setRelease(asRow(inspected.release));
|
||
const result = await api.governanceReleaseReconciliations(id);
|
||
if (!activeRef.current || !isCurrent()) return false;
|
||
const list = collectionItems(result); const selected = list.find(item => String(item.id) === String(result.acceptanceId)) || list[0];
|
||
const reconciliation = selected?.id ? await api.governanceReconciliation(String(selected.id)) : null;
|
||
if (!activeRef.current || !isCurrent()) return false;
|
||
setReconciliation(reconciliation);
|
||
return true;
|
||
};
|
||
useEffect(() => {
|
||
if (!active || !resumeId || candidateReadLock.current) return;
|
||
candidateReadLock.current = true; setBusy(true);
|
||
loadCandidate(resumeId).catch(reportError).finally(() => { candidateReadLock.current = false; setBusy(false); });
|
||
return () => { generation.current++; };
|
||
}, [active, reportError, resumeId]);
|
||
const runId = String(run?.id || '');
|
||
runIdRef.current = runId;
|
||
const pollRun = useCallback(async () => {
|
||
if (!activeRef.current || !runId) return;
|
||
if (pollLock.current) { pollAgainAfterCurrent.current = true; return; }
|
||
pollLock.current = true;
|
||
try {
|
||
const result = await api.importRun(runId);
|
||
const isCurrent = () => activeRef.current && runIdRef.current === runId;
|
||
if (!isCurrent()) return;
|
||
setRun(result.run); setError('');
|
||
const status = String(result.run.status || '').toUpperCase();
|
||
if (status === 'COMPLETED') {
|
||
const id = String(result.run.resultReleaseId || ''); if (!id) throw new Error('校验已完成,但没有返回候选数据');
|
||
const candidateRead = await runImportPollFollowup(runId, () => isCurrent(), () => loadCandidate(id, isCurrent));
|
||
if (!candidateRead.started || !candidateRead.current || !candidateRead.value || !isCurrent()) return;
|
||
setStep(4);
|
||
if (asRow(result.run.validation).complete === false) {
|
||
const issueRead = await runImportPollFollowup(runId, () => isCurrent(), () => api.importIssues(runId));
|
||
if (!issueRead.started || !issueRead.current) return;
|
||
setIssues(collectionItems(issueRead.value));
|
||
}
|
||
if (!completionNotified.current.has(runId)) { completionNotified.current.add(runId); onComplete(); }
|
||
setRunTerminalId(runId); setBusy(false);
|
||
try { localStorage.removeItem(runStorageKey); } catch { /* The server task remains in task history. */ }
|
||
} else if (['FAILED', 'CANCELLED'].includes(status)) {
|
||
const issueRead = await runImportPollFollowup(runId, () => isCurrent(), () => api.importIssues(runId));
|
||
if (!issueRead.started || !issueRead.current) return;
|
||
setIssues(collectionItems(issueRead.value)); setRunTerminalId(runId); setBusy(false);
|
||
try { localStorage.removeItem(runStorageKey); } catch { /* The server task remains in task history. */ }
|
||
}
|
||
} catch (value) { if (activeRef.current && runIdRef.current === runId) { reportError(value); setBusy(false); } }
|
||
finally {
|
||
pollLock.current = false;
|
||
if (pollAgainAfterCurrent.current && activeRef.current && runIdRef.current === runId) {
|
||
pollAgainAfterCurrent.current = false;
|
||
void pollRun();
|
||
}
|
||
}
|
||
}, [loadCandidate, onComplete, reportError, runId, runStorageKey]);
|
||
useVisiblePolling(pollRun, 2000, active && Boolean(runId) && runTerminalId !== runId, true);
|
||
const 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 }); 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 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 || !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 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); }
|
||
finally { actionLock.current = false; }
|
||
};
|
||
const rebuild = async () => {
|
||
if (!active || actionLock.current) return; actionLock.current = true;
|
||
setBusy(true); setError(''); setStep(3);
|
||
try {
|
||
if (!options.currentReleaseId) throw new Error('当前没有可用于重新计算的来源');
|
||
const inspected = await api.governanceReleaseInspect(options.currentReleaseId); const members = asRows(inspected.members);
|
||
const ids = options.currentSourcesComplete && options.currentSourceIds?.length ? options.currentSourceIds : members.map(member => sources.find(source => source.sha256 === member.sha256 && source.stage === member.stage && source.year === Number(member.sourceYear) && source.month === Number(member.sourceMonth))?.id);
|
||
if (!ids.length || ids.some(id => !id)) throw new Error('部分原始文件当前不可用于重算,请重新上传缺少的原始文件。');
|
||
const created = asRow(await api.startImport({ sourceIds: ids as string[], expectedCurrentReleaseId: options.currentReleaseId, idempotencyKey: importKey.current }));
|
||
const nextRun = asRow(created.run || created); if (!nextRun.id) throw new Error('服务端未返回计算任务编号');
|
||
setRun(nextRun); try { localStorage.setItem(runStorageKey, String(nextRun.id)); } catch { /* Server task history remains available if local storage is unavailable. */ }
|
||
} catch (value) { reportError(value); setBusy(false); }
|
||
finally { actionLock.current = false; }
|
||
};
|
||
const reconcile = async () => {
|
||
if (!active || !release?.id || actionLock.current) return; actionLock.current = true; setBusy(true); setError('');
|
||
try { const created = await api.createGovernanceReconciliation(String(release.id), { ...(options.currentReleaseId ? { baselineReleaseId: options.currentReleaseId } : {}), dimensions: ['overall', 'department', 'group', 'product', 'projectGroup'] }); const detail = asRow(created.reconciliation || created); setReconciliation(detail.id ? await api.governanceReconciliation(String(detail.id)) : detail); setConfirmDifferences(false); }
|
||
catch (value) { reportError(value); } finally { actionLock.current = false; setBusy(false); }
|
||
};
|
||
const confirm = async () => {
|
||
if (!active || !reconciliation?.id || actionLock.current) return; actionLock.current = true; setBusy(true); setError('');
|
||
try { const evidence = asRow(reconciliation.result); const result = await api.confirmGovernanceReconciliation(String(reconciliation.id), { expectedRowVersion: Number(reconciliation.rowVersion || 0), expectedDifferenceHash: String(reconciliation.differenceHash), ...(evidence.transitionDifferenceHash ? { expectedTransitionDifferenceHash: String(evidence.transitionDifferenceHash) } : {}), reason: differenceReason.trim() }); setReconciliation(result); }
|
||
catch (value) { reportError(value); } finally { actionLock.current = false; setBusy(false); }
|
||
};
|
||
const publish = async () => {
|
||
if (!active || !release?.id || actionLock.current) return; actionLock.current = true; setBusy(true); setError('');
|
||
try { await api.publishRelease(String(release.id), { expectedCurrentReleaseId: release.expectedCurrentReleaseId === undefined ? options.currentReleaseId : release.expectedCurrentReleaseId as string | null, idempotencyKey: publishKey.current, reason: reason.trim() || differenceReason.trim() || '经来源校验与候选基线对账后发布' }); setPublished(true); onComplete(); }
|
||
catch (value) { reportError(value); } finally { actionLock.current = false; setBusy(false); }
|
||
};
|
||
const evidence = asRow(reconciliation?.result); const comparisons = asRows(evidence.periodComparisons); const reconciliationErrors = Array.isArray(evidence.errors) ? evidence.errors : [];
|
||
const publishReady = release?.complete === true && reconciliation?.publishReady === true;
|
||
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 && !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>{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>}
|
||
{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>}
|
||
{issues.length > 0 && <><h3>需要处理的来源行</h3><Table size="small" bordered dataSource={issues} rowKey={(row, index) => String(row.id || index)} pagination={{ pageSize: 15 }} columns={[{ title: '工作表', dataIndex: 'sheet', width: 120 }, { title: '行号', dataIndex: 'rowNumber', width: 80 }, { title: '字段', dataIndex: 'field', width: 130 }, { title: '问题说明', dataIndex: 'message' }]} /></>}
|
||
</>}
|
||
</Modal>;
|
||
}
|
||
|
||
const MASTER_KINDS: { value: MasterWorkbookKind; label: string; columns: { key: string; label: string; required?: boolean }[] }[] = [
|
||
...[{ value: 'departments', label: '产业部' }, { value: 'groups', label: '业务分组' }, { value: 'products', label: '产品' }, { value: 'projectGroups', label: '项目组' }].map(item => ({ ...item, value: item.value as MasterWorkbookKind, columns: [{ key: 'name', label: '名称', required: true }, { key: 'enabled', label: '启用状态(可选)' }] })),
|
||
{ value: 'categoryLookup', label: '业务分组对应', columns: [{ key: 'source', label: 'PDT代码', required: true }, { key: 'secondary', label: '销售片区', required: true }, { key: 'target', label: '业务分组', required: true }, { key: 'enabled', label: '启用状态(可选)' }] },
|
||
{ value: 'projectGroupLookup', label: '项目组对应', columns: [{ key: 'source', label: '客户代码', required: true }, { key: 'secondary', label: '业务分组', required: true }, { key: 'target', label: '项目组', required: true }, { key: 'enabled', label: '启用状态(可选)' }] },
|
||
{ value: 'departmentLookup', label: '产业部对应', columns: [{ key: 'source', label: '源事业部', required: true }, { key: 'target', label: '统一产业部', required: true }, { key: 'enabled', label: '启用状态(可选)' }] },
|
||
{ value: 'productLookup', label: '产品对应', columns: [{ key: 'source', label: '源规格', required: true }, { key: 'target', label: '统一产品', required: true }, { key: 'enabled', label: '启用状态(可选)' }] },
|
||
];
|
||
|
||
export function MasterWorkbookUpload({ kind, base, onUnauthorized, onComplete, simplified = false, expectedCurrentReleaseId = null }: { kind: 'masterData' | 'mappings'; base?: Row; onUnauthorized: (error: unknown) => boolean; onComplete: () => void; simplified?: boolean; expectedCurrentReleaseId?: string | null }) {
|
||
const { message } = App.useApp();
|
||
const fileInput = useRef<HTMLInputElement>(null);
|
||
const [open, setOpen] = useState(false); const [preview, setPreview] = useState<MasterWorkbookPreview | null>(null);
|
||
const [sheetName, setSheetName] = useState('');
|
||
const [selectedKind, setSelectedKind] = useState<MasterWorkbookKind>(kind === 'masterData' ? 'departments' : 'categoryLookup');
|
||
const [keyFormat, setKeyFormat] = useState<MasterWorkbookKeyFormat>('SEPARATE_COLUMNS');
|
||
const [mode, setMode] = useState<'MERGE' | 'REPLACE'>('MERGE'); const [columns, setColumns] = useState<Record<string, string>>({});
|
||
const [name, setName] = useState(''); const [reason, setReason] = useState(''); const [confirmed, setConfirmed] = useState(false);
|
||
const [busy, setBusy] = useState(false); const [error, setError] = useState(''); const [result, setResult] = useState<Row | null>(null);
|
||
const actionLock = useRef(false);
|
||
const [preparedDefinition, setPreparedDefinition] = useState<Row | null>(null);
|
||
const [preparedReleaseId, setPreparedReleaseId] = useState<string | null>(null);
|
||
const workflowOperation = useDataWorkflowOperation('mapping-workbook-import', () => { onComplete(); message.success('基础数据已保存,报表已更新'); });
|
||
useEffect(() => { if (workflowOperation.operation?.operationId) setOpen(true); }, [workflowOperation.operation?.operationId]);
|
||
const bundle = selectedKind === 'standardBundle';
|
||
const availableKinds = MASTER_KINDS.filter(item => kind === 'masterData' ? !item.value.endsWith('Lookup') : item.value.endsWith('Lookup'));
|
||
const definition = MASTER_KINDS.find(item => item.value === selectedKind) || MASTER_KINDS[0];
|
||
const activeColumns = selectedKind === 'categoryLookup' && keyFormat === 'PDT_REGION_COMBINED' ? definition.columns.filter(column => column.key !== 'secondary').map(column => column.key === 'source' ? { ...column, label: '匹配列(如P001中国区)' } : column) : definition.columns;
|
||
const sheet = preview?.sheets.find(item => item.name === sheetName);
|
||
const suggestedTables = preview?.suggestedTables || [];
|
||
const summary = asRow(result?.summary); const validation = asRow(result?.validation); const draft = asRow(result?.mapping || result?.draft || result?.version || result);
|
||
const tableSummaries = asRows(result?.tableSummaries || summary.tableSummaries);
|
||
const kindLabel = (value: unknown) => MASTER_KINDS.find(item => item.value === value)?.label || txt(value);
|
||
const inferFormat = (headers: string[], nextKind: MasterWorkbookKind): MasterWorkbookKeyFormat => nextKind === 'categoryLookup' && headers.includes('匹配') && headers.includes('产业部') ? 'PDT_REGION_COMBINED' : 'SEPARATE_COLUMNS';
|
||
const autoMatch = (headers: string[], nextKind: MasterWorkbookKind, format: MasterWorkbookKeyFormat, suggestions = suggestedTables, selectedSheet = sheetName) => {
|
||
const suggestion = suggestions.find(item => item.kind === nextKind && item.sheetName === selectedSheet && (!item.keyFormat || item.keyFormat === format));
|
||
if (suggestion) return { ...suggestion.columns };
|
||
const spec = MASTER_KINDS.find(item => item.value === nextKind); if (!spec) return {};
|
||
const candidates: Record<string, string[]> = {
|
||
code: ['编码', '代码'], name: ['名称', nextKind === 'departments' ? '事业部' : nextKind === 'groups' ? '产业部' : nextKind === 'projectGroups' ? '项目组' : '产品'], enabled: ['启用状态', '启用', '状态'],
|
||
source: nextKind === 'categoryLookup' ? format === 'PDT_REGION_COMBINED' ? ['匹配'] : ['PDT代码', 'PDT号', 'PDT'] : nextKind === 'projectGroupLookup' ? ['客户代码'] : nextKind === 'departmentLookup' ? ['源事业部', '事业部'] : ['源规格', '成品规格', '规格'],
|
||
secondary: nextKind === 'projectGroupLookup' ? ['业务分组', '产业部'] : ['销售片区', '销售区域'],
|
||
target: nextKind === 'categoryLookup' ? ['业务分组', '产业部'] : nextKind === 'projectGroupLookup' ? ['项目组'] : nextKind === 'departmentLookup' ? ['统一产业部', '产业部'] : ['统一产品', '产品'],
|
||
};
|
||
return Object.fromEntries(spec.columns.filter(column => !(nextKind === 'categoryLookup' && format === 'PDT_REGION_COMBINED' && column.key === 'secondary')).map(column => [column.key, candidates[column.key]?.find(header => headers.includes(header)) || '']).filter(([, header]) => header));
|
||
};
|
||
const selectKind = (nextKind: MasterWorkbookKind) => {
|
||
setSelectedKind(nextKind); setConfirmed(false);
|
||
if (nextKind === 'standardBundle') { setColumns({}); return; }
|
||
const suggested = suggestedTables.find(item => item.kind === nextKind);
|
||
const nextSheet = suggested ? preview?.sheets.find(item => item.name === suggested.sheetName) : sheet;
|
||
if (nextSheet) setSheetName(nextSheet.name);
|
||
const format = suggested?.keyFormat || inferFormat(nextSheet?.headers || [], nextKind); setKeyFormat(format);
|
||
setColumns(autoMatch(nextSheet?.headers || [], nextKind, format, suggestedTables, nextSheet?.name || sheetName));
|
||
};
|
||
const readFile = async (file?: File) => {
|
||
if (!file || actionLock.current) return; actionLock.current = true; setBusy(true); setError('');
|
||
try {
|
||
const response = await api.previewMasterWorkbook(file); setPreview(response);
|
||
const nextKind = response.standardBundleAvailable ? 'standardBundle' : (selectedKind === 'standardBundle' ? kind === 'masterData' ? 'departments' : 'categoryLookup' : selectedKind);
|
||
const suggestion = response.suggestedTables?.find(item => item.kind === nextKind);
|
||
const first = response.sheets.find(item => item.name === suggestion?.sheetName) || response.sheets[0];
|
||
const format = suggestion?.keyFormat || inferFormat(first?.headers || [], nextKind);
|
||
setSelectedKind(nextKind); setSheetName(first?.name || ''); setKeyFormat(format);
|
||
setColumns(nextKind === 'standardBundle' ? {} : autoMatch(first?.headers || [], nextKind, format, response.suggestedTables || [], first?.name || ''));
|
||
setName(simplified ? configurationDateTime(new Date()) : `${nextKind === 'standardBundle' ? '整本基础数据' : kindLabel(nextKind)}·${file.name.replace(/\.xlsx$/i, '')}`.slice(0, 120));
|
||
setResult(null); setConfirmed(false);
|
||
} catch (value) { if (!onUnauthorized(value)) setError(failure(value)); }
|
||
finally { actionLock.current = false; setBusy(false); if (fileInput.current) fileInput.current.value = ''; }
|
||
};
|
||
const submit = async () => {
|
||
if (!preview || !base || !sheet || actionLock.current) return; actionLock.current = true; setBusy(true); setError('');
|
||
try {
|
||
if (simplified && preparedDefinition) {
|
||
await workflowOperation.start(() => api.applyDataWorkflow({ kind: 'mapping', name: name.trim(), definition: preparedDefinition, description: '测试阶段基础数据导入', expectedCurrentReleaseId: preparedReleaseId }));
|
||
return;
|
||
}
|
||
const response = await (simplified ? api.prepareMasterWorkbook : api.importMasterWorkbook)({ previewId: preview.previewId, sheetName: bundle ? suggestedTables[0]?.sheetName || sheetName : sheetName, kind: selectedKind, mode, columns: bundle ? {} : columns, ...(selectedKind === 'categoryLookup' ? { keyFormat } : {}), baseMappingVersionId: String(base.id), expectedBaseRowVersion: Number(base.rowVersion || 0), name: name.trim(), reason: simplified ? '测试阶段基础数据导入' : reason.trim() });
|
||
if (simplified) {
|
||
const importedDraft = asRow(response.mapping || response.draft || response.version || response);
|
||
let definition = asRow(importedDraft.definition);
|
||
if (!Object.keys(definition).length) {
|
||
const list = collectionItems(await api.mappings()).filter(item => item && typeof item === 'object') as Row[];
|
||
const matching = list.find(item => String(item.id || '') === String(importedDraft.id || '') && item.definition && typeof item.definition === 'object')
|
||
|| [...list].reverse().find(item => String(item.name || '') === name.trim() && item.definition && typeof item.definition === 'object');
|
||
definition = asRow(matching?.definition);
|
||
}
|
||
if (!Object.keys(definition).length) throw new Error('导入内容已接收,但没有读取到生成的配置定义;请刷新后重试。');
|
||
setPreparedDefinition(definition);
|
||
setPreparedReleaseId(expectedCurrentReleaseId);
|
||
setResult(response);
|
||
await workflowOperation.start(() => api.applyDataWorkflow({ kind: 'mapping', name: name.trim(), definition, description: '测试阶段基础数据导入', expectedCurrentReleaseId }));
|
||
return;
|
||
}
|
||
setResult(response); onComplete();
|
||
} catch (value) { if (!onUnauthorized(value)) setError(failure(value)); }
|
||
finally { actionLock.current = false; setBusy(false); }
|
||
};
|
||
const canSubmit = Boolean(base && name.trim() && (simplified || (reason.trim() && confirmed)) && (bundle ? preview?.standardBundleAvailable && suggestedTables.length : sheet && activeColumns.every(column => !column.required || columns[column.key])));
|
||
return <>
|
||
<Button type="primary" icon={<UploadOutlined />} disabled={!base || workflowOperation.busy} title={!base ? '先加载当前配置' : undefined} onClick={() => { setOpen(true); setPreview(null); setResult(null); setPreparedDefinition(null); setError(''); setReason(''); setConfirmed(false); }}>上传{kind === 'masterData' ? '基础数据表' : '对应关系表'}</Button>
|
||
<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} />}
|
||
{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} />}
|
||
{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 ? '系统正在保存更新并重新计算报表。' : '配置已更新,报表已刷新。') : '当前数据未改变。可关闭此窗口,查看、校验并启用已保存的配置。'} />
|
||
<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>
|
||
{tableSummaries.length > 0 && <Table size="small" bordered dataSource={tableSummaries} rowKey={(row, index) => `${row.kind}:${index}`} pagination={false} columns={[{ title: '数据类别', dataIndex: 'kind', render: (value, row) => txt(row.label || kindLabel(value)) }, { title: '工作表', dataIndex: 'sheetName' }, { title: '导入行数', dataIndex: 'rowCount', align: 'right', render: (value, row) => txt(row.imported ?? asRow(row.summary).imported ?? value) }, { title: '新增', align: 'right', render: (_, row) => txt(row.added ?? asRow(row.summary).added) }, { title: '更新', align: 'right', render: (_, row) => txt(row.updated ?? asRow(row.summary).updated) }, { title: '停用', align: 'right', render: (_, row) => txt(row.disabled ?? asRow(row.summary).disabled) }]} />}
|
||
{Array.isArray(validation.errors) && validation.errors.length > 0 && <Alert type="warning" showIcon message="草稿需要处理以下事项" description={validation.errors.map(txt).join(';')} />}
|
||
{!simplified && <Alert type="info" showIcon message="启用后还需要重新计算" description="启用名录或对应关系后,到“数据接入”选择“按当前来源重新计算”,完成对账并发布,查询结果才会采用新配置。" />}
|
||
</> : <>
|
||
<div className="nc-workbook-upload-intro"><div><strong>从 Excel 导入基础数据</strong><p>{simplified ? '可自动识别整本基础数据,或选择单个工作表匹配各列;合并更新和整表替换后直接重算并更新报表。' : '可自动识别整本基础数据,或选择单个工作表匹配各列。合并更新和整表替换均先生成草稿。'}</p></div><input ref={fileInput} type="file" accept=".xlsx" className="visually-hidden-file" aria-label="选择基础数据或对应关系Excel表" onChange={event => void readFile(event.target.files?.[0])} /><Button icon={<UploadOutlined />} loading={busy} onClick={() => fileInput.current?.click()}>{preview ? '重新选择文件' : '选择 Excel 文件'}</Button></div>
|
||
{preview && <Form layout="vertical">
|
||
<div className="nc-form-grid">
|
||
<Form.Item label="导入哪一类数据" required><Select aria-label="导入数据类型" value={selectedKind} options={[...(preview.standardBundleAvailable ? [{ value: 'standardBundle' as MasterWorkbookKind, label: '整本基础数据(自动识别)' }] : []), ...availableKinds.map(item => ({ value: item.value, label: item.label }))]} onChange={selectKind} /></Form.Item>
|
||
{!bundle && <Form.Item label="工作表" required><Select {...readableSelectPopup} aria-label="基础表工作表" value={sheetName} options={preview.sheets.map(item => ({ value: item.name, label: `${item.name} · ${item.rowCount}行` }))} onChange={value => { const next = preview.sheets.find(item => item.name === value); const format = inferFormat(next?.headers || [], selectedKind); setSheetName(value); setKeyFormat(format); setColumns(autoMatch(next?.headers || [], selectedKind, format, suggestedTables, value)); setConfirmed(false); }} /></Form.Item>}
|
||
<Form.Item label="更新方式" required><Select aria-label="基础表更新方式" value={mode} options={[{ value: 'MERGE', label: '合并更新:新增或更新表内记录' }, { value: 'REPLACE', label: '整表替换:表外旧记录停用' }]} onChange={value => { setMode(value); setConfirmed(false); }} /></Form.Item>
|
||
{selectedKind === 'categoryLookup' && <Form.Item label="业务分组匹配方式" required><Select aria-label="业务分组匹配方式" value={keyFormat} options={[{ value: 'SEPARATE_COLUMNS', label: '两列:PDT代码 + 销售片区' }, { value: 'PDT_REGION_COMBINED', label: '一列:匹配(如P001中国区)' }]} onChange={value => { setKeyFormat(value); setColumns(autoMatch(sheet?.headers || [], selectedKind, value)); setConfirmed(false); }} /></Form.Item>}
|
||
</div>
|
||
{bundle ? <section className="nc-bundle-preview"><h3>将一起导入的工作表</h3><Table size="small" bordered dataSource={suggestedTables} rowKey={(row, index) => `${row.kind}:${index}`} pagination={false} columns={[{ title: '工作表', dataIndex: 'sheetName', width: 200 }, { title: '数据类别', dataIndex: 'kind', width: 180, render: (value, row) => txt(row.label || kindLabel(value)) }, { title: '来源行数', dataIndex: 'rowCount', align: 'right', width: 100 }, { title: '已识别的字段对应', render: (_, row) => Object.entries(row.columns).map(([field, header]) => `${({ code: '编码', name: '名称', source: row.keyFormat === 'PDT_REGION_COMBINED' ? '匹配条件' : '来源条件', secondary: '业务分组/销售片区', target: '对应结果', enabled: '启用状态' } as Record<string, string>)[field] || field} ← ${header}`).join(';') }]} /><p className="nc-note">{simplified ? '以上名录和对应关系将一起保存并更新报表' : '以上名录和对应关系合并生成同一个草稿'},项目组名录按名称去重。月份等辅助工作表不导入。</p></section> : <>
|
||
<div className="nc-column-matching">{activeColumns.map(column => <label key={column.key} className="nc-field-match"><span>{column.label}{column.required && <b>必填</b>}</span><Select {...readableSelectPopup} aria-label={`${column.label}对应的基础表列`} value={columns[column.key] || undefined} allowClear placeholder="选择 Excel 列" options={(sheet?.headers || []).map(header => ({ value: header, label: header }))} onChange={value => { setColumns(previous => { const next = { ...previous }; if (value) next[column.key] = value; else delete next[column.key]; return next; }); setConfirmed(false); }} /></label>)}</div>
|
||
{selectedKind === 'projectGroupLookup' && <p className="nc-note">此处“业务分组”可以选择原表中的“产业部”列;“事业部”用于产业部名录。</p>}
|
||
</>}
|
||
{!simplified && <div className="nc-form-grid"><Form.Item label="草稿名称" required><Input aria-label="基础表草稿名称" value={name} maxLength={120} onChange={event => setName(event.target.value)} /></Form.Item><Form.Item label="变更理由" required><Input aria-label="基础表变更理由" value={reason} maxLength={1000} placeholder="说明新增或替换的原因" onChange={event => setReason(event.target.value)} /></Form.Item></div>}
|
||
{simplified && <p className="nc-note">名称:{name || '新配置'} · 修改内容会在导入后直接应用。</p>}
|
||
{mode === 'REPLACE' && <Alert type="warning" showIcon message={simplified ? '整表替换会停用导入表中未出现的旧记录' : '整表替换会在新草稿中停用导入表未出现的旧记录'} description={bundle ? '仅处理上方已识别的数据类别,其他名录和对应关系沿用当前配置。' : '仅影响当前选择的数据类型,其余名录和对应关系沿用当前配置。'} />}
|
||
{!bundle && <><h3>导入预览 · {sheet?.rowCount || 0} 行</h3><SampleTable headers={activeColumns.filter(column => columns[column.key]).map(column => column.label)} rows={(sheet?.sampleRows || []).map(row => Object.fromEntries(activeColumns.filter(column => columns[column.key]).map(column => [column.label, row[columns[column.key]]])))} /></>}
|
||
{!simplified && <Checkbox checked={confirmed} onChange={event => setConfirmed(event.target.checked)}>{bundle ? '我已核对上方全部工作表、数据类别和更新方式,确认合并生成一个新草稿。' : '我已核对所选类型、字段对应和更新方式,确认生成新草稿。'}</Checkbox>}
|
||
</Form>}
|
||
</>}
|
||
</Modal>
|
||
</>;
|
||
}
|
||
|
||
export function ReadableConfigDefinition({ kind, value }: { kind: 'masterData' | 'mappings'; value: unknown }) {
|
||
const definition = asRow(value); const master = asRow(definition.masterData); const disabled = asRow(definition.disabledMappings);
|
||
const kinds = MASTER_KINDS.filter(item => kind === 'masterData' ? !item.value.endsWith('Lookup') : item.value.endsWith('Lookup'));
|
||
return <div className="nc-config-contents">{kinds.map(item => {
|
||
const isLookup = item.value.endsWith('Lookup');
|
||
const stopped = new Set(Array.isArray(disabled[item.value]) ? disabled[item.value] as string[] : []);
|
||
const rows = isLookup ? Object.entries(asRow(definition[item.value])).map(([key, target]) => { const split = key.indexOf('|'); return { code: key, source: split >= 0 ? key.slice(0, split) : key, secondary: split >= 0 ? key.slice(split + 1) : '', target, enabled: !stopped.has(key) }; }) : asRows(master[item.value]);
|
||
return <section key={item.value}><h3>{item.label} · {rows.length} 条</h3><Table size="small" bordered dataSource={rows} rowKey={(row, index) => String(row.code || index)} pagination={{ pageSize: 15, showSizeChanger: false }} scroll={{ x: 600 }} columns={item.columns.map(column => ({ title: column.label.replace('(可选)', ''), dataIndex: column.key, key: column.key, render: column.key === 'enabled' ? (enabled: unknown) => <Tag>{enabled === false ? '停用' : '启用'}</Tag> : txt }))} locale={{ emptyText: '当前配置未单独维护此类记录' }} /></section>;
|
||
})}</div>;
|
||
}
|