初始化:质量数据分析平台源码

This commit is contained in:
2026-10-22 15:58:57 +08:00
commit 1e8a655adc
280 changed files with 43922 additions and 0 deletions
+411
View File
@@ -0,0 +1,411 @@
import { useEffect, useMemo, useState } from 'react';
import { Alert, App, AutoComplete, Button, Checkbox, Form, Input, InputNumber, Modal, Select, Switch, Table, Tabs, Tag } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { DownloadOutlined, PlusOutlined, UploadOutlined } 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',
]);
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) } };
}
function csvText(rows: (string | boolean | null)[][]): string { return rows.map(row => row.map(cell => `"${String(cell ?? '').replaceAll('"', '""')}"`).join(',')).join('\r\n'); }
function downloadCsv(filename: string, rows: (string | boolean | null)[][]) {
const url = URL.createObjectURL(new Blob(['\uFEFF', csvText(rows)], { type: 'text/csv;charset=utf-8' }));
const link = document.createElement('a'); link.href = url; link.download = filename; link.click(); URL.revokeObjectURL(url);
}
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}:编码最多100字、名称最多190字`);
if (codes.has(row.code)) errors.push(`${prefix}:编码“${row.code}”重复`);
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 { 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={() => 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">
<Tabs activeKey={kind} onChange={key => { setKind(key as MappingKind); setSearch(''); }} items={mappingKinds.map(key => ({ key, label: mappingInfo[key].label }))} />
<div className="structured-config-toolbar"><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"><Button icon={<DownloadOutlined />} onClick={() => downloadCsv(`${info.label}.csv`, [headers, ...rows.map(row => [row.source, ...(info.secondary ? [row.secondary] : []), row.target, row.enabled])])}>导出 CSV</Button>{!readOnly && <><Button icon={<UploadOutlined />} onClick={() => setImporting(true)}>批量导入</Button><Button type="primary" icon={<PlusOutlined />} onClick={() => openRow()}>新增对应</Button></>}</div></div>
<Table size="small" bordered rowKey="key" columns={columns} dataSource={visibleRows} pagination={{ pageSize: 10, 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 = { 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: 'vcm-category', 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 [editing, setEditing] = useState<MatchRule | null>(null);
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 { 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.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"><span>按优先级从小到大执行;同一目标类型只采用首条命中规则。条件之间按“且”组合。</span><div className="structured-config-actions">{!readOnly && <Button type="primary" icon={<PlusOutlined />} onClick={() => open()}>新增匹配规则</Button>}</div></div>
<Table size="small" bordered rowKey="id" dataSource={rules} pagination={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={() => 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; }
commit(editing.id ? rules.map(rule => rule.id === editing.id ? next : rule) : [...rules, { ...next, id: `match-${crypto.randomUUID()}` }]); 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={() => setEditing({ ...editing, conditions: editing.conditions.filter((__, rowIndex) => rowIndex !== index) })}>移除</Button> },
]} />
<div className="structured-config-form-grid" style={{ marginTop: 16 }}><Form.Item label="目标类型"><Select value={editing.target} options={targets} 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 { 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;
let code = name.slice(0, 100); let suffix = 2; while (codes.has(code)) { const tail = `-${suffix++}`; code = `${name.slice(0, 100 - tail.length)}${tail}`; }
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: 'code', key: 'code', width: 220 }, { 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={() => 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.code} ${row.name} ${kind === 'groups' ? departmentFor(row) : ''}`.toLowerCase().includes(search.toLowerCase()));
return <div className="structured-config-editor">
<div className="structured-config-intro"><p>维护产业部、业务分组、产品及项目组的统一名录。编码与名称必须唯一。</p>{!simplified && <Button onClick={loadExisting}>从当前配置及对应关系载入名录</Button>}</div>
<Tabs activeKey={kind} onChange={key => { setKind(key as MasterKind); setSearch(''); }} items={masterKinds.map(key => ({ key, label: `${masterLabels[key]}(${masterRows(value, key).length})` }))} />
<div className="structured-config-toolbar"><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"><Button icon={<DownloadOutlined />} onClick={() => downloadCsv(`${label}名录.csv`, [csvHeaders, ...rows.map(row => [row.code, row.name, row.enabled, ...(kind === 'groups' ? [departmentFor(row)] : [])])])}>导出 CSV</Button>{!readOnly && <><Button icon={<UploadOutlined />} onClick={() => setImporting(true)}>批量导入</Button><Button type="primary" icon={<PlusOutlined />} onClick={() => openRow()}>新增{label}</Button></>}</div></div>
<Table size="small" bordered rowKey="code" columns={columns} dataSource={visibleRows} pagination={{ pageSize: 10, 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: fields.code.trim(), 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="code" label="编码" rules={[{ required: true, whitespace: true, message: '请填写编码' }]}><Input maxLength={100} /></Form.Item><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<string>(); const names = new Set<string>();
input.forEach((cells, index) => {
const maxColumns = kind === 'groups' ? 4 : 3;
if (cells.length < 2 || cells.length > maxColumns || !cells[0] || !cells[1]) throw new Error(`第 ${index + 1} 行应包含编码、名称${kind === 'groups' ? '、可选启用状态及可选所属产业部' : '及可选启用状态'}`);
if (codes.has(cells[0]) || names.has(cells[1])) throw new Error(`第 ${index + 1} 行编码或名称在导入内容中重复`); codes.add(cells[0]); names.add(cells[1]);
const previous = rows.find(row => row.code === cells[0]);
if (previous && !replace) throw new Error(`第 ${index + 1} 行编码已存在:${cells[0]}`);
if (rows.some(row => row.name === cells[1] && row.code !== cells[0] && !input.some(candidate => candidate[0] === row.code))) throw new Error(`第 ${index + 1} 行名称已被其他编码使用:${cells[1]}`);
const renamedParent = kind === 'groups' && previous && previous.name !== cells[1] && !Object.hasOwn(previous, 'department')
? departmentFor(previous) : '';
incoming.push({ ...previous, code: cells[0], name: cells[1], enabled: parseEnabled(cells[2], index + 1) ?? previous?.enabled ?? true,
...(kind === 'groups' && cells.length >= 4 ? { department: cells[3] } : renamedParent ? { department: renamedParent } : {}) });
});
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>;
}
type RuleRow = Record<string, unknown>;
const policyLabels: Record<string, string> = { PROPAGATE: '任一输入为空则结果为空', ZERO: '空值按 0 参与计算', IGNORE: '全部为空则为空,其余按 0', ONE: '分母为 0 时返回 1', NULL: '分母为 0 时返回空值', ERROR: '分母为 0 时停止计算' };
const nullResultLabels: Record<string, string> = { NULL: '保留空值', ONE: '返回 1', ZERO: '返回 0', ERROR: '停止并报错' };
const zeroPolicyLabels: Record<string, string> = { ONE: '返回 1', ZERO: '返回 0', NULL: '返回空值', ERROR: '停止并报错' };
const operatorLabels: Record<string, string> = { EQ: '等于', NE: '不等于', CONTAINS: '包含', NOT_CONTAINS: '不包含', IS_BLANK: '为空', IS_NOT_BLANK: '不为空', GT: '大于', GTE: '大于等于', LT: '小于', LTE: '小于等于' };
function stringList(value: unknown): string[] { return Array.isArray(value) ? value.map(String) : []; }
export function RuleDefinitionEditor({ value, onChange, schema, schemaError }: DefinitionProps & { schema: Record<string, unknown> | null; schemaError: string }) {
const [tab, setTab] = useState('source'); const [editing, setEditing] = useState<number | null>(null); const [ruleError, setRuleError] = useState('');
const [form] = Form.useForm<{ stage: string; target: string; formula: string; nullPolicy: string; zeroDenominatorPolicy: string; nullResultPolicy: string; conditional: boolean; conditionField: string; conditionOperator: string; conditionValue: string; otherwiseFormula: string }>();
const selectedStage = Form.useWatch('stage', form) || 'black'; const conditional = Form.useWatch('conditional', form); const conditionOperator = Form.useWatch('conditionOperator', form);
if (!schema) return <Alert showIcon type={schemaError ? 'error' : 'info'} message={schemaError ? '规则编辑结构读取失败' : '正在读取规则编辑结构'} description={schemaError || '编辑项与可用公式变量由服务端提供。'} />;
const configured = value.schemaVersion === schema.schemaVersion;
const fields = objectValue(schema.sourceFields); const targets = objectValue(schema.rowTargets); const componentLabels = objectValue(schema.componentLabels); const metricLabels = objectValue(schema.metricLabels); const baselineDescriptions = objectValue(schema.baselineMetricDescriptions);
const nullOptions = stringList(schema.nullPolicies).map(key => ({ value: key, label: policyLabels[key] || key })); const zeroOptions = stringList(schema.zeroDenominatorPolicies).map(key => ({ value: key, label: zeroPolicyLabels[key] || key }));
const nullResultOptions = stringList(schema.nullResultPolicies).map(key => ({ value: key, label: nullResultLabels[key] || key }));
const sourceFields = objectValue(value.sourceFields); const rowRules = Array.isArray(value.rowRules) ? value.rowRules.map(objectValue) : []; const metricRules = objectValue(value.metricRules); const metricCodes = stringList(schema.metricCodes);
const limits = objectValue(schema.limits); const maxFormulaLength = Number(limits.maxFormulaLength || 500); const maxRowRules = Number(limits.maxRowRules || 100);
const targetLabel = (target: unknown) => String(componentLabels[String(target)] || target || ''); const metricLabel = (metric: string) => String(metricLabels[metric] || metric);
const replaceRules = (rules: RuleRow[]) => onChange({ ...value, rowRules: rules });
const editRow = (index: number | null) => {
const rule = index === null ? {} : rowRules[index]; const when = objectValue(rule.when); const stage = String(rule.stage || 'black');
setEditing(index === null ? rowRules.length : index); setRuleError('');
form.setFieldsValue({ stage, target: String(rule.target || stringList(targets[stage])[0] || ''), formula: String(rule.formula || ''), nullPolicy: String(rule.nullPolicy || 'PROPAGATE'), zeroDenominatorPolicy: String(rule.zeroDenominatorPolicy || 'ONE'), nullResultPolicy: String(rule.nullResultPolicy || 'NULL'), conditional: Boolean(rule.when), conditionField: String(when.field || Object.keys(objectValue(fields[stage]))[0] || ''), conditionOperator: String(when.operator || 'CONTAINS'), conditionValue: String(when.value ?? ''), otherwiseFormula: String(rule.otherwiseFormula || '') });
};
const metricVariables = ['blackGood', 'blackScrap', 'blackTotal', 'brightGood', 'brightScrap', 'brightTotal', 'headquartersScrap'];
const ruleColumns: ColumnsType<RuleRow & { index: number }> = [
{ title: '顺序', dataIndex: 'index', width: 70, render: index => index + 1 },
{ title: '阶段 / 结果', key: 'target', width: 205, render: (_, row) => <span>{row.stage === 'black' ? '黑片' : '亮片'} · {targetLabel(row.target)}</span> },
{ title: '公式', dataIndex: 'formula', width: 290, render: formula => <code>{String(formula)}</code> },
{ title: '触发条件', key: 'when', width: 200, render: (_, row) => { const when = objectValue(row.when); return row.when ? `${String(objectValue(fields[String(row.stage)])[String(when.field)] || when.field)} ${operatorLabels[String(when.operator)] || when.operator} ${String(when.value ?? '')}` : '所有行'; } },
{ title: '操作', key: 'actions', width: 205, render: (_, row) => <span className="task-actions"><Button type="link" onClick={() => editRow(row.index)}>编辑</Button><Button type="link" disabled={row.index === 0} onClick={() => { const next = [...rowRules]; [next[row.index - 1], next[row.index]] = [next[row.index], next[row.index - 1]]; replaceRules(next); }}>上移</Button><Button type="link" disabled={row.index === rowRules.length - 1} onClick={() => { const next = [...rowRules]; [next[row.index], next[row.index + 1]] = [next[row.index + 1], next[row.index]]; replaceRules(next); }}>下移</Button><Button type="link" onClick={() => replaceRules(rowRules.filter((_, index) => index !== row.index))}>移除</Button></span> },
];
if (!configured) return <div className="structured-config-editor"><Alert showIcon type="info" message="当前草稿沿用原始公式" description="当前公式继续生效。需要调整字段或公式时,先转换为可维护规则;未覆盖的计算继续沿用原逻辑。" /><Button style={{ marginTop: 12 }} onClick={() => onChange(JSON.parse(JSON.stringify(objectValue(schema.defaultDefinition))) as ConfigDefinition)}>开始维护字段与公式</Button></div>;
return <div className="structured-config-editor">
<Tabs activeKey={tab} onChange={setTab} items={[
{ key: 'source', label: '来源字段', children: <div><p className="structured-config-note" style={{ marginBottom: 12 }}>将计算字段对应到来源表列名。未修改项沿用原列名,字段别名用于公式引用。</p><Tabs items={['black', 'bright'].map(stage => ({ key: stage, label: stage === 'black' ? '黑片字段' : '亮片字段', children: <Table size="small" bordered rowKey="alias" pagination={false} scroll={{ x: 670 }} dataSource={Object.entries(objectValue(fields[stage])).map(([alias, header]) => ({ alias, header: String(header) }))} columns={[
{ title: '计算字段', dataIndex: 'header', width: 240 }, { title: '公式别名', dataIndex: 'alias', width: 200, render: alias => <code>{alias}</code> },
{ title: '来源表列名', key: 'source', render: (_, row) => <Input aria-label={`${stage === 'black' ? '黑片' : '亮片'} ${row.header}来源列名`} value={String(objectValue(sourceFields[stage])[row.alias] ?? row.header)} maxLength={200} onChange={event => onChange({ ...value, sourceFields: { ...sourceFields, [stage]: { ...objectValue(sourceFields[stage]), [row.alias]: event.target.value } } })} /> },
{ title: '操作', key: 'reset', width: 100, render: (_, row) => <Button type="link" onClick={() => { const next = { ...objectValue(sourceFields[stage]) }; delete next[row.alias]; onChange({ ...value, sourceFields: { ...sourceFields, [stage]: next } }); }}>恢复原列名</Button> },
]} /> }))} /></div> },
{ key: 'rows', label: `行计算(${rowRules.length})`, children: <div><div className="structured-config-toolbar"><span>按顺序执行;未覆盖的结果沿用原计算。</span><div className="structured-config-actions"><Button type="primary" icon={<PlusOutlined />} disabled={rowRules.length >= maxRowRules} onClick={() => editRow(null)}>新增行公式</Button></div></div><Table size="small" bordered rowKey="index" columns={ruleColumns} dataSource={rowRules.map((row, index) => ({ ...row, index }))} pagination={false} scroll={{ x: 980 }} locale={{ emptyText: '当前全部沿用原始行计算' }} /><p className="structured-config-note">修改报废等分量后,如需改变合计结果,请同时维护依赖它的合计公式。</p></div> },
{ key: 'metrics', label: '指标公式', children: <div className="structured-config-rule-list"><p className="structured-config-note">未开启覆盖的指标沿用原始公式。公式可引用重量变量及排在前面的指标结果。</p>{metricCodes.map((metric, index) => {
const rule = objectValue(metricRules[metric]); const enabled = Object.hasOwn(metricRules, metric);
const updateMetric = (patch: Record<string, unknown>) => onChange({ ...value, metricRules: { ...metricRules, [metric]: { ...rule, ...patch } } });
return <div className="structured-config-rule-card" key={metric}><div className="structured-config-toolbar"><strong>{metricLabel(metric)}</strong><code>{metric}</code><Checkbox checked={enabled} onChange={event => { const next = { ...metricRules }; if (event.target.checked) next[metric] = { formula: '', nullPolicy: 'PROPAGATE', zeroDenominatorPolicy: 'ONE', ...(nullResultOptions.length ? { nullResultPolicy: 'NULL' } : {}) }; else delete next[metric]; onChange({ ...value, metricRules: next }); }}>使用此公式</Checkbox></div>{Boolean(baselineDescriptions[metric]) && <p className="structured-config-note" style={{ marginBottom: 12 }}>原计算:{String(baselineDescriptions[metric])}</p>}{enabled && <><div className="structured-config-rule-grid"><div><label>公式</label><Input.TextArea rows={2} aria-label={`${metricLabel(metric)}公式`} value={String(rule.formula || '')} maxLength={maxFormulaLength} onChange={event => updateMetric({ formula: event.target.value })} placeholder="填写四则运算公式" /></div><div><label>空值策略</label><Select style={{ width: '100%' }} aria-label={`${metricLabel(metric)}空值策略`} options={nullOptions} value={String(rule.nullPolicy || 'PROPAGATE')} onChange={nullPolicy => updateMetric({ nullPolicy })} /></div><div><label>零分母策略</label><Select style={{ width: '100%' }} aria-label={`${metricLabel(metric)}零分母策略`} options={zeroOptions} value={String(rule.zeroDenominatorPolicy || 'ONE')} onChange={zeroDenominatorPolicy => updateMetric({ zeroDenominatorPolicy })} /></div>{nullResultOptions.length > 0 && <div><label>计算结果为空时</label><Select style={{ width: '100%' }} aria-label={`${metricLabel(metric)}空结果策略`} options={nullResultOptions} value={String(rule.nullResultPolicy || 'NULL')} onChange={nullResultPolicy => updateMetric({ nullResultPolicy })} /></div>}</div><p className="structured-config-note">可用变量:{[...metricVariables, ...metricCodes.slice(0, index)].join('、')}</p></>}</div>;
})}</div> },
]} />
<Modal className="management-modal structured-config-modal" open={editing !== null} title={editing !== null && editing < rowRules.length ? '编辑行公式' : '新增行公式'} width={780} okText="写入草稿" onCancel={() => setEditing(null)} onOk={() => { void form.validateFields().then(formValue => {
const rule: RuleRow = { stage: formValue.stage, target: formValue.target, formula: formValue.formula.trim(), nullPolicy: formValue.nullPolicy, zeroDenominatorPolicy: formValue.zeroDenominatorPolicy, ...(nullResultOptions.length ? { nullResultPolicy: formValue.nullResultPolicy } : {}) };
if (formValue.conditional) {
const when: RuleRow = { field: formValue.conditionField, operator: formValue.conditionOperator };
if (!['IS_BLANK', 'IS_NOT_BLANK'].includes(formValue.conditionOperator)) { if (!formValue.conditionValue?.trim()) { setRuleError('请填写触发条件值'); return; } when.value = formValue.conditionValue; }
rule.when = when; if (formValue.otherwiseFormula?.trim()) rule.otherwiseFormula = formValue.otherwiseFormula.trim();
}
const next = [...rowRules]; if (editing === null) return; next[editing] = rule; replaceRules(next); setEditing(null);
}).catch(() => undefined); }}>
<Form form={form} layout="vertical"><div className="structured-config-form-grid"><Form.Item name="stage" label="阶段" rules={[{ required: true }]}><Select options={[{ value: 'black', label: '黑片' }, { value: 'bright', label: '亮片' }]} onChange={stage => form.setFieldsValue({ target: stringList(targets[stage])[0], conditionField: Object.keys(objectValue(fields[stage]))[0] })} /></Form.Item><Form.Item name="target" label="计算结果" rules={[{ required: true, message: '请选择计算结果' }]}><Select {...readableSelectPopup} options={stringList(targets[selectedStage]).map(target => ({ value: target, label: `${targetLabel(target)} · ${target}` }))} /></Form.Item></div><Form.Item name="formula" label="公式" rules={[{ required: true, whitespace: true, message: '请填写公式' }]}><Input.TextArea rows={2} maxLength={maxFormulaLength} spellCheck={false} /></Form.Item><p className="structured-config-note" style={{ marginBottom: 14 }}>允许四则运算、括号及 SUM 求和(忽略空项,全部为空则为空)。可用别名与结果:{[...Object.keys(objectValue(fields[selectedStage])).filter(alias => !['issueLocation', 'inspectionNote', 'applicability'].includes(alias)), ...stringList(targets[selectedStage])].join('、')}</p><div className="structured-config-form-grid"><Form.Item name="nullPolicy" label="空值策略"><Select options={nullOptions} /></Form.Item><Form.Item name="zeroDenominatorPolicy" label="零分母策略"><Select options={zeroOptions} /></Form.Item>{nullResultOptions.length > 0 && <Form.Item name="nullResultPolicy" label="计算结果为空时"><Select options={nullResultOptions} /></Form.Item>}</div><Form.Item name="conditional" valuePropName="checked"><Checkbox>仅在符合条件时执行</Checkbox></Form.Item>{conditional && <><div className="structured-config-form-grid"><Form.Item name="conditionField" label="条件字段" rules={[{ required: true }]}><Select {...readableSelectPopup} options={Object.entries(objectValue(fields[selectedStage])).map(([alias, header]) => ({ value: alias, label: String(header) }))} /></Form.Item><Form.Item name="conditionOperator" label="判断方式" rules={[{ required: true }]}><Select options={stringList(schema.conditionOperators).map(operator => ({ value: operator, label: operatorLabels[operator] || operator }))} /></Form.Item></div>{!['IS_BLANK', 'IS_NOT_BLANK'].includes(conditionOperator) && <Form.Item name="conditionValue" label="条件值"><Input /></Form.Item>}<Form.Item name="otherwiseFormula" label="不符合条件时的公式(留空保留原结果)"><Input.TextArea rows={2} maxLength={maxFormulaLength} /></Form.Item></>}</Form>{ruleError && <Alert showIcon type="error" message={ruleError} />}
</Modal>
</div>;
}