Files
quality_analyse/web/src/ResultFormulaModal.tsx
T
lyun c3354c1f64 新增:查询页面快照并修复筛选选框闪烁
页面快照支持勾选查询条件、指标卡片、趋势、汇总表、不良构成和细分缺陷图,复制PNG或下载;增加取消、分阶段提示和等待超时恢复。

修复公共Select弹层准备帧被opacity覆盖导致的先闪出再展开,并取消查询字段原生label的重复点击转发。

同步已经验收上线的销售订单类型映射、排除筛选及预聚合,以及其线上权限、删除确认配套源码;保留既有公式编辑和名录编码修改。源码范围按发布清单冻结,不纳入本机数据、凭据及未发布工作。

验证:前后端独立源码构建通过;10项前端检查、4项订单分类单元测试通过;实际系统剪贴板粘贴PNG验证通过;线上配置及筛选结果与发布前一致,后端未重启。
2026-11-04 00:15:32 +08:00

89 lines
11 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 { useDeleteConfirmation } from './useDeleteConfirmation';
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 confirmDelete = useDeleteConfirmation();
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={()=>confirmDelete({title:`移除条件 ${position + 1}?`,description:"将从当前结果公式中移除此条件分支,点击“应用修改”后更新编辑内容,保存并更新报表后生效。",confirmText:"确认移除",onConfirm:()=>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>;
}