Files
quality_analyse/web/src/StructuredConfigEditors.tsx
T

356 lines
44 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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<string, unknown>;
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<MappingKind, { label: string; source: string; secondary?: string; target: string; master: MasterKind }> = {
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<MasterKind, string> = { departments: '产业部', groups: '业务分组', products: '产品', projectGroups: '项目组' };
function objectValue(value: unknown): Record<string, unknown> { return value && typeof value === 'object' && !Array.isArray(value) ? value as Record<string, unknown> : {}; }
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<string, unknown>)
.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<string, unknown> = {};
for (const [key, value] of Object.entries(next as Record<string, unknown>)) {
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, string | null>): string[] {
const errors: string[] = [];
for (const kind of masterKinds) {
const codes = new Set<string>(); const names = new Set<string>();
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 <Modal className="management-modal structured-config-modal" open={open} title={`批量导入${title}`} width={760} okText={`检查并写入${writeTarget}`} onCancel={onCancel} onOk={() => {
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 : '导入内容有误'); }
}}>
<p>粘贴 CSV 或从表格复制的内容,列顺序为:{columns.join('、')}。首行可含表头;启用列可填写 true/false。</p>
<Input.TextArea value={text} onChange={event => setText(event.target.value)} rows={10} spellCheck={false} aria-label={`${title}批量导入内容`} placeholder={columns.join(',')} />
{existing && <Checkbox checked={replace} onChange={event => setReplace(event.target.checked)}>按相同名称或源条件更新已有记录(不勾选时重复即停止导入)</Checkbox>}
{error && <Alert showIcon type="error" message="导入未写入" description={error} />}
</Modal>;
}
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<MappingKind>('categoryLookup'); const [search, setSearch] = useState(''); const [status, setStatus] = useState('all');
const [editing, setEditing] = useState<MappingRow | null>(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<MappingRow> = [
{ 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 ? <span className="structured-config-muted">未配置</span> : target },
{ title: '状态', dataIndex: 'enabled', key: 'enabled', width: 100, render: enabled => <Tag color={enabled ? 'green' : 'default'}>{enabled ? '启用' : '停用'}</Tag> },
...(!readOnly ? [{ title: '操作', key: 'actions', width: 205, render: (_: unknown, row: MappingRow) => <span className="task-actions"><Button type="link" onClick={() => openRow(row)}>编辑</Button><Button type="link" onClick={() => onChange(setMappingRows(value, kind, rows.map(item => item.key === row.key ? { ...item, enabled: !item.enabled } : item)))}>{row.enabled ? '停用' : '恢复'}</Button><Button type="link" danger onClick={() => confirmDelete({title:`删除这条${info.label}?`,description:`来源“${row.source}”对应“${row.target}”。删除后需保存并更新报表才生效。`,onConfirm:()=>onChange(setMappingRows(value, kind, rows.filter(item => item.key !== row.key)))})}>删除</Button></span> }] : []),
];
const headers = [info.source, ...(info.secondary ? [info.secondary] : []), info.target, '启用'];
return <div className="structured-config-editor">
<div className="structured-config-toolbar"><label className="config-type-filter"><span>对应类型</span><Select {...readableSelectPopup} aria-label="对应类型" value={kind} options={mappingKinds.map(key=>({value:key,label:mappingInfo[key].label}))} onChange={key=>{setKind(key);setSearch('');}} /></label><Input.Search value={search} onChange={event => setSearch(event.target.value)} placeholder="查找来源或目标" allowClear aria-label="查找对应关系" /><Select value={status} onChange={setStatus} aria-label="对应关系状态" options={[{ value: 'all', label: '全部状态' }, { value: 'enabled', label: '启用中' }, { value: 'disabled', label: '已停用' }]} /><span>{rows.length} 条 · 启用 {rows.filter(row => row.enabled).length}</span><div className="structured-config-actions"><ConfigurationWorkbookActions value={value} onChange={onChange} scope={kind} label={info.label} readOnly={readOnly} validate={validateStructuredMappingDefinition} onPaste={()=>setImporting(true)} />{!readOnly && <><Button type="primary" icon={<PlusOutlined />} onClick={() => openRow()}>新增对应</Button></>}</div></div>
<Table size="small" bordered rowKey="key" columns={columns} dataSource={visibleRows} pagination={{ pageSize: 15, showSizeChanger: false }} scroll={{ x: info.secondary ? 860 : 680 }} locale={{ emptyText: '没有符合条件的对应关系' }} />
<p className="structured-config-note">{simplified ? '新增的对应目标会自动补入对应名录;全部变更由页面主按钮一次保存并更新报表。' : '停用保留原对应值;变更经保存、校验并启用后用于新的数据构建。'}</p>
<Modal className="management-modal structured-config-modal" open={Boolean(editing)} title={`${newRow ? '新增' : '编辑'}${info.label}`} width={560} okText={simplified ? '保存此行' : '写入草稿'} onCancel={() => 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); }}>
<Form form={form} layout="vertical"><div className="structured-config-form-grid"><Form.Item name="source" label={info.source} rules={[{ required: true, whitespace: true, message: `请填写${info.source}` }, { validator: (_, text) => !info.secondary || !String(text ?? '').includes('|') ? Promise.resolve() : Promise.reject(new Error('请分别填写两个源条件')) }]}><Input /></Form.Item>{info.secondary && <Form.Item name="secondary" label={info.secondary} rules={[{ required: true, whitespace: true, message: `请填写${info.secondary}` }, { validator: (_, text) => !String(text ?? '').includes('|') ? Promise.resolve() : Promise.reject(new Error('源条件不能包含 |')) }]}><Input /></Form.Item>}</div>
<Form.Item noStyle shouldUpdate={(before, after) => before.unassigned !== after.unassigned}>{({ getFieldValue }) => <Form.Item name="target" label={info.target}><AutoComplete disabled={getFieldValue('unassigned')} options={targetNames.map(name => { 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="选择或输入目标名称" /></Form.Item>}</Form.Item>
<Form.Item name="unassigned" valuePropName="checked"><Checkbox>明确不设归属(保留空值)</Checkbox></Form.Item><Form.Item name="enabled" label="状态" valuePropName="checked"><Switch checkedChildren="启用" unCheckedChildren="停用" /></Form.Item></Form>
{editError && <Alert showIcon type="error" message={editError} />}
</Modal>
<BatchImport open={importing} title={info.label} columns={headers} existing={rows.length > 0} writeTarget={simplified ? '当前配置' : '草稿'} onCancel={() => setImporting(false)} onImport={(input, replace) => {
const incoming: MappingRow[] = []; const keys = new Set<string>();
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} 条对应关系写入草稿,请保存后校验`);
}} />
</div>;
}
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<string, unknown> };
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<string, unknown> : {};
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<MatchRule | null>(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 <div className="structured-config-editor structured-match-editor">
<div className="structured-config-toolbar"><Input.Search aria-label="搜索条件匹配规则" placeholder="规则名称、条件或目标分类" value={search} allowClear onChange={event=>setSearch(event.target.value)}/><span>{rules.length} 条规则</span><div className="structured-config-actions"><ConfigurationWorkbookActions value={value} onChange={onChange} scope="matchRules" label="条件匹配规则" defaults={metadata?.defaultRules??defaultMatchRules} readOnly={readOnly} />{!readOnly && <Button type="primary" icon={<PlusOutlined />} onClick={() => open()}>新增匹配规则</Button>}</div></div>
<Table size="small" bordered rowKey="id" dataSource={rules.filter(rule=>(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) => <span className="structured-match-readable">{readableRule(row)}</span> },
{ title: '阶段', dataIndex: 'stage', width: 104, render: stage => labelFor(stages, String(stage)) },
{ title: '状态', dataIndex: 'enabled', width: 84, render: enabled => <Tag color={enabled ? 'green' : 'default'}>{enabled ? '启用' : '停用'}</Tag> },
...(!readOnly ? [{ title: '操作', width: 150, render: (_: unknown, row: MatchRule) => <span className="task-actions"><Button type="link" onClick={() => open(row)}>编辑</Button><Button type="link" onClick={() => commit(rules.map(item => item.id === row.id ? { ...item, enabled: !item.enabled } : item))}>{row.enabled ? '停用' : '启用'}</Button><Button type="link" danger onClick={() => confirmDelete({title:`删除匹配规则“${row.name || "未命名规则"}”?`,description:"将移除这条规则及其匹配条件,保存并更新报表后生效。",onConfirm:()=>commit(rules.filter(item => item.id !== row.id))})}>删除</Button></span> }] : []),
]} locale={{ emptyText: '还没有条件匹配规则' }} />
<Modal className="management-modal structured-config-modal" open={Boolean(editing)} title={editing?.id ? '编辑条件匹配规则' : '新增条件匹配规则'} width={860} okText="保存规则" onCancel={() => 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 && <Form layout="vertical"><div className="structured-config-form-grid"><Form.Item label="规则名称" required><Input value={editing.name} maxLength={160} onChange={event => setEditing({ ...editing, name: event.target.value })} /></Form.Item><Form.Item label="优先级" required><InputNumber min={-10000} max={10000} style={{ width: '100%' }} value={editing.priority} onChange={priority => setEditing({ ...editing, priority: Number(priority ?? 0) })} /></Form.Item><Form.Item label="阶段"><Select value={editing.stage} options={stages} onChange={stage => setEditing({ ...editing, stage })} /></Form.Item><Form.Item label="状态"><Switch checked={editing.enabled} checkedChildren="启用" unCheckedChildren="停用" onChange={enabled => setEditing({ ...editing, enabled })} /></Form.Item></div>
<div className="structured-config-toolbar"><strong>命中条件(条件之间按“且”组合)</strong><Button icon={<PlusOutlined />} onClick={() => setEditing({ ...editing, conditions: [...editing.conditions, { field: '', operator: 'EQUALS', value: '' }] })}>新增条件</Button></div>
<Table size="small" bordered rowKey={(_, index) => String(index)} pagination={false} dataSource={editing.conditions} columns={[
{ title: '字段', width: 250, render: (_, condition, index) => <AutoComplete value={condition.field} options={fields} style={{ width: '100%' }} filterOption={(input, option) => 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) => <Select {...readableSelectPopup} value={condition.operator} options={operators} style={{ width: '100%' }} onChange={operator => setEditing({ ...editing, conditions: editing.conditions.map((row, rowIndex) => rowIndex === index ? { ...row, operator, ...(operatorDescription(operator) ? {} : { value: undefined }) } : row) })} /> },
{ title: '判断值', render: (_, condition, index) => ['IS_BLANK', 'IS_NOT_BLANK'].includes(condition.operator) ? <span className="structured-config-muted">无需填写</span> : <Input value={condition.value} onChange={event => setEditing({ ...editing, conditions: editing.conditions.map((row, rowIndex) => rowIndex === index ? { ...row, value: event.target.value } : row) })} /> },
{ title: '', width: 82, render: (_, __, index) => <Button type="link" danger disabled={editing.conditions.length <= 1} onClick={() => confirmDelete({title:`移除条件 ${index + 1}?`,description:"将从当前匹配规则中移除此条件,保存规则后生效。",confirmText:"确认移除",onConfirm:()=>setEditing({ ...editing, conditions: editing.conditions.filter((__, rowIndex) => rowIndex !== index) })})}>移除</Button> },
]} />
<Form.Item label="处理范围"><Switch checked={editing.onlyUnclassified===true} disabled={!['group','projectGroup'].includes(editing.target) || rules.some(rule=>rule.id===editing.id && rule.onlyUnclassified===true)} checkedChildren="仅未分类" unCheckedChildren="全部匹配行" onChange={onlyUnclassified=>setEditing({...editing,onlyUnclassified})}/></Form.Item><div className="structured-config-form-grid" style={{ marginTop: 16 }}><Form.Item label="目标类型"><Select value={editing.target} options={targets} disabled={editing.onlyUnclassified===true} onChange={target => setEditing({ ...editing, target })} /></Form.Item><Form.Item label="匹配结果" required><Input value={editing.value} maxLength={190} onChange={event => setEditing({ ...editing, value: event.target.value })} placeholder="例如:工业电机-VCM" /></Form.Item></div>
{error && <Alert showIcon type="error" message={error} />}
</Form>}
</Modal>
</div>;
}
export function MasterDataDefinitionEditor({ value, onChange, publishedNames, simplified = false, readOnly = false }: DefinitionProps & { publishedNames?: Partial<Record<MasterKind, string[]>> & { groupDepartments?: Record<string, string | null> }; simplified?: boolean; readOnly?: boolean }) {
const confirmDelete = useDeleteConfirmation();
const { message } = App.useApp(); const [kind, setKind] = useState<MasterKind>('departments'); const [search, setSearch] = useState('');
const [editing, setEditing] = useState<MasterRow | null>(null); const [originalCode, setOriginalCode] = useState<string | null>(null); const [error, setError] = useState(''); const [importing, setImporting] = useState(false);
const [departmentAtOpen, setDepartmentAtOpen] = useState<{ value: string } | null>(null);
const [form] = Form.useForm<MasterRow>(); 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<MasterRow> = [{ 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 ? '(已停用)' : ''}` : <span className="structured-config-muted">未设置</span>; } }] : []), { title: '状态', dataIndex: 'enabled', key: 'enabled', width: 100, render: enabled => <Tag color={enabled ? 'green' : 'default'}>{enabled ? '启用' : '停用'}</Tag> }, ...(!readOnly ? [{ title: '操作', key: 'actions', width: 205, render: (_: unknown, row: MasterRow) => <span className="task-actions"><Button type="link" onClick={() => openRow(row)}>编辑</Button><Button type="link" onClick={() => onChange(setMasterRows(value, kind, rows.map(item => item.code === row.code ? { ...item, enabled: !item.enabled } : item)))}>{row.enabled ? '停用' : '恢复'}</Button><Button type="link" danger onClick={() => confirmDelete({title:`删除${masterLabels[kind]}“${row.name}”?`,description:"将从当前名录移除,保存并更新报表后生效。请确认相关对应关系不再使用此项。",onConfirm:()=>onChange(setMasterRows(value, kind, rows.filter(item => item.code !== row.code)))})}>删除</Button></span> }] : [])];
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 <div className="structured-config-editor">
{!simplified && <div className="structured-config-intro"><p>维护产业部、业务分组、产品及项目组的统一名录。名称必须唯一。</p>{!simplified && <Button onClick={loadExisting}>从当前配置及对应关系载入名录</Button>}</div>}
<div className="structured-config-toolbar"><label className="config-type-filter"><span>名录类型</span><Select {...readableSelectPopup} aria-label="名录类型" value={kind} options={masterKinds.map(key=>({value:key,label:masterLabels[key]}))} onChange={key=>{setKind(key);setSearch('');}} /></label><Input.Search value={search} onChange={event => setSearch(event.target.value)} placeholder="查找名称或所属产业部" allowClear aria-label={`查找${label}`} /><span>{rows.length} 条 · 启用 {rows.filter(row => row.enabled).length}</span><div className="structured-config-actions"><ConfigurationWorkbookActions value={value} onChange={onChange} scope={kind} label={`${label}名录`} readOnly={readOnly} validate={validateStructuredMappingDefinition} onPaste={()=>setImporting(true)} />{!readOnly && <><Button type="primary" icon={<PlusOutlined />} onClick={() => openRow()}>新增{label}</Button></>}</div></div>
<Table size="small" bordered rowKey="code" columns={columns} dataSource={visibleRows} pagination={{ pageSize: 15, showSizeChanger: false }} scroll={{ x: kind === 'groups' ? 940 : 720 }} locale={{ emptyText: `尚未维护${label}名录` }} />
<p className="structured-config-note">停用项保留在名录中;启用中的对应关系如引用停用名称,校验将指出具体位置。已有分析记录保留生成时使用的名称。</p>
<Modal className="management-modal structured-config-modal" open={Boolean(editing)} title={`${originalCode === null ? '新增' : '编辑'}${label}`} width={520} okText={simplified ? '保存此行' : '写入草稿'} onCancel={() => 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); }}><Form form={form} layout="vertical"><Form.Item name="name" label="名称" rules={[{ required: true, whitespace: true, message: '请填写名称' }]}><Input maxLength={190} /></Form.Item>{kind === 'groups' && <Form.Item name="department" label="所属产业部"><Select {...readableSelectPopup} allowClear placeholder="可不设置;选择启用中的产业部" options={departmentOptions} /></Form.Item>}<Form.Item name="enabled" label="状态" valuePropName="checked"><Switch checkedChildren="启用" unCheckedChildren="停用" /></Form.Item></Form>{error && <Alert showIcon type="error" message={error} />}</Modal>
<BatchImport open={importing} title={`${label}名录`} columns={csvHeaders} existing={rows.length > 0} writeTarget={simplified ? '当前配置' : '草稿'} onCancel={() => setImporting(false)} onImport={(input, replace) => {
const incoming: MasterRow[] = []; const codes = new Set(rows.map(row => row.code)); const names = new Set<string>();
input.forEach((cells, index) => {
const maxColumns = kind === 'groups' ? 3 : 2;
const name = cells[0]?.trim();
if (!name || cells.length > maxColumns) throw new Error(`第 ${index + 1} 行应包含名称${kind === 'groups' ? '、可选启用状态及可选所属产业部' : '及可选启用状态'}`);
if (names.has(name)) throw new Error(`第 ${index + 1} 行名称在导入内容中重复`); names.add(name);
const previous = rows.find(row => row.name === name);
if (previous && !replace) throw new Error(`第 ${index + 1} 行名称已存在:${name}`);
const code = previous?.code || newMasterDataCode(codes); codes.add(code);
incoming.push({ ...previous, code, name, enabled: parseEnabled(cells[1], index + 1) ?? previous?.enabled ?? true,
...(kind === 'groups' && cells.length >= 3 ? { department: cells[2] } : {}) });
});
const changed = new Set(incoming.map(row => row.code)); const result = [...rows.filter(row => !changed.has(row.code)), ...incoming];
if (new Set(result.map(row => row.name)).size !== result.length) throw new Error('导入后名称重复,请检查名称');
onChange(setMasterRows(value, kind, result)); setImporting(false); message.success(simplified ? `已将 ${incoming.length} 个名称加入当前编辑` : `已将 ${incoming.length} 个名称写入草稿,请保存后校验`);
}} />
</div>;
}
export function TechnicalDefinitionEditor({ value, onChange }: DefinitionProps) {
const [text, setText] = useState(JSON.stringify(withoutSystemVersionFields(value), null, 2)); const [error, setError] = useState(''); const { message } = App.useApp();
useEffect(() => { setText(JSON.stringify(withoutSystemVersionFields(value), null, 2)); setError(''); }, [value]);
return <details className="structured-config-technical"><summary>可编辑规则定义</summary><p className="structured-config-note">系统维护字段已隐藏,保存时会自动保留。</p><Input.TextArea rows={12} value={text} onChange={event => setText(event.target.value)} spellCheck={false} className="json-editor" aria-label="可编辑规则定义" /><Button onClick={() => {
try { const parsed: unknown = JSON.parse(text); if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) throw new Error('定义必须是对象'); onChange(preserveSystemVersionFields(parsed, value) as ConfigDefinition); setError(''); message.success('定义已应用到当前草稿,请保存'); } catch (value) { setError(value instanceof Error ? value.message : 'JSON 无效'); }
}}>应用到草稿</Button>{error && <Alert type="error" showIcon message={error} />}</details>;
}
export { RuleSettingsEditor as RuleDefinitionEditor } from './RuleSettingsEditor';