优化:整理指标目标并支持中文字段公式编辑

黑片和亮片按结果展示完整公式,在同一窗口维护条件与未匹配取值。支持中文字段选择、运算符和求和,并保留原计算语义及特殊策略。

移除重复账号入口与配置说明,统一紧凑表格。保留仓库既有权限判断,不包含此前未同步的角色迁移、预览快照或运行数据。

验证:前端构建及68项相关检查通过。
This commit is contained in:
2026-11-03 16:31:23 +08:00
parent 1aeccddd4d
commit 54813accaa
19 changed files with 992 additions and 103 deletions
+2 -62
View File
@@ -2,7 +2,7 @@ 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, Tabs, Tag } from 'antd';
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';
@@ -347,64 +347,4 @@ export function TechnicalDefinitionEditor({ value, onChange }: DefinitionProps)
}}>应用到草稿</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, showWorkbookActions = true }: DefinitionProps & { schema: Record<string, unknown> | null; schemaError: string; showWorkbookActions?: boolean }) {
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 workbookActions=showWorkbookActions?<div className="structured-config-toolbar"><ConfigurationWorkbookActions value={configured?value:objectValue(schema.defaultDefinition)} onChange={onChange} scope="rules" label="计算规则" /></div>:null;
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">{workbookActions}<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">{workbookActions}
<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={{pageSize:15,showSizeChanger: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 } } })} /> },
]} /> }))} /></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={{pageSize:15,showSizeChanger: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>;
}
export { RuleSettingsEditor as RuleDefinitionEditor } from './RuleSettingsEditor';