优化:整理指标目标并支持中文字段公式编辑
黑片和亮片按结果展示完整公式,在同一窗口维护条件与未匹配取值。支持中文字段选择、运算符和求和,并保留原计算语义及特殊策略。 移除重复账号入口与配置说明,统一紧凑表格。保留仓库既有权限判断,不包含此前未同步的角色迁移、预览快照或运行数据。 验证:前端构建及68项相关检查通过。
This commit is contained in:
@@ -0,0 +1,86 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { Alert, Button, Form, Input, Modal, Select } from 'antd';
|
||||
import { ArrowDownOutlined, ArrowUpOutlined, PlusOutlined } from '@ant-design/icons';
|
||||
import { readableSelectPopup } from './readableSelectPopup';
|
||||
import { blankCondition, conditionOperators, describeResultFormula, type ResultFormula } from './resultFormulas';
|
||||
import { ChineseFormulaEditor } from './ChineseFormulaEditor';
|
||||
import { compileChineseFormula, rowFormulaFields } from './formulaLanguage';
|
||||
import { ruleObject as obj, type RuleDefinition } from './rulePresentation';
|
||||
|
||||
type Props = { result: ResultFormula; existing: boolean; schema: RuleDefinition; availableTargets: string[]; onCancel: () => void; onApply: (result: ResultFormula) => string | undefined };
|
||||
const strings = (value: unknown): string[] => Array.isArray(value) ? value.map(String) : [];
|
||||
const missingLabels: Record<string, string> = { PROPAGATE:'任一输入缺失,结果为空', ZERO:'空值按0参与运算', IGNORE:'忽略空项,全部为空时结果为空' };
|
||||
const outcomeLabels: Record<string, string> = { ONE:'取1', ZERO:'取0', NULL:'保留空白', ERROR:'停止并报错' };
|
||||
|
||||
export function ResultFormulaModal({ result, existing, schema, availableTargets, onCancel, onApply }: Props) {
|
||||
const [draft, setDraft] = useState<ResultFormula>(() => structuredClone(result));
|
||||
const [error, setError] = useState('');
|
||||
const errorHost = useRef<HTMLDivElement>(null);
|
||||
useEffect(() => { if (error) errorHost.current?.scrollIntoView({block:'nearest'}); }, [error]);
|
||||
const fields = obj(obj(schema.sourceFields)[draft.stage]), labels = obj(schema.componentLabels);
|
||||
const maxLength = Number(obj(schema.limits).maxFormulaLength || 500);
|
||||
const formulaFields = rowFormulaFields(schema,draft.stage);
|
||||
const baseIndex = draft.rules.findIndex(rule => !rule.when);
|
||||
const branchIndexes = draft.rules.flatMap((rule, index) => rule.when ? [index] : []).reverse();
|
||||
const label = (key: string) => String(labels[key] || key);
|
||||
const update = (index: number, patch: RuleDefinition) => setDraft(current => ({ ...current, rules: current.rules.map((rule, i) => i === index ? { ...rule, ...patch } : rule) }));
|
||||
const condition = (index: number, patch: RuleDefinition) => update(index, { when: { ...obj(draft.rules[index].when), ...patch } });
|
||||
const changeTarget = (target: string) => setDraft(current => ({ ...current, target, rules: current.rules.map(rule => ({ ...rule, target })) }));
|
||||
const addBranch = () => setDraft(current => ({ ...current, rules: [...current.rules, { stage: current.stage, target: current.target, formula: '', when: { field: Object.hasOwn(fields, current.stage === 'bright' ? 'applicability' : 'issueLocation') ? (current.stage === 'bright' ? 'applicability' : 'issueLocation') : Object.keys(fields)[0], operator: current.stage === 'bright' ? 'EQ' : 'CONTAINS', value: '' } }] }));
|
||||
const remove = (index: number) => setDraft(current => ({ ...current, rules: current.rules.filter((_, i) => i !== index) }));
|
||||
const moveBranch = (index: number, direction: number) => {
|
||||
const position = branchIndexes.indexOf(index), other = branchIndexes[position + direction];
|
||||
if (other === undefined) return;
|
||||
setDraft(current => { const rules = current.rules.slice(); [rules[index], rules[other]] = [rules[other], rules[index]]; return { ...current, rules }; });
|
||||
};
|
||||
const apply = () => {
|
||||
if (!draft.target || !draft.rules.length) { setError('请设置计算结果及公式'); return; }
|
||||
if (draft.rules.some(rule => !String(rule.formula || '').trim())) { setError('请填写完整公式'); return; }
|
||||
if (draft.rules.some(rule => rule.when && !blankCondition(obj(rule.when).operator) && !String(obj(rule.when).value ?? '').trim())) { setError('请填写条件值'); return; }
|
||||
const rules: RuleDefinition[] = [];
|
||||
for (const rule of draft.rules) {
|
||||
const formula = compileChineseFormula(rule.formula,formulaFields,maxLength);
|
||||
if (formula.error) { setError(formula.error); return; }
|
||||
const next: RuleDefinition = { ...rule, formula:formula.formula };
|
||||
if (rule.otherwiseFormula !== undefined) {
|
||||
const otherwise = compileChineseFormula(rule.otherwiseFormula,formulaFields,maxLength);
|
||||
if (otherwise.error) { setError(otherwise.error); return; }
|
||||
next.otherwiseFormula = otherwise.formula;
|
||||
}
|
||||
rules.push(next);
|
||||
}
|
||||
const failure = onApply({ ...draft,rules }); if (failure) setError(failure);
|
||||
};
|
||||
const formulaInput = (index: number, title: string) => <Form.Item label={title} htmlFor={`result-formula-${index}`}><ChineseFormulaEditor id={`result-formula-${index}`} label={title} value={String(draft.rules[index].formula ?? '')} onChange={formula => update(index, { formula })} fields={formulaFields} maxLength={maxLength}/></Form.Item>;
|
||||
const policies = (index: number) => <details className="rule-reference result-rule-options"><summary>特殊情况处理</summary><div className="structured-config-form-grid">
|
||||
{(['nullPolicy','zeroDenominatorPolicy', ...(strings(schema.nullResultPolicies).length ? ['nullResultPolicy'] : [])]).map(key => <Form.Item key={key} label={{nullPolicy:'输入缺失时',zeroDenominatorPolicy:'分母为0时',nullResultPolicy:'最终结果为空时'}[key]} htmlFor={`result-${index}-${key}`}><Select id={`result-${index}-${key}`} value={String(draft.rules[index][key] || (key === 'nullPolicy' ? 'PROPAGATE' : key === 'zeroDenominatorPolicy' ? 'ONE' : 'NULL'))} options={strings(schema[key === 'nullPolicy' ? 'nullPolicies' : key === 'zeroDenominatorPolicy' ? 'zeroDenominatorPolicies' : 'nullResultPolicies']).map(value => ({ value, label:(key === 'nullPolicy' ? missingLabels : outcomeLabels)[value] || value }))} onChange={value => update(index, { [key]:value })}/></Form.Item>)}
|
||||
</div>{Boolean(draft.rules[index].when) && <Form.Item label="未满足此条件时的覆盖公式(留空保留此前取值)" htmlFor={`result-otherwise-${index}`}><ChineseFormulaEditor id={`result-otherwise-${index}`} label="其他情况公式" optional fields={formulaFields} value={String(draft.rules[index].otherwiseFormula ?? '')} maxLength={maxLength} onChange={formula => {
|
||||
const rules = draft.rules.slice(), rule = { ...rules[index] };
|
||||
if (formula.trim()) rule.otherwiseFormula = formula; else delete rule.otherwiseFormula;
|
||||
rules[index] = rule; setDraft({ ...draft, rules });
|
||||
}}/></Form.Item>}</details>;
|
||||
const simpleFallback = baseIndex === 0 && draft.rules.slice(1).every(rule => Boolean(rule.when) && rule.otherwiseFormula === undefined);
|
||||
const baseFormula = baseIndex >= 0 ? <div className={`result-formula-default${branchIndexes.length ? ' result-formula-fallback' : ''}`}>{formulaInput(baseIndex,branchIndexes.length ? (simpleFallback ? '以上条件均不满足时取值' : '基础取值') : '计算公式')}{policies(baseIndex)}</div> : <div className="result-fallback"><span>以上条件均不满足时沿用原计算结果</span><Button type="link" onClick={()=>setDraft(current=>({...current,rules:[{stage:current.stage,target:current.target,formula:'0'},...current.rules]}))}>设置未匹配时取值</Button></div>;
|
||||
return <Modal open className="management-modal rule-form-modal result-formula-modal" title={existing ? `编辑公式 · ${label(draft.target)}` : '新增结果公式'} width={820} styles={{body:{maxHeight:'calc(100dvh - 240px)',overflowY:'auto',paddingRight:4}}} okText="应用修改" onCancel={onCancel} onOk={apply}>
|
||||
{error&&<div ref={errorHost}><Alert type="error" showIcon title="公式尚未应用" description={error}/></div>}
|
||||
<Form layout="vertical">
|
||||
{!existing && <Form.Item label="计算结果" htmlFor="result-target"><Select id="result-target" {...readableSelectPopup} value={draft.target} options={availableTargets.map(value => ({value,label:label(value)}))} onChange={changeTarget}/></Form.Item>}
|
||||
<div className="rule-change-preview rule-form-logic"><div><span>完整公式</span><p>{describeResultFormula(draft,schema)}</p></div></div>
|
||||
{branchIndexes.length === 0 && baseFormula}
|
||||
{(branchIndexes.length > 0) && <p className="result-priority-hint">{draft.rules.some(rule=>rule.otherwiseFormula !== undefined) ? '已设置其他情况取值,最终取值以完整公式为准。' : '条件同时满足时,上方分支优先。'}</p>}
|
||||
{branchIndexes.map((index, position) => { const rule=draft.rules[index], when=obj(rule.when); return <section className="result-condition-branch" key={index}>
|
||||
<div className="result-branch-heading"><strong>条件 {position + 1}</strong><span className="task-actions"><Button size="small" type="text" aria-label={`条件${position+1}提高优先级`} icon={<ArrowUpOutlined/>} disabled={position===0} onClick={()=>moveBranch(index,-1)}/><Button size="small" type="text" aria-label={`条件${position+1}降低优先级`} icon={<ArrowDownOutlined/>} disabled={position===branchIndexes.length-1} onClick={()=>moveBranch(index,1)}/><Button size="small" type="link" danger onClick={()=>remove(index)}>移除</Button></span></div>
|
||||
<div className="result-condition-fields">
|
||||
<Form.Item label="条件字段" htmlFor={`result-field-${index}`}><Select id={`result-field-${index}`} {...readableSelectPopup} value={String(when.field || '')} options={Object.entries(fields).map(([value,name])=>({value,label:String(name)}))} onChange={field=>condition(index,{field})}/></Form.Item>
|
||||
<Form.Item label="判断方式" htmlFor={`result-operator-${index}`}><Select id={`result-operator-${index}`} value={String(when.operator || '')} options={strings(schema.conditionOperators).map(value=>({value,label:conditionOperators[value]||value}))} onChange={operator=>condition(index,{operator})}/></Form.Item>
|
||||
{!blankCondition(when.operator) && <Form.Item label="条件值" htmlFor={`result-value-${index}`}><Input id={`result-value-${index}`} value={String(when.value ?? '')} onChange={event=>condition(index,{value:event.target.value})}/></Form.Item>}
|
||||
</div>
|
||||
{formulaInput(index,'满足条件时取值')}{policies(index)}
|
||||
</section>; })}
|
||||
{draft.rules.flatMap((rule,index)=>!rule.when&&index!==baseIndex?[index]:[]).map(index=><section className="result-condition-branch" key={index}>{formulaInput(index,'后续覆盖公式')}{policies(index)}</section>)}
|
||||
<Button icon={<PlusOutlined/>} onClick={addBranch} disabled={draft.rules.length >= Number(obj(schema.limits).maxRowRules || 100)}>新增条件</Button>
|
||||
{branchIndexes.length > 0 && baseFormula}
|
||||
|
||||
</Form>
|
||||
</Modal>;
|
||||
}
|
||||
Reference in New Issue
Block a user