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; 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)[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 = { QUEUED: '等待处理', RUNNING: '正在处理', COMPLETED: '校验完成', FAILED: '处理失败', CANCELLED: '已取消', CANDIDATE_READY: '候选已生成', AUTO_PASSED: '对账通过', CONFIRMED: '差异已确认', REVIEW_REQUIRED: '差异待确认', BLOCKED: '存在阻断问题' }; function SampleTable({ headers, rows }: { headers: string[]; rows: Row[] }) { return ({ ...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; onChange: (value: Record) => void; disabled?: boolean }) { return
{fields.map(field =>
}, { title: '阶段', key: 'stage', render: (_, item) => stageName(item.stage) }, { title: '统计期间', key: 'period', render: (_, item) => `${item.year}年${item.month}月` }, { title: '识别结果', key: 'validation', render: (_, item) => draftReady(item) ? 已识别 : 需核对列或替换对象 }, { title: '操作', key: 'action', render: (_, item) => configured.current.has(item.id) ? 已接收待导入 : }, ]} />} {!workbook ?

选择 Excel 来源文件

可多选文件;系统自动识别阶段和月份,每个文件都可单独调整。

{hasImportCapability && }
: <>
{workbook.sourceFile}{hasImportCapability && }
} {mode === 'REPLACE' &&

业务字段对应 Excel 列

{missing.length ? `还有 ${missing.length} 个必填字段待匹配` : duplicate ? '同一 Excel 列不能重复对应' : '已匹配'}
{ setFieldMap(value); }} />

原表预览

row.values)} /> {missing.length > 0 && item.name).join('、')}`} />}
{mode === 'REPLACE' ? '替换后会按当前规则重算并更新对应报表。' : `${year}年${String(month).padStart(2, '0')}月 · ${stageName(stage)} · 完成后自动刷新报表`}{hasImportCapability && }
} ; } 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 ? {errors.map((item, index) =>
  • {txt(item)}
  • )}} /> : result.complete === true ? : result.complete === false ? : 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(null); const [workflowStatus, setWorkflowStatus] = useState(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([]); 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
    {statusRead.busy ?
    读取当前维护模式正在加载可执行操作
    : workflowStatusError ? void loadWorkflowStatus()}>重试} /> : null}
    ; if (workflowStatus?.simplified === true && workflowStatus.mode === 'TEST' && options) return ; return <>
    日常数据维护

    选择文件,核对后发布

    文件名可以保持原样。黑片或亮片、统计年月和表头均在下一步选择。

    上传 → 选择年月 → 匹配列 → 校验 → 发布
    {optionError && { optionsAttempted.current = true; void loadOptions(); }}>重试} />} {candidateError && { candidatesAttempted.current = true; void loadCandidates(); }}>重试} />} {!options && optionsRead.busy &&
    读取上传选项…
    } {!candidatesLoaded && candidatesRead.busy &&
    读取候选数据…
    } {!canMaintain && } {candidatesLoaded && candidates.length > 0 &&
    待完成的数据已保存的候选可继续校验、对账和发布。
    void readFiles(Array.from(event.target.files || []))} aria-label={mode === 'REPLACE' ? '选择要替换的质量数据Excel文件' : '选择要追加的质量数据Excel文件'} />} {error && { if (!activeRef.current || candidateReadLock.current) return; candidateReadLock.current = true; setBusy(true); loadCandidate(resumeId).catch(reportError).finally(() => { candidateReadLock.current = false; setBusy(false); }); }}>重试读取候选 : runId ? : undefined} />} {published ?

    {purpose === 'WITHDRAW' ? '该来源已从当前查询结果移除' : '当前查询数据已更新'}

    来源原件和本次对账记录均已保留。

    : <> {step === 0 && (mode === 'REBUILD' ?

    使用当前数据所用的全部来源重新计算

    计算使用当前启用的基础数据、对应关系和规则。完成后先生成候选,核对差异后再发布。

    {options.targets.map(item =>
    {stageName(item.stage)}{item.year}年{item.month}月{item.sourceFile}
    )}
    :

    选择要{mode === 'REPLACE' ? '替换' : '追加'}的 Excel 文件

    {mode === 'REPLACE' ? '替换一份已发布文件,其他来源保留。' : '文件会作为独立来源加入所选月份,并与已有来源合并统计。'} 请确保业务记录不与其他文件重叠。

    )} {workbook && step > 0 && step < 4 &&
    {workbook.sourceFile}{stageName(stage)} · {year}年{month}月
    } {wizardFiles.length > 0 && step > 0 && step < 4 && <>
    本次文件 · {wizardFiles.length} 份{mode === 'ADD' && step === 1 && }
    }, { title: '字段匹配', key: 'mapping', render: (_, item) => (options.fields[stage] || []).filter(field => field.required).every(field => item.fieldMap[field.name]) ? 已完成 : 需核对 }, { title: '操作', key: 'action', render: (_, item) => configuredByFile.current.has(item.id) ? 已接收待导入 : }]} />} {step === 1 &&
    {mode === 'REPLACE' ? { setStage(value); setWizardFiles(previous => previous.map(item => ({ ...item, fieldMap: matchFields(options.fields[value] || [], item.workbook.preview.headers) }))); }} /> { if (value) setYear(value); }} /> ({ value, label: value === 'ALL' ? '全部范围' : value }))} onChange={setScopeCode} />}}
    {target &&
    原文件{target.sourceFile} · {target.fileId ? `分批 ${target.fileId.slice(0, 8)}` : '整月文件'}新文件{workbook?.sourceFile}
    } setReason(event.target.value)} />} {step === 2 && workbook && <>
    `${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(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(';') || '一致' }]} /> : }{reconciliation?.status === 'REVIEW_REQUIRED' &&
    {canPublish ? <> setDifferenceReason(event.target.value)} /> setConfirmDifferences(event.target.checked)}>我已核对上方差异,并确认新数据正确 :

    候选已保存,请交由有数据发布权限的同事完成差异确认。

    }
    }{canPublish ?
    setPublishConfirmed(event.target.checked)}>{purpose === 'WITHDRAW' ? '我确认发布此删除候选,从当前查询结果移除已批准的来源' : '我确认将此候选发布为当前查询数据'}{target ? `,替换${target.year}年${target.month}月${stageName(target.stage)}` : ''}{!publishReady && 来源校验和基线对账通过后可发布。}
    : 当前账号没有数据发布权限。可复制处理链接交接,正式查询数据尚未更新。} />}} {issues.length > 0 && <>

    需要处理的来源行

    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' }]} />} } ; } 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(null); const [open, setOpen] = useState(false); const [preview, setPreview] = useState(null); const [sheetName, setSheetName] = useState(''); const [selectedKind, setSelectedKind] = useState(kind === 'masterData' ? 'departments' : 'categoryLookup'); const [keyFormat, setKeyFormat] = useState('SEPARATE_COLUMNS'); const [mode, setMode] = useState<'MERGE' | 'REPLACE'>('MERGE'); const [columns, setColumns] = useState>({}); 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(null); const actionLock = useRef(false); const [preparedDefinition, setPreparedDefinition] = useState(null); const [preparedReleaseId, setPreparedReleaseId] = useState(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 = { 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 <> setOpen(false)} footer={
    {simplified ? '导入后自动保存配置、重算并更新报表。' : result ? '草稿经过校验并启用后,再重新计算和发布数据。' : '导入只创建新草稿,先预览、再确认。'}
    {(!result || simplified && Boolean(error || workflowOperation.error)) && }
    }> {error && } {workflowOperation.error && 重试读取进度 : undefined} />} {workflowOperation.operation && } {result ? <>
    新增{txt(summary.added)}
    更新{txt(summary.updated)}
    停用{txt(summary.disabled)}
    合计{txt(summary.total)}
    {tableSummaries.length > 0 &&
    `${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 && } {!simplified && } : <>
    从 Excel 导入基础数据

    {simplified ? '可自动识别整本基础数据,或选择单个工作表匹配各列;合并更新和整表替换后直接重算并更新报表。' : '可自动识别整本基础数据,或选择单个工作表匹配各列。合并更新和整表替换均先生成草稿。'}

    void readFile(event.target.files?.[0])} />
    {preview &&
    ({ 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); }} />} { setKeyFormat(value); setColumns(autoMatch(sheet?.headers || [], selectedKind, value)); setConfirmed(false); }} />}
    {bundle ?

    将一起导入的工作表

    `${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)[field] || field} ← ${header}`).join(';') }]} />

    {simplified ? '以上名录和对应关系将一起保存并更新报表' : '以上名录和对应关系合并生成同一个草稿'},项目组名录按名称去重。月份等辅助工作表不导入。

    : <>
    {activeColumns.map(column =>
    } {simplified &&

    名称:{name || '新配置'} · 修改内容会在导入后直接应用。

    } {mode === 'REPLACE' && } {!bundle && <>

    导入预览 · {sheet?.rowCount || 0} 行

    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 && setConfirmed(event.target.checked)}>{bundle ? '我已核对上方全部工作表、数据类别和更新方式,确认合并生成一个新草稿。' : '我已核对所选类型、字段对应和更新方式,确认生成新草稿。'}} } } ; } 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
    {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

    {item.label} · {rows.length} 条

    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) => {enabled === false ? '停用' : '启用'} : txt }))} locale={{ emptyText: '当前配置未单独维护此类记录' }} />; })}; }