import { createRequestUuid } from './requestUuid'; import { useDeleteConfirmation } from './useDeleteConfirmation'; import { newMasterDataCode } from './masterDataIdentity'; import { ConfigurationWorkbookActions } from './ConfigurationWorkbookActions'; import { matchRuleConflicts } from './classificationMaintenance'; import { useEffect, useMemo, useState } from 'react'; import { Alert, App, AutoComplete, Button, Checkbox, Form, Input, InputNumber, Modal, Select, Switch, Tag } from 'antd'; import type { ColumnsType } from 'antd/es/table'; import { QualityTable as Table } from './QualityTable'; import { PlusOutlined } from '@ant-design/icons'; import { readableSelectPopup } from './readableSelectPopup'; import './structured-config-editors.css'; export type ConfigDefinition = Record; type MappingKind = 'categoryLookup' | 'projectGroupLookup' | 'departmentLookup' | 'productLookup'; type MasterKind = 'departments' | 'groups' | 'products' | 'projectGroups'; type MappingRow = { key: string; source: string; secondary: string; target: string | null; enabled: boolean }; type MasterRow = { code: string; name: string; enabled: boolean; department?: string; [key: string]: unknown }; type DefinitionProps = { value: ConfigDefinition; onChange: (value: ConfigDefinition) => void }; const mappingKinds: MappingKind[] = ['categoryLookup', 'projectGroupLookup', 'departmentLookup', 'productLookup']; const masterKinds: MasterKind[] = ['departments', 'groups', 'products', 'projectGroups']; const mappingInfo: Record = { categoryLookup: { label: '业务分组对应', source: 'PDT代码', secondary: '销售片区', target: '业务分组', master: 'groups' }, projectGroupLookup: { label: '项目组对应', source: '客户代码', secondary: '业务分组', target: '项目组', master: 'projectGroups' }, departmentLookup: { label: '产业部对应', source: '源事业部', target: '统一产业部', master: 'departments' }, productLookup: { label: '产品对应', source: '源规格(大写)', target: '统一产品', master: 'products' }, }; const masterLabels: Record = { departments: '产业部', groups: '业务分组', products: '产品', projectGroups: '项目组' }; function objectValue(value: unknown): Record { return value && typeof value === 'object' && !Array.isArray(value) ? value as Record : {}; } const SYSTEM_DEFINITION_METADATA_KEYS = new Set([ 'schemaversion', 'ruleversion', 'ruleversionid', 'engineversion', 'formulaversion', 'parserversion', 'mappingversion', 'mappingversionid', 'basemappingversionid', 'versionid', 'versionno', 'releaseid', 'currentreleaseid', 'revisionid', 'sourcerevisionid', 'rowversion', 'masterdata', ]); function isSystemDefinitionMetadataField(key: string): boolean { return SYSTEM_DEFINITION_METADATA_KEYS.has(key.replace(/[^a-z0-9]/gi, '').toLowerCase()); } function withoutSystemVersionFields(value: unknown): unknown { if (!value || typeof value !== 'object' || Array.isArray(value)) return value; return Object.fromEntries(Object.entries(value as Record) .filter(([key]) => !isSystemDefinitionMetadataField(key))); } function preserveSystemVersionFields(next: unknown, current: unknown): unknown { if (!next || typeof next !== 'object' || Array.isArray(next)) return next; const currentObject = objectValue(current); const result: Record = {}; for (const [key, value] of Object.entries(next as Record)) { if (!isSystemDefinitionMetadataField(key)) result[key] = value; } for (const [key, value] of Object.entries(currentObject)) if (isSystemDefinitionMetadataField(key)) result[key] = value; return result; } function disabledKeys(value: ConfigDefinition, kind: MappingKind): string[] { const keys = objectValue(value.disabledMappings)[kind]; return Array.isArray(keys) ? keys.map(String) : []; } function mappingRows(value: ConfigDefinition, kind: MappingKind): MappingRow[] { const disabled = new Set(disabledKeys(value, kind)); return Object.entries(objectValue(value[kind])).map(([key, target]) => { const split = mappingInfo[kind].secondary ? key.indexOf('|') : -1; return { key, source: split < 0 ? key : key.slice(0, split), secondary: split < 0 ? '' : key.slice(split + 1), target: target === null ? null : String(target), enabled: !disabled.has(key) }; }); } function masterRows(value: ConfigDefinition, kind: MasterKind): MasterRow[] { const rows = objectValue(value.masterData)[kind]; return Array.isArray(rows) ? rows.map(item => { const row = objectValue(item); return { ...row, code: String(row.code ?? ''), name: String(row.name ?? ''), enabled: row.enabled !== false, ...(Object.hasOwn(row, 'department') ? { department: String(row.department ?? '') } : {}) }; }) : []; } function setMasterRows(value: ConfigDefinition, kind: MasterKind, rows: MasterRow[]): ConfigDefinition { return { ...value, masterData: { ...objectValue(value.masterData), [kind]: rows } }; } function setMappingRows(value: ConfigDefinition, kind: MappingKind, rows: MappingRow[]): ConfigDefinition { return { ...value, [kind]: Object.fromEntries(rows.map(row => [row.key, row.target])), disabledMappings: { ...objectValue(value.disabledMappings), [kind]: rows.filter(row => !row.enabled).map(row => row.key) } }; } export function parseConfigDelimited(text: string): string[][] { const source = text.replace(/^\uFEFF/, '').replace(/^[\r\n]+|[\r\n]+$/g, ''); if (!source.trim()) throw new Error('请粘贴需要导入的内容'); const firstLine = source.split(/\r?\n/, 1)[0]; let headerQuoted = false; let hasTab = false; for (let index = 0; index < firstLine.length; index++) { if (firstLine[index] === '"') { if (headerQuoted && firstLine[index + 1] === '"') index++; else headerQuoted = !headerQuoted; } else if (!headerQuoted && firstLine[index] === '\t') hasTab = true; } const delimiter = hasTab ? '\t' : ','; const result: string[][] = []; let row: string[] = []; let cell = ''; let quoted = false; let closedQuote = false; for (let index = 0; index < source.length; index++) { const char = source[index]; if (char === '"') { if (quoted && source[index + 1] === '"') { cell += '"'; index++; } else if (!quoted && (cell.trim() || closedQuote)) throw new Error('引号位置有误,请检查 CSV 格式'); else { quoted = !quoted; if (!quoted) closedQuote = true; } } else if (!quoted && char === delimiter) { row.push(cell.trim()); cell = ''; closedQuote = false; } else if (!quoted && (char === '\n' || char === '\r')) { row.push(cell.trim()); if (row.some(Boolean)) result.push(row); row = []; cell = ''; closedQuote = false; if (char === '\r' && source[index + 1] === '\n') index++; } else { if (!quoted && closedQuote && char.trim()) throw new Error('闭合引号后存在多余内容,请检查 CSV 格式'); cell += char; } } if (quoted) throw new Error('CSV 引号未闭合'); row.push(cell.trim()); if (row.some(Boolean)) result.push(row); return result; } function parseEnabled(value: string | undefined, line: number): boolean | undefined { if (value === undefined || value === '') return undefined; if (['true', '1', '是', '启用'].includes(value.toLowerCase())) return true; if (['false', '0', '否', '停用'].includes(value.toLowerCase())) return false; throw new Error(`第 ${line} 行启用状态无效,请填写 true/false 或 启用/停用`); } export function validateStructuredMappingDefinition(value: ConfigDefinition, _groupDepartments?: Record): string[] { const errors: string[] = []; for (const kind of masterKinds) { const codes = new Set(); const names = new Set(); masterRows(value, kind).forEach((row, index) => { const prefix = `${masterLabels[kind]}名录第 ${index + 1} 行`; if (!row.code.trim() || !row.name.trim()) errors.push(`${prefix}:记录标识缺失或名称未填写`); if (row.code.length > 100 || row.name.length > 190) errors.push(`${prefix}:记录标识异常或名称超过190字`); if (codes.has(row.code)) errors.push(`${prefix}:记录标识重复,请刷新后重试`); if (names.has(row.name)) errors.push(`${prefix}:名称“${row.name}”重复`); codes.add(row.code); names.add(row.name); }); } const enabledDepartments = masterRows(value, 'departments'); for (const group of masterRows(value, 'groups')) { const department = Object.hasOwn(group, 'department') ? String(group.department ?? '') : ''; if (!department) continue; const parent = enabledDepartments.find(row => row.name === department); if (!parent) errors.push(`业务分组名录 ${group.name}:所属产业部“${department}”不在产业部名录中`); else if (!parent.enabled) errors.push(`业务分组名录 ${group.name}:所属产业部“${department}”已停用,请调整或清空所属产业部`); } for (const kind of mappingKinds) { const catalog = masterRows(value, mappingInfo[kind].master); if (!Object.hasOwn(objectValue(value.masterData), mappingInfo[kind].master)) continue; for (const row of mappingRows(value, kind)) { if (!row.enabled || row.target === null) continue; const target = catalog.find(item => item.name === row.target); if (!target) errors.push(`${mappingInfo[kind].label} ${row.key}:目标“${row.target}”不在${masterLabels[mappingInfo[kind].master]}名录中`); else if (!target.enabled) errors.push(`${mappingInfo[kind].label} ${row.key}:目标“${row.target}”已停用,请调整或停用此对应关系`); } } return errors; } function BatchImport({ open, title, columns, existing, writeTarget = '草稿', onCancel, onImport }: { open: boolean; title: string; columns: string[]; existing: boolean; writeTarget?: string; onCancel: () => void; onImport: (rows: string[][], replace: boolean) => void }) { const [text, setText] = useState(''); const [replace, setReplace] = useState(false); const [error, setError] = useState(''); useEffect(() => { if (open) { setText(''); setReplace(false); setError(''); } }, [open]); return { try { const rows = parseConfigDelimited(text); const first = rows[0]?.map(item => item.replace(/\s/g, '').toLowerCase()); if (first?.[0] === columns[0].replace(/\s/g, '').toLowerCase() || ['source', 'code', 'pdt代码'].includes(first?.[0] || '')) rows.shift(); if (!rows.length) throw new Error('表头下没有可导入的记录'); onImport(rows, replace); setError(''); } catch (value) { setError(value instanceof Error ? value.message : '导入内容有误'); } }}>

粘贴 CSV 或从表格复制的内容,列顺序为:{columns.join('、')}。首行可含表头;启用列可填写 true/false。

setText(event.target.value)} rows={10} spellCheck={false} aria-label={`${title}批量导入内容`} placeholder={columns.join(',')} /> {existing && setReplace(event.target.checked)}>按相同名称或源条件更新已有记录(不勾选时重复即停止导入)} {error && }
; } export function MappingDefinitionEditor({ value, onChange, simplified = false, readOnly = false }: DefinitionProps & { simplified?: boolean; readOnly?: boolean }) { const confirmDelete = useDeleteConfirmation(); const { message } = App.useApp(); const [kind, setKind] = useState('categoryLookup'); const [search, setSearch] = useState(''); const [status, setStatus] = useState('all'); const [editing, setEditing] = useState(null); const [newRow, setNewRow] = useState(false); const [importing, setImporting] = useState(false); const [editError, setEditError] = useState(''); const [form] = Form.useForm<{ source: string; secondary: string; target: string; unassigned: boolean; enabled: boolean }>(); const info = mappingInfo[kind]; const rows = useMemo(() => mappingRows(value, kind), [value, kind]); const visibleRows = rows.filter(row => `${row.source} ${row.secondary} ${row.target ?? ''}`.toLowerCase().includes(search.toLowerCase()) && (status === 'all' || row.enabled === (status === 'enabled'))); const targetNames = Array.from(new Set([...masterRows(value, info.master).map(row => row.name), ...rows.map(row => row.target).filter((target): target is string => target !== null)])); const openRow = (row?: MappingRow) => { setEditing(row ?? { key: '', source: '', secondary: '', target: '', enabled: true }); setNewRow(!row); setEditError(''); form.setFieldsValue({ source: row?.source ?? '', secondary: row?.secondary ?? '', target: row?.target ?? '', unassigned: row?.target === null, enabled: row?.enabled ?? true }); }; const columns: ColumnsType = [ { title: info.source, dataIndex: 'source', key: 'source', width: 190 }, ...(info.secondary ? [{ title: info.secondary, dataIndex: 'secondary', key: 'secondary', width: 180 }] : []), { title: info.target, dataIndex: 'target', key: 'target', width: 220, render: target => target === null ? 未配置 : target }, { title: '状态', dataIndex: 'enabled', key: 'enabled', width: 100, render: enabled => {enabled ? '启用' : '停用'} }, ...(!readOnly ? [{ title: '操作', key: 'actions', width: 205, render: (_: unknown, row: MappingRow) => }] : []), ]; const headers = [info.source, ...(info.secondary ? [info.secondary] : []), info.target, '启用']; return

{simplified ? '新增的对应目标会自动补入对应名录;全部变更由页面主按钮一次保存并更新报表。' : '停用保留原对应值;变更经保存、校验并启用后用于新的数据构建。'}

setEditing(null)} onOk={() => { void form.validateFields().then(fields => { const source = kind === 'productLookup' ? fields.source.trim().toUpperCase() : fields.source.trim(); const secondary = fields.secondary?.trim() ?? ''; const key = info.secondary ? `${source}|${secondary}` : source; if (rows.some(row => row.key === key && (newRow || row.key !== editing?.key))) { setEditError('相同源条件已有对应关系,请编辑已有行'); return; } const target = fields.unassigned ? null : String(fields.target ?? '').trim(); if (target === '') { setEditError('请填写目标名称,或勾选“明确不设归属”'); return; } const updated = { key, source, secondary, target, enabled: fields.enabled }; onChange(setMappingRows(value, kind, newRow ? [...rows, updated] : rows.map(row => row.key === editing?.key ? updated : row))); setEditing(null); }).catch(() => undefined); }}>
!info.secondary || !String(text ?? '').includes('|') ? Promise.resolve() : Promise.reject(new Error('请分别填写两个源条件')) }]}>{info.secondary && !String(text ?? '').includes('|') ? Promise.resolve() : Promise.reject(new Error('源条件不能包含 |')) }]}>}
before.unassigned !== after.unassigned}>{({ getFieldValue }) => { const item = masterRows(value, info.master).find(row => row.name === name); return { value: name, label: `${name}${item?.enabled === false ? '(已停用)' : ''}` }; })} filterOption={(input, option) => String(option?.label || option?.value || '').toLowerCase().includes(input.toLowerCase())} placeholder="选择或输入目标名称" />} 明确不设归属(保留空值) {editError && }
0} writeTarget={simplified ? '当前配置' : '草稿'} onCancel={() => setImporting(false)} onImport={(input, replace) => { const incoming: MappingRow[] = []; const keys = new Set(); input.forEach((cells, index) => { const expected = info.secondary ? 4 : 3; if (cells.length < expected - 1 || cells.length > expected) throw new Error(`第 ${index + 1} 行应为 ${expected - 1} 或 ${expected} 列`); const source = kind === 'productLookup' ? cells[0].toUpperCase() : cells[0]; const secondary = info.secondary ? cells[1] : ''; if (!source || (info.secondary && !secondary)) throw new Error(`第 ${index + 1} 行来源条件不完整`); if (info.secondary && (source.includes('|') || secondary.includes('|'))) throw new Error(`第 ${index + 1} 行请分别填写两个源条件`); const key = info.secondary ? `${source}|${secondary}` : source; if (keys.has(key)) throw new Error(`第 ${index + 1} 行与导入内容重复:${key}`); keys.add(key); const previous = rows.find(row => row.key === key); if (previous && !replace) throw new Error(`第 ${index + 1} 行已存在:${key}`); incoming.push({ key, source, secondary, target: cells[info.secondary ? 2 : 1] || null, enabled: parseEnabled(cells[expected - 1], index + 1) ?? previous?.enabled ?? true }); }); const changed = new Set(incoming.map(row => row.key)); onChange(setMappingRows(value, kind, [...rows.filter(row => !changed.has(row.key)), ...incoming])); setImporting(false); message.success(simplified ? `已将 ${incoming.length} 条对应关系加入当前编辑` : `已将 ${incoming.length} 条对应关系写入草稿,请保存后校验`); }} /> ; } type MatchCondition = { field: string; operator: string; value?: string }; type MatchRule = { onlyUnclassified?:boolean; id?: string; name: string; enabled: boolean; priority: number; stage: string; conditions: MatchCondition[]; target: string; value: string }; type MatchMetadata = { fields?: unknown[]; operators?: unknown[]; targets?: unknown[]; stages?: unknown[]; defaultRules?: unknown[]; limits?: Record }; const defaultMatchRules: MatchRule[] = [{ id: 'default-vcm-group', name: '成品规格含VCM归入工业电机-VCM', enabled: true, priority: 100, stage: 'all', conditions: [{ field: '成品规格', operator: 'CONTAINS', value: 'VCM' }], target: 'group', value: '工业电机-VCM' }]; const plainObject = (value: unknown) => value && typeof value === 'object' && !Array.isArray(value) ? value as Record : {}; type MatchOption = { value: string; label: string }; const metadataOptions = (value: unknown, fallback: MatchOption[]): MatchOption[] => Array.isArray(value) && value.length ? value.map(item => { const row = plainObject(item); return { value: String(row.id || row.value || ''), label: String(row.label || row.name || row.id || row.value || '') }; }).filter(item => item.value) : fallback; export function MatchRulesDefinitionEditor({ value, onChange, metadata, readOnly = false }: DefinitionProps & { metadata?: MatchMetadata | null; readOnly?: boolean }) { const confirmDelete = useDeleteConfirmation(); const [editing, setEditing] = useState(null); const [search,setSearch]=useState(''); const [error, setError] = useState(''); const fields = metadataOptions(metadata?.fields, [ { value: 'PDT代码', label: 'PDT代码' }, { value: '销售片区', label: '销售片区' }, { value: '客户代码', label: '客户代码' }, { value: '成品规格', label: '成品规格' }, { value: '@department', label: '已算产业部 @department' }, { value: '@group', label: '已算业务分组 @group' }, { value: '@product', label: '已算产品 @product' }, { value: '@projectGroup', label: '已算项目组 @projectGroup' }, ]); const operators = metadataOptions(metadata?.operators, [ { value: 'EQUALS', label: '等于' }, { value: 'NOT_EQUALS', label: '不等于' }, { value: 'CONTAINS', label: '包含' }, { value: 'STARTS_WITH', label: '开头是' }, { value: 'IS_BLANK', label: '为空' }, { value: 'IS_NOT_BLANK', label: '不为空' }, ]); const targets = metadataOptions(metadata?.targets, [ { value: 'department', label: '产业部' }, { value: 'group', label: '业务分组' }, { value: 'product', label: '产品' }, { value: 'projectGroup', label: '项目组' }, ]); const stages = metadataOptions(metadata?.stages, [ { value: 'all', label: '黑片和亮片' }, { value: 'black', label: '黑片' }, { value: 'bright', label: '亮片' }, ]); const sourceRules = Array.isArray(value.matchRules) ? value.matchRules : (metadata?.defaultRules ?? defaultMatchRules); const rules = sourceRules.map((item, index) => { const row = plainObject(item); return { ...(row.onlyUnclassified===undefined?{}:{onlyUnclassified:row.onlyUnclassified===true}), id: String(row.id || `match-${index + 1}`), name: String(row.name || `条件规则 ${index + 1}`), enabled: row.enabled !== false, priority: Number(row.priority ?? (index + 1) * 100), stage: String(row.stage || 'all'), conditions: Array.isArray(row.conditions) ? row.conditions.map(condition => { const conditionRow = plainObject(condition); return { field: String(conditionRow.field || ''), operator: String(conditionRow.operator || 'EQUALS'), ...(conditionRow.value === undefined ? {} : { value: String(conditionRow.value) }) }; }) : [], target: String(row.target || 'group'), value: String(row.value || '') } as MatchRule; }); const labelFor = (options: MatchOption[], id: string) => options.find(option => option.value === id)?.label || id; const conditionText = (condition: MatchCondition) => `${labelFor(fields, condition.field)} ${labelFor(operators, condition.operator)}${['IS_BLANK', 'IS_NOT_BLANK'].includes(condition.operator) ? '' : ` ${condition.value || '…'}`}`; const readableRule = (rule: MatchRule) => `${rule.onlyUnclassified?'仅未分类:':''}当 ${rule.conditions.map(conditionText).join(' 且 ') || '(未设置条件)'} → ${labelFor(targets, rule.target)}:${rule.value || '(未填写)'}`; const commit = (next: MatchRule[]) => onChange({ ...value, matchRules: next.map((rule, index) => ({ ...rule, id: rule.id || `match-${index + 1}` })) }); const open = (rule?: MatchRule) => { setError(''); setEditing(rule ? { ...rule, conditions: rule.conditions.map(condition => ({ ...condition })) } : { name: '', enabled: true, priority: Math.min(10000, (rules.length + 1) * 100), stage: 'all', conditions: [{ field: '', operator: 'EQUALS', value: '' }], target: 'group', value: '' }); }; const operatorDescription = (operator: string) => ['IS_BLANK', 'IS_NOT_BLANK'].includes(operator) ? '' : operator; return
setSearch(event.target.value)}/>{rules.length} 条规则
{!readOnly && }
(rule.name+' '+readableRule(rule)).toLowerCase().includes(search.toLowerCase()))} pagination={{ pageSize: 15, showSizeChanger: false }} scroll={{ x: 1080 }} columns={[ { title: '顺序', dataIndex: 'priority', width: 84, align: 'right', sorter: (a, b) => a.priority - b.priority }, { title: '规则名称', dataIndex: 'name', width: 220 }, { title: '匹配条件', width: 410, render: (_, row) => {readableRule(row)} }, { title: '阶段', dataIndex: 'stage', width: 104, render: stage => labelFor(stages, String(stage)) }, { title: '状态', dataIndex: 'enabled', width: 84, render: enabled => {enabled ? '启用' : '停用'} }, ...(!readOnly ? [{ title: '操作', width: 150, render: (_: unknown, row: MatchRule) => }] : []), ]} locale={{ emptyText: '还没有条件匹配规则' }} /> setEditing(null)} onOk={() => { if (!editing) return; const next = { ...editing, name: editing.name.trim(), value: editing.value.trim(), conditions: editing.conditions.map(condition => ({ field: condition.field.trim(), operator: condition.operator, value: ['IS_BLANK', 'IS_NOT_BLANK'].includes(condition.operator) ? '' : String(condition.value || '').trim() })) }; if (!next.name) { setError('请填写规则名称'); return; } if (!next.conditions.length || next.conditions.some(condition => !condition.field || (!['IS_BLANK', 'IS_NOT_BLANK'].includes(condition.operator) && !condition.value))) { setError('请补全每条条件的字段和判断值'); return; } if (!next.value) { setError('请填写匹配结果'); return; } const updated=editing.id ? rules.map(rule => rule.id === editing.id ? next : rule) : [...rules, { ...next, id: `match-${createRequestUuid()}` }]; const conflicts=matchRuleConflicts(updated);if(conflicts.length){setError(conflicts.join(';'));return;} commit(updated); setEditing(null); }}> {editing &&
setEditing({ ...editing, name: event.target.value })} /> setEditing({ ...editing, priority: Number(priority ?? 0) })} />
String(index)} pagination={false} dataSource={editing.conditions} columns={[ { title: '字段', width: 250, render: (_, condition, index) => String(option?.label || '').toLowerCase().includes(input.toLowerCase())} placeholder="选择或输入字段" onChange={field => setEditing({ ...editing, conditions: editing.conditions.map((row, rowIndex) => rowIndex === index ? { ...row, field } : row) })} /> }, { title: '判断方式', width: 180, render: (_, condition, index) => setEditing({ ...editing, conditions: editing.conditions.map((row, rowIndex) => rowIndex === index ? { ...row, value: event.target.value } : row) })} /> }, { title: '', width: 82, render: (_, __, index) => }, ]} /> rule.id===editing.id && rule.onlyUnclassified===true)} checkedChildren="仅未分类" unCheckedChildren="全部匹配行" onChange={onlyUnclassified=>setEditing({...editing,onlyUnclassified})}/>
setEditing({ ...editing, value: event.target.value })} placeholder="例如:工业电机-VCM" />
{error && } } ; } export function MasterDataDefinitionEditor({ value, onChange, publishedNames, simplified = false, readOnly = false }: DefinitionProps & { publishedNames?: Partial> & { groupDepartments?: Record }; simplified?: boolean; readOnly?: boolean }) { const confirmDelete = useDeleteConfirmation(); const { message } = App.useApp(); const [kind, setKind] = useState('departments'); const [search, setSearch] = useState(''); const [editing, setEditing] = useState(null); const [originalCode, setOriginalCode] = useState(null); const [error, setError] = useState(''); const [importing, setImporting] = useState(false); const [departmentAtOpen, setDepartmentAtOpen] = useState<{ value: string } | null>(null); const [form] = Form.useForm(); const rows = masterRows(value, kind); const label = masterLabels[kind]; const departmentFor = (row: MasterRow) => Object.hasOwn(row, 'department') ? String(row.department ?? '') : String(publishedNames?.groupDepartments?.[row.name] ?? ''); const openRow = (row?: MasterRow) => { const initial = row ?? { code: '', name: '', enabled: true }; const department = kind === 'groups' ? row ? departmentFor(row) : '' : null; setEditing(initial); setOriginalCode(row?.code ?? null); setDepartmentAtOpen(department === null ? null : { value: department }); setError(''); form.setFieldsValue({ ...initial, ...(kind === 'groups' ? { department: department ?? '' } : {}) }); }; const loadExisting = () => { let next = { ...value }; let count = 0; for (const masterKind of masterKinds) { const existing = masterRows(next, masterKind); const names = new Set(existing.map(row => row.name)); const codes = new Set(existing.map(row => row.code)); const added: MasterRow[] = []; const candidates = [...(publishedNames?.[masterKind] ?? []), ...mappingKinds.filter(item => mappingInfo[item].master === masterKind).flatMap(mappingKind => mappingRows(value, mappingKind).map(row => row.target))]; for (const name of candidates) { if (name === null || !name || names.has(name)) continue; const code = newMasterDataCode(codes); added.push({ code, name, enabled: true }); names.add(name); codes.add(code); count++; } next = setMasterRows(next, masterKind, [...existing, ...added]); } onChange(next); message.success(count ? `已从当前配置及对应值载入 ${count} 个名称,请核对后保存` : '现有名称均已在名录中'); }; const departments = masterRows(value, 'departments'); const columns: ColumnsType = [{ title: '名称', dataIndex: 'name', key: 'name', width: 300 }, ...(kind === 'groups' ? [{ title: '所属产业部', key: 'department', width: 220, render: (_: unknown, row: MasterRow) => { const department = departmentFor(row); const parent = departments.find(item => item.name === department); return department ? `${department}${parent && !parent.enabled ? '(已停用)' : ''}` : 未设置; } }] : []), { title: '状态', dataIndex: 'enabled', key: 'enabled', width: 100, render: enabled => {enabled ? '启用' : '停用'} }, ...(!readOnly ? [{ title: '操作', key: 'actions', width: 205, render: (_: unknown, row: MasterRow) => }] : [])]; const csvHeaders = kind === 'groups' ? ['名称', '启用', '所属产业部'] : ['名称', '启用']; const departmentValue = Form.useWatch('department', form); const selectedDepartment = typeof departmentValue === 'string' ? departmentValue : ''; const departmentOptions = departments.filter(row => row.enabled || row.name === selectedDepartment).map(row => ({ value: row.name, label: `${row.name}${row.enabled ? '' : '(已停用)'}`, disabled: !row.enabled })); if (selectedDepartment && !departmentOptions.some(option => option.value === selectedDepartment)) departmentOptions.push({ value: selectedDepartment, label: `${selectedDepartment}(未在产业部名录中)`, disabled: true }); const visibleRows = rows.filter(row => `${row.name} ${kind === 'groups' ? departmentFor(row) : ''}`.toLowerCase().includes(search.toLowerCase())); return
{!simplified &&

维护产业部、业务分组、产品及项目组的统一名录。名称必须唯一。

{!simplified && }
}

停用项保留在名录中;启用中的对应关系如引用停用名称,校验将指出具体位置。已有分析记录保留生成时使用的名称。

setEditing(null)} onOk={() => { void form.validateFields().then(fields => { const existing = originalCode === null ? undefined : rows.find(item => item.code === originalCode); const department = String(fields.department ?? '').trim(); const persistDepartment = kind === 'groups' && (!existing || Object.hasOwn(existing, 'department') || department !== (departmentAtOpen?.value ?? '') || (!!department && fields.name.trim() !== existing.name)); const row: MasterRow = { ...existing, code: existing?.code || newMasterDataCode(rows.map(item => item.code)), name: fields.name.trim(), enabled: fields.enabled, ...(persistDepartment ? { department } : {}) }; if (rows.some(item => item.code !== originalCode && (item.code === row.code || item.name === row.name))) { setError('名称已存在,请编辑已有行'); return; } onChange(setMasterRows(value, kind, originalCode === null ? [...rows, row] : rows.map(item => item.code === originalCode ? row : item))); setEditing(null); }).catch(() => undefined); }}>
{kind === 'groups' &&