优化:整理指标目标并支持中文字段公式编辑
黑片和亮片按结果展示完整公式,在同一窗口维护条件与未匹配取值。支持中文字段选择、运算符和求和,并保留原计算语义及特殊策略。 移除重复账号入口与配置说明,统一紧凑表格。保留仓库既有权限判断,不包含此前未同步的角色迁移、预览快照或运行数据。 验证:前端构建及68项相关检查通过。
This commit is contained in:
@@ -135,3 +135,32 @@
|
|||||||
- 实现与验证详见 docs/全系统统一加载实现与验收_20261102.md。
|
- 实现与验证详见 docs/全系统统一加载实现与验收_20261102.md。
|
||||||
|
|
||||||
- 2026-11-02:趋势折线使用用户选定的 A 轻度平滑(0.15),沿横轴约束曲线;查询合格率、不良率、智能分析与导出统一。柏拉图累计线保持直线,数据点、缺失断点和计算口径不变。
|
- 2026-11-02:趋势折线使用用户选定的 A 轻度平滑(0.15),沿横轴约束曲线;查询合格率、不良率、智能分析与导出统一。柏拉图累计线保持直线,数据点、缺失断点和计算口径不变。
|
||||||
|
|
||||||
|
## 2026-11-03:指标与目标(本地预览)
|
||||||
|
|
||||||
|
- 采用用户确认的“指标说明、质量目标、计算设置”顺序,默认显示中文指标与当前生效公式。
|
||||||
|
- 指标说明的修改公式动作定位到同一计算设置表单;名称、别名与说明独立编辑。
|
||||||
|
- 目标默认表格查看,表单修改年度、范围和百分比;展示既有匹配优先级得出的沿用值,保持保存目标的现有接口与即时生效行为。
|
||||||
|
- 计算设置默认从黑片计算开始,黑片、亮片各一张表,每个结果只占一行,各自从1开始编号,不分组、不重复展示完整执行顺序;完整公式包含默认值和全部条件分支,长内容使用共享悬浮全文。来源字段收进高级设置,仅用于旧数据兼容。保留原始行数组、所有公式及特殊处理。
|
||||||
|
- 英文变量放入表单参考详情;率值1解释为100%。延续现有主题、控件、弹窗及切换过渡,不新增位移动效。
|
||||||
|
- 本次预览使用配置只读快照,保存及失败重试在预览中模拟;未发布线上,未修改计算后端及正式配置。
|
||||||
|
|
||||||
|
- 用户反馈行高偏大:指标说明、质量目标、计算设置统一复用现有管理表格的紧凑样式(表头34px、内容行36px),不单独覆盖字号、行距或单元格间距;长内容通过共享悬浮全文与详情查看。
|
||||||
|
|
||||||
|
- 调整顺序以完整结果及其分支为单位,只发生在当前阶段内,限制合计早于分量等依赖冲突;编辑在同一窗口维护默认取值、条件和各自特殊策略,分支同时命中时上方优先。编辑与保存前检查不可用变量、重复冲突条件及指标前向引用。校验只作用于维护操作,不改写或求值正式公式;来源变量按对应阶段的服务端字段字典显示中文。
|
||||||
|
|
||||||
|
- 2026-11-03:用户确认“一个结果一条完整公式”,本地将黑片13条执行规则呈现为8个结果、亮片9条执行规则呈现为7个结果。相同取值的条件可用“或”展示,底层不合并求值、不改优先级;未修改直接应用须保持原22条规则、位置、数值类型和空值策略完全一致。原有表头34px、行高36px及共享悬浮全文保持。未发布线上。
|
||||||
|
|
||||||
|
## 2026-11-03:中文公式编辑与账号入口精简(本地)
|
||||||
|
|
||||||
|
- 黑片、亮片及合格率公式共用中文公式编辑器,使用 `[中文字段名]` 引用;可搜索选择字段、在光标处插入、替换选中文字、插入四则运算、括号、逗号和求和。也接受直接输入中文字段名。
|
||||||
|
- 字段列表区分来源字段和计算结果;重名字段用中文类别消歧,条件用文本字段不进入数值公式列表。合格率只提供已计算的前序指标。
|
||||||
|
- 保存前将中文引用转换为原有引擎字段,检查结构、参数数量、嵌套与长度,不在浏览器求值,不引入新的计算语言或改变条件与空值策略。不改动时保存须保留原公式文字及全部元数据。
|
||||||
|
- 删除左下角重复账号区域,保留右上角个人账户菜单及原有资料、密码、退出操作。
|
||||||
|
- 沿用现有表格密度、主题、弹窗与浮层风格,未发布线上。
|
||||||
|
|
||||||
|
- 条件公式编辑按阅读顺序展示:先列条件分支和满足时取值,再列“以上条件均不满足时取值”;无条件结果仍显示“计算公式”。仅调整表单展示顺序,底层初始化位置、条件优先级和特殊策略不变。
|
||||||
|
|
||||||
|
- 计算设置移除“配置说明”折叠区和说明编辑框,仅保留隐藏字段以沿用既有保存数据;公式维护和保存入口不变。
|
||||||
|
|
||||||
|
- 2026-11-03:本轮指标与目标、完整结果公式、中文字段编辑、条件优先布局、重复账号与配置说明精简,已按用户授权发布为 `20261103-082040Z-rules-workspace`。分母策略的条件隐藏已撤销,线上保持始终显示;正式计算、后端与业务数据未改动。68项检查和线上桌面/窄屏验收通过。
|
||||||
|
|||||||
@@ -0,0 +1,45 @@
|
|||||||
|
import { useLayoutEffect, useRef, useState } from 'react';
|
||||||
|
import { Button, Input, Popover } from 'antd';
|
||||||
|
import type { TextAreaRef } from 'antd/es/input/TextArea';
|
||||||
|
import { PlusOutlined, SearchOutlined } from '@ant-design/icons';
|
||||||
|
import { chineseFormula, compileChineseFormula, formulaFieldName, formulaFieldReference, insertFormulaPart, type FormulaField } from './formulaLanguage';
|
||||||
|
|
||||||
|
type Props = { id?: string; value?: string; onChange?: (value: string) => void; fields: FormulaField[]; disabled?: boolean; optional?: boolean; maxLength?: number; label?: string };
|
||||||
|
export function ChineseFormulaEditor({ id, value='', onChange, fields, disabled=false, optional=false, maxLength=500, label='公式' }: Props) {
|
||||||
|
const [text,setText]=useState(()=>chineseFormula(value,fields));
|
||||||
|
const [picker,setPicker]=useState(false), [search,setSearch]=useState('');
|
||||||
|
const [composing,setComposing]=useState(false);
|
||||||
|
const editor=useRef<TextAreaRef>(null),selection=useRef({start:0,end:0});
|
||||||
|
const emitted=useRef<string|undefined>(undefined),previousFields=useRef('');
|
||||||
|
const fieldKey=JSON.stringify(fields);
|
||||||
|
useLayoutEffect(()=>{
|
||||||
|
if(value!==emitted.current||fieldKey!==previousFields.current){setText(chineseFormula(value,fields));selection.current={start:0,end:0};}
|
||||||
|
previousFields.current=fieldKey;
|
||||||
|
// 字段集合按内容比较,父表单重绘不会打断正在输入的中文。
|
||||||
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
|
},[value,fieldKey]);
|
||||||
|
const changed=(next:string)=>{setText(next);emitted.current=next;onChange?.(next);};
|
||||||
|
const remember=()=>{const node=editor.current?.resizableTextArea?.textArea;if(node)selection.current={start:node.selectionStart,end:node.selectionEnd};};
|
||||||
|
const insert=(part:string,fn=false)=>{
|
||||||
|
const node=editor.current?.resizableTextArea?.textArea;
|
||||||
|
const range=node?{start:node.selectionStart,end:node.selectionEnd}:selection.current;
|
||||||
|
const next=insertFormulaPart(text,range.start,range.end,part,fn);
|
||||||
|
changed(next.text);selection.current={start:next.caret,end:next.caret};setPicker(false);
|
||||||
|
requestAnimationFrame(()=>{const node=editor.current?.resizableTextArea?.textArea;node?.focus();node?.setSelectionRange(next.caret,next.caret);});
|
||||||
|
};
|
||||||
|
const check=optional&&!text.trim()?undefined:compileChineseFormula(text,fields,maxLength).error;
|
||||||
|
const matching=fields.filter(field=>field.label.toLowerCase().includes(search.trim().toLowerCase()));
|
||||||
|
const groups=[...new Set(matching.map(field=>field.group))];
|
||||||
|
const chooser=<div className="formula-field-chooser">
|
||||||
|
<Input aria-label="查找公式字段" prefix={<SearchOutlined/>} placeholder="查找中文字段" value={search} onChange={event=>setSearch(event.target.value)} allowClear/>
|
||||||
|
<div className="formula-field-list">{groups.map(group=><section key={group}><h4>{group}</h4>{matching.filter(field=>field.group===group).map(field=><Button block type="text" key={field.key} onClick={()=>insert(formulaFieldReference(field,fields))}>{formulaFieldName(field,fields)}</Button>)}</section>)}{!matching.length&&<p>没有匹配的字段</p>}</div>
|
||||||
|
</div>;
|
||||||
|
return <div className={`chinese-formula-editor${disabled?' formula-editor-disabled':''}`}>
|
||||||
|
<div className="formula-input-toolbar">
|
||||||
|
<Popover content={chooser} trigger="click" placement="bottomLeft" open={picker&&!disabled} onOpenChange={open=>{setPicker(open);if(open)setSearch('');}}><Button size="small" disabled={disabled} icon={<PlusOutlined/>} aria-label={`${label}插入字段`} onMouseDown={event=>event.preventDefault()}>插入字段</Button></Popover>
|
||||||
|
<div className="formula-operator-buttons">{['+','−','×','÷','(',')',','].map(operator=><Button size="small" type="text" key={operator} disabled={disabled} aria-label={`插入${operator}`} onMouseDown={event=>event.preventDefault()} onClick={()=>insert(` ${operator} `)}>{operator}</Button>)}<Button size="small" type="text" disabled={disabled} onMouseDown={event=>event.preventDefault()} onClick={()=>insert('',true)}>求和</Button></div>
|
||||||
|
</div>
|
||||||
|
<Input.TextArea ref={editor} id={id} aria-label={label} aria-invalid={Boolean(check)} aria-describedby={check?`${id}-error`:undefined} value={text} disabled={disabled} rows={3} status={check&&!disabled&&!composing?'error':undefined} placeholder={fields.length > 1 ? `例如:${formulaFieldReference(fields[0],fields)} + ${formulaFieldReference(fields[1],fields)}` : '选择字段或直接输入中文公式'} onCompositionStart={()=>setComposing(true)} onCompositionEnd={()=>setComposing(false)} onChange={event=>changed(event.target.value)} onSelect={remember} onClick={remember} onKeyUp={remember} onBlur={remember}/>
|
||||||
|
{check&&!disabled&&!composing&&<div id={`${id}-error`} role="status" className="formula-input-error">{check}</div>}
|
||||||
|
</div>;
|
||||||
|
}
|
||||||
+40
-23
@@ -45,7 +45,10 @@ import type { DataWorkflowStatus } from './NoCodeDataTypes';
|
|||||||
import type { PageKey } from './QualityWorkspace';
|
import type { PageKey } from './QualityWorkspace';
|
||||||
import { readableSelectPopup } from './readableSelectPopup';
|
import { readableSelectPopup } from './readableSelectPopup';
|
||||||
import './management-alignment.css';
|
import './management-alignment.css';
|
||||||
import { TargetVersionAdmin } from './AnalyticsCompletion';
|
import { QualityTargetsPanel } from './QualityTargetsPanel';
|
||||||
|
import { METRIC_KEYS, formulaOnly, ruleChangeSummary } from './rulePresentation';
|
||||||
|
import { ruleLogicIssues } from './ruleEditing';
|
||||||
|
import './rules-workspace.css';
|
||||||
import { AnalysisReportExport, NativeAnalysisReport } from './AnalysisReportExport';
|
import { AnalysisReportExport, NativeAnalysisReport } from './AnalysisReportExport';
|
||||||
import { AiMarkdown } from './AiMarkdown';
|
import { AiMarkdown } from './AiMarkdown';
|
||||||
import { authorizeAnalysisSnapshot } from './analysisSnapshot';
|
import { authorizeAnalysisSnapshot } from './analysisSnapshot';
|
||||||
@@ -229,13 +232,23 @@ export default function ManagementPages(props: ManagementPageProps) {
|
|||||||
<ManagementPageContents {...props}/>
|
<ManagementPageContents {...props}/>
|
||||||
</CompactManagementTables.Provider>;
|
</CompactManagementTables.Provider>;
|
||||||
}
|
}
|
||||||
|
function RulesWorkspace({ user, onUnauthorized, onNavigate }: Omit<ManagementPageProps, 'page'>) {
|
||||||
|
const [section, setSection] = useState('dictionary');
|
||||||
|
const [focusMetric, setFocusMetric] = useState<{ code: string; request: number }>();
|
||||||
|
const editFormula = (code: string) => { setFocusMetric({ code: METRIC_KEYS[code] || code, request: Date.now() }); setSection('settings'); };
|
||||||
|
return <ManagementSections selectedKey={section} onSelect={setSection} items={[
|
||||||
|
{ key: 'dictionary', label: '指标说明', children: <MetricDictionaryPanel user={user} onUnauthorized={onUnauthorized} onEditFormula={editFormula} /> },
|
||||||
|
...(user.roles.some(role => ['SYSTEM_ADMIN', 'RULE_MAINTAINER'].includes(role)) ? [{ key: 'targets', label: '质量目标', children: <QualityTargetsPanel onUnauthorized={onUnauthorized} /> }] : []),
|
||||||
|
{ key: 'settings', label: '计算设置', children: <ConfigManagementPage kind="rules" user={user} onUnauthorized={onUnauthorized} onNavigate={onNavigate} focusMetric={focusMetric} /> },
|
||||||
|
]} />;
|
||||||
|
}
|
||||||
function ManagementPageContents({ page, user, onUnauthorized, onNavigate }: ManagementPageProps) {
|
function ManagementPageContents({ page, user, onUnauthorized, onNavigate }: ManagementPageProps) {
|
||||||
if (page === 'sources' || page === 'imports') return <SourcesPage onUnauthorized={onUnauthorized} user={user} />;
|
if (page === 'sources' || page === 'imports') return <SourcesPage onUnauthorized={onUnauthorized} user={user} />;
|
||||||
if (page === 'tasks') return <TasksMonitorPage user={user} onUnauthorized={onUnauthorized} />;
|
if (page === 'tasks') return <TasksMonitorPage user={user} onUnauthorized={onUnauthorized} />;
|
||||||
if (page === 'analysis') return <AnalysisPage onUnauthorized={onUnauthorized} user={user} />;
|
if (page === 'analysis') return <AnalysisPage onUnauthorized={onUnauthorized} user={user} />;
|
||||||
if (page === 'access') return <AccessPage user={user} onUnauthorized={onUnauthorized} />;
|
if (page === 'access') return <AccessPage user={user} onUnauthorized={onUnauthorized} />;
|
||||||
if (page === 'basis') return <BasisPage onUnauthorized={onUnauthorized} />;
|
if (page === 'basis') return <BasisPage onUnauthorized={onUnauthorized} />;
|
||||||
if (page === 'rules') return <ManagementSections items={[{ key: 'rules', label: '计算规则', children: <ConfigManagementPage kind={page} user={user} onUnauthorized={onUnauthorized} onNavigate={onNavigate} /> },{ key: 'dictionary', label: '指标定义', children: <MetricDictionaryPanel user={user} onUnauthorized={onUnauthorized} /> },...(user.roles.some(role => ['SYSTEM_ADMIN', 'RULE_MAINTAINER'].includes(role)) ? [{ key: 'targets', label: '目标管理', children: <TargetVersionAdmin onUnauthorized={onUnauthorized} /> }] : [])]} />;
|
if (page === 'rules') return <RulesWorkspace user={user} onUnauthorized={onUnauthorized} onNavigate={onNavigate} />;
|
||||||
if (page === 'masterData') return <ManagementSections items={[{ key: 'catalog', label: '基础名录', children: <ConfigManagementPage kind={page} user={user} onUnauthorized={onUnauthorized} onNavigate={onNavigate} /> },{ key: 'filters', label: '查询字段', children: <FilterFieldSettings canManage={user.roles.some(role => ['SYSTEM_ADMIN','DATA_MAINTAINER'].includes(role))} onUnauthorized={onUnauthorized} /> }]} />;
|
if (page === 'masterData') return <ManagementSections items={[{ key: 'catalog', label: '基础名录', children: <ConfigManagementPage kind={page} user={user} onUnauthorized={onUnauthorized} onNavigate={onNavigate} /> },{ key: 'filters', label: '查询字段', children: <FilterFieldSettings canManage={user.roles.some(role => ['SYSTEM_ADMIN','DATA_MAINTAINER'].includes(role))} onUnauthorized={onUnauthorized} /> }]} />;
|
||||||
if (page === 'mappings') return <MappingMaintenancePage user={user} onUnauthorized={onUnauthorized} onNavigate={onNavigate} />;
|
if (page === 'mappings') return <MappingMaintenancePage user={user} onUnauthorized={onUnauthorized} onNavigate={onNavigate} />;
|
||||||
const resource: Record<string, { endpoint: 'imports' | 'tasks'; title: string; subtitle: string }> = {
|
const resource: Record<string, { endpoint: 'imports' | 'tasks'; title: string; subtitle: string }> = {
|
||||||
@@ -401,7 +414,7 @@ function ruleDisplayName(value: unknown): string {
|
|||||||
|
|
||||||
type PublishedConfigNames = Pick<OptionsResponse, 'departments' | 'groups' | 'products' | 'projectGroups'> & { groupDepartments?: Record<string, string | null> };
|
type PublishedConfigNames = Pick<OptionsResponse, 'departments' | 'groups' | 'products' | 'projectGroups'> & { groupDepartments?: Record<string, string | null> };
|
||||||
|
|
||||||
function ConfigManagementPage({ kind, user, onUnauthorized, onNavigate, extraSections }: { extraSections?: { key: string; label: string; children: React.ReactNode }[]; kind: 'rules' | 'mappings' | 'masterData'; user: AuthUser; onUnauthorized: (error: unknown) => boolean; onNavigate: (page: PageKey) => void }) {
|
function ConfigManagementPage({ kind, user, onUnauthorized, onNavigate, extraSections, focusMetric }: { focusMetric?: { code: string; request: number }; extraSections?: { key: string; label: string; children: React.ReactNode }[]; kind: 'rules' | 'mappings' | 'masterData'; user: AuthUser; onUnauthorized: (error: unknown) => boolean; onNavigate: (page: PageKey) => void }) {
|
||||||
const { message } = App.useApp();
|
const { message } = App.useApp();
|
||||||
const { active: pageActive } = usePageCache();
|
const { active: pageActive } = usePageCache();
|
||||||
const [items, setItems] = useState<Record<string, unknown>[]>([]);
|
const [items, setItems] = useState<Record<string, unknown>[]>([]);
|
||||||
@@ -427,6 +440,7 @@ function ConfigManagementPage({ kind, user, onUnauthorized, onNavigate, extraSec
|
|||||||
const classificationUpdates=useClassificationQueue(kind==='mappings'?String(user.id):'inactive-'+kind);
|
const classificationUpdates=useClassificationQueue(kind==='mappings'?String(user.id):'inactive-'+kind);
|
||||||
const [ruleSchema, setRuleSchema] = useState<Record<string, unknown> | null>(null);
|
const [ruleSchema, setRuleSchema] = useState<Record<string, unknown> | null>(null);
|
||||||
const [ruleSchemaError, setRuleSchemaError] = useState('');
|
const [ruleSchemaError, setRuleSchemaError] = useState('');
|
||||||
|
const [ruleBaseline, setRuleBaseline] = useState<ConfigDefinition>({});
|
||||||
const [publishedNames, setPublishedNames] = useState<PublishedConfigNames | null>(null);
|
const [publishedNames, setPublishedNames] = useState<PublishedConfigNames | null>(null);
|
||||||
const [matchMetadata,setMatchMetadata]=useState<Record<string,unknown>|null>(null);
|
const [matchMetadata,setMatchMetadata]=useState<Record<string,unknown>|null>(null);
|
||||||
const [differenceItem, setDifferenceItem] = useState<Record<string, unknown> | null>(null);
|
const [differenceItem, setDifferenceItem] = useState<Record<string, unknown> | null>(null);
|
||||||
@@ -488,6 +502,7 @@ function ConfigManagementPage({ kind, user, onUnauthorized, onNavigate, extraSec
|
|||||||
const definitionKey=JSON.stringify([kind,active?.id??fallback?.id,definition]);
|
const definitionKey=JSON.stringify([kind,active?.id??fallback?.id,definition]);
|
||||||
if (definition && typeof definition === 'object' && loadedDefinitionKey.current!==definitionKey) {loadedDefinitionKey.current=definitionKey;const serialized=JSON.stringify(definition),prior=loadedDefinition.current;setDraftDefinition(previous=>!prior||JSON.stringify(previous)===prior?JSON.parse(serialized) as ConfigDefinition:previous);loadedDefinition.current=serialized;}
|
if (definition && typeof definition === 'object' && loadedDefinitionKey.current!==definitionKey) {loadedDefinitionKey.current=definitionKey;const serialized=JSON.stringify(definition),prior=loadedDefinition.current;setDraftDefinition(previous=>!prior||JSON.stringify(previous)===prior?JSON.parse(serialized) as ConfigDefinition:previous);loadedDefinition.current=serialized;}
|
||||||
const metadata = items.find(row => String(row.id) === String(active?.id)) ?? fallback;
|
const metadata = items.find(row => String(row.id) === String(active?.id)) ?? fallback;
|
||||||
|
if (!drafting && isRules) setRuleBaseline(JSON.parse(JSON.stringify(definition || {})) as ConfigDefinition);
|
||||||
if (!drafting) form.setFieldsValue({ name: testMode ? currentConfigurationName(active?.name ?? metadata?.name, metadata?.createdAt) : isRules ? ruleDisplayName(active?.name || fallback?.name || '测试计算规则') : String(active?.name || fallback?.name || '测试基础数据与对应关系'), description: isRules ? readableRuleDescription(active?.description || fallback?.description) : String(active?.description || fallback?.description || '') });
|
if (!drafting) form.setFieldsValue({ name: testMode ? currentConfigurationName(active?.name ?? metadata?.name, metadata?.createdAt) : isRules ? ruleDisplayName(active?.name || fallback?.name || '测试计算规则') : String(active?.name || fallback?.name || '测试基础数据与对应关系'), description: isRules ? readableRuleDescription(active?.description || fallback?.description) : String(active?.description || fallback?.description || '') });
|
||||||
}, [workflowStatus, items, kind, isRules, testMode, ruleSchema, drafting, form]);
|
}, [workflowStatus, items, kind, isRules, testMode, ruleSchema, drafting, form]);
|
||||||
|
|
||||||
@@ -613,6 +628,10 @@ function ConfigManagementPage({ kind, user, onUnauthorized, onNavigate, extraSec
|
|||||||
if (actionLock.current) return; actionLock.current = true;
|
if (actionLock.current) return; actionLock.current = true;
|
||||||
try {
|
try {
|
||||||
await form.validateFields();
|
await form.validateFields();
|
||||||
|
if (isRules && ruleSchema) {
|
||||||
|
const issues = ruleLogicIssues(draftDefinition, ruleSchema);
|
||||||
|
if (issues.length) throw new Error(issues[0].message);
|
||||||
|
}
|
||||||
const values = form.getFieldsValue(true);
|
const values = form.getFieldsValue(true);
|
||||||
await workflowOperation.start(() => api.applyDataWorkflow({ kind: isRules ? 'rule' : 'mapping', name: configurationDateTime(new Date()), definition: draftDefinition, expectedCurrentReleaseId: workflowStatus?.currentReleaseId ?? null, ...(values.description?.trim() ? { description: values.description.trim() } : {}) }));
|
await workflowOperation.start(() => api.applyDataWorkflow({ kind: isRules ? 'rule' : 'mapping', name: configurationDateTime(new Date()), definition: draftDefinition, expectedCurrentReleaseId: workflowStatus?.currentReleaseId ?? null, ...(values.description?.trim() ? { description: values.description.trim() } : {}) }));
|
||||||
} catch (value) {
|
} catch (value) {
|
||||||
@@ -643,13 +662,14 @@ function ConfigManagementPage({ kind, user, onUnauthorized, onNavigate, extraSec
|
|||||||
<div className="completion-actions"><ConfigurationWorkbookActions value={draftDefinition} onChange={setDraftDefinition} scope={mode==='rules'?'rules':mode==='catalog'?'catalogs':'all'} label={mode==='rules'?'计算规则':mode==='catalog'?'基础名录':'对应关系配置'} defaults={Array.isArray(matchMetadata?.defaultRules)?matchMetadata.defaultRules:[]} readOnly={!canApplyWorkflow} disabled={loading||(isRules?!ruleSchema:!matchMetadata)} validate={isRules?undefined:validateStructuredMappingDefinition} whole /></div>
|
<div className="completion-actions"><ConfigurationWorkbookActions value={draftDefinition} onChange={setDraftDefinition} scope={mode==='rules'?'rules':mode==='catalog'?'catalogs':'all'} label={mode==='rules'?'计算规则':mode==='catalog'?'基础名录':'对应关系配置'} defaults={Array.isArray(matchMetadata?.defaultRules)?matchMetadata.defaultRules:[]} readOnly={!canApplyWorkflow} disabled={loading||(isRules?!ruleSchema:!matchMetadata)} validate={isRules?undefined:validateStructuredMappingDefinition} whole /></div>
|
||||||
<Button icon={<ReloadOutlined />} onClick={() => { void load(); void refreshWorkflowStatus(); void loadEditorSupport(); }}>刷新</Button>
|
<Button icon={<ReloadOutlined />} onClick={() => { void load(); void refreshWorkflowStatus(); void loadEditorSupport(); }}>刷新</Button>
|
||||||
</div>
|
</div>
|
||||||
{mode === 'rules' && <Form form={form} layout="vertical"><div className="structured-config-form-grid"><Form.Item name="name" label="配置名称"><Input readOnly /></Form.Item><Form.Item name="description" label="说明(可选)"><Input disabled={!canApplyWorkflow} maxLength={1000} /></Form.Item></div></Form>}
|
{mode === 'rules' && <Form form={form} component={false}><Form.Item name="name" hidden><Input readOnly /></Form.Item><Form.Item name="description" hidden><Input readOnly /></Form.Item></Form>}
|
||||||
{mode === 'rules' ? canApplyWorkflow ? <RuleDefinitionEditor value={draftDefinition} onChange={setDraftDefinition} schema={ruleSchema} schemaError={ruleSchemaError} showWorkbookActions={false} /> : <RuleContents value={draftDefinition} />
|
{mode === 'rules' ? <RuleDefinitionEditor value={draftDefinition} onChange={setDraftDefinition} schema={ruleSchema} schemaError={ruleSchemaError} showWorkbookActions={false} focusMetric={focusMetric} readOnly={!canApplyWorkflow} />
|
||||||
: mode === 'catalog' ? <MasterDataDefinitionEditor value={draftDefinition} onChange={setDraftDefinition} publishedNames={publishedNames ?? undefined} simplified readOnly={!canApplyWorkflow} />
|
: mode === 'catalog' ? <MasterDataDefinitionEditor value={draftDefinition} onChange={setDraftDefinition} publishedNames={publishedNames ?? undefined} simplified readOnly={!canApplyWorkflow} />
|
||||||
: mode === 'lookups' ? <MappingDefinitionEditor value={draftDefinition} onChange={setDraftDefinition} simplified readOnly={!canApplyWorkflow} />
|
: mode === 'lookups' ? <MappingDefinitionEditor value={draftDefinition} onChange={setDraftDefinition} simplified readOnly={!canApplyWorkflow} />
|
||||||
: <MatchRulesDefinitionEditor value={draftDefinition} onChange={setDraftDefinition} metadata={matchMetadata??workflowStatus} readOnly={!canApplyWorkflow} />}
|
: <MatchRulesDefinitionEditor value={draftDefinition} onChange={setDraftDefinition} metadata={matchMetadata??workflowStatus} readOnly={!canApplyWorkflow} />}
|
||||||
{!isRules && validateStructuredMappingDefinition(draftDefinition, publishedNames?.groupDepartments).length > 0 && <Alert showIcon type="warning" message="有名录引用需要留意" description={<ul className="structured-config-error-list">{validateStructuredMappingDefinition(draftDefinition, publishedNames?.groupDepartments).slice(0,12).map((issue,index)=><li key={index}>{issue}</li>)}</ul>} />}
|
{!isRules && validateStructuredMappingDefinition(draftDefinition, publishedNames?.groupDepartments).length > 0 && <Alert showIcon type="warning" message="有名录引用需要留意" description={<ul className="structured-config-error-list">{validateStructuredMappingDefinition(draftDefinition, publishedNames?.groupDepartments).slice(0,12).map((issue,index)=><li key={index}>{issue}</li>)}</ul>} />}
|
||||||
{canApplyWorkflow && <div className="nc-simple-save-row"><span>保存后检查配置并更新报表。</span><Button type="primary" size="large" disabled={workflowOperation.busy || classificationBusy || (isRules && !ruleSchema)} loading={workflowOperation.busy} onClick={() => void applyCurrent()}>保存并更新报表</Button></div>}
|
{isRules && ruleChangeSummary(ruleBaseline, draftDefinition).length > 0 && <div className="rule-pending-changes"><strong>本次变更</strong><span>{ruleChangeSummary(ruleBaseline, draftDefinition).join(';')}</span></div>}
|
||||||
|
{canApplyWorkflow && <div className="nc-simple-save-row"><span>{isRules ? '检查规则 → 重新计算 → 更新报表' : '保存后检查配置并更新报表。'}</span><Button type="primary" size="large" disabled={workflowOperation.busy || classificationBusy || (isRules && !ruleSchema)} loading={workflowOperation.busy} onClick={() => void applyCurrent()}>保存并更新报表</Button></div>}
|
||||||
</section>
|
</section>
|
||||||
</div>;
|
</div>;
|
||||||
if (kind === 'masterData') return <><Form form={form} component={false} />{editor('catalog')}</>;
|
if (kind === 'masterData') return <><Form form={form} component={false} />{editor('catalog')}</>;
|
||||||
@@ -811,7 +831,7 @@ function MappingIssueResolutionPanel({ onUnauthorized, onEdit }: { onUnauthorize
|
|||||||
</div>;
|
</div>;
|
||||||
}
|
}
|
||||||
|
|
||||||
function MetricDictionaryPanel({ user, onUnauthorized }: { user: AuthUser; onUnauthorized: (error: unknown) => boolean }) {
|
function MetricDictionaryPanel({ user, onUnauthorized, onEditFormula }: { user: AuthUser; onUnauthorized: (error: unknown) => boolean; onEditFormula?: (code: string) => void }) {
|
||||||
const { message } = App.useApp();
|
const { message } = App.useApp();
|
||||||
const { active } = usePageCache();
|
const { active } = usePageCache();
|
||||||
const [items, setItems] = useState<Record<string, unknown>[]>([]);
|
const [items, setItems] = useState<Record<string, unknown>[]>([]);
|
||||||
@@ -853,7 +873,7 @@ function MetricDictionaryPanel({ user, onUnauthorized }: { user: AuthUser; onUna
|
|||||||
reason: values.reason.trim(),
|
reason: values.reason.trim(),
|
||||||
expectedRowVersion: Number(editing.rowVersion || 0),
|
expectedRowVersion: Number(editing.rowVersion || 0),
|
||||||
});
|
});
|
||||||
message.success('术语名称、别名和说明已保存'); setEditing(null); form.resetFields(); await load();
|
message.success('指标说明已保存'); setEditing(null); form.resetFields(); await load();
|
||||||
} catch (value) {
|
} catch (value) {
|
||||||
if (value && typeof value === 'object' && 'errorFields' in value) return;
|
if (value && typeof value === 'object' && 'errorFields' in value) return;
|
||||||
if (!onUnauthorized(value)) message.error(apiMessage(value));
|
if (!onUnauthorized(value)) message.error(apiMessage(value));
|
||||||
@@ -862,33 +882,30 @@ function MetricDictionaryPanel({ user, onUnauthorized }: { user: AuthUser; onUna
|
|||||||
};
|
};
|
||||||
|
|
||||||
const columns: ColumnsType<Record<string, unknown>> = [
|
const columns: ColumnsType<Record<string, unknown>> = [
|
||||||
{ title: '术语名称', dataIndex: 'name', key: 'name', width: 160 },
|
{ title: '指标', dataIndex: 'name', key: 'name', width: 190 },
|
||||||
{ title: '说明', dataIndex: 'description', key: 'description', width: 200, render: value => readableValue(readableRuleDescription(value)) },
|
{ title: '当前计算公式', key: 'formula', width: 330, render: (_, row) => <div style={{ whiteSpace: 'normal', overflowWrap: 'anywhere', lineHeight: 1.7 }}>{formulaOnly(currentMetricFormula(row))}</div> },
|
||||||
{ title: '单位', dataIndex: 'unit', key: 'unit', width: 55, render: value => value === 'RATE' ? '%' : toText(value) },
|
{ title: '计算口径', dataIndex: 'description', key: 'description', width: 280, render: value => readableValue(readableRuleDescription(value)) },
|
||||||
{ title: '适用范围', dataIndex: 'dimensions', key: 'dimensions', width: 130, render: value => <BusinessValue value={value} field="dimensions" /> },
|
{ title: '操作', key: 'actions', width: 220, render: (_, row) => <span className="task-actions"><Button type="link" onClick={() => setInspecting(row)}>查看说明</Button>{canManage && <><Button type="link" onClick={() => openEditor(row)}>编辑说明</Button>{onEditFormula && <Button type="link" onClick={() => onEditFormula(String(row.code))}>修改公式</Button>}</>}</span> },
|
||||||
{ title: '当前生效公式', key: 'formula', width: 420, render: (_, row) => <div style={{ whiteSpace: 'normal', overflowWrap: 'anywhere', lineHeight: 1.7 }}>{currentMetricFormula(row)}</div> },
|
|
||||||
{ title: '状态', dataIndex: 'enabled', key: 'enabled', width: 70, render: value => <Tag color={value === true ? 'green' : 'default'}>{value === true ? '启用' : value === false ? '停用' : '—'}</Tag> },
|
|
||||||
{ title: '操作', key: 'actions', fixed: 'right', width: 100, render: (_, row) => <span className="task-actions"><Button type="link" onClick={() => setInspecting(row)}>查看</Button>{canManage && <Button type="link" onClick={() => openEditor(row)}>编辑术语</Button>}</span> },
|
|
||||||
];
|
];
|
||||||
useMaintenanceRefresh(load);
|
useMaintenanceRefresh(load);
|
||||||
return <section className="panel section-panel completion-tools">
|
return <CompactManagementTables.Provider value={true}><section className="panel section-panel completion-tools metric-explanation-panel">
|
||||||
<div className="completion-panel-heading"><div><strong>指标术语字典</strong><span>维护展示名称与别名;计算公式在上方计算规则中维护</span></div><Button icon={<ReloadOutlined />} onClick={() => void load()}>刷新字典</Button></div>
|
<div className="completion-panel-heading"><div><strong>当前生效指标</strong></div><Button icon={<ReloadOutlined />} onClick={() => void load()}>刷新</Button></div>
|
||||||
{dictionaryError && <Alert showIcon type="error" message="术语字典读取失败" description={loaded ? `${dictionaryError};以下为上次成功读取的结果。` : dictionaryError} action={!loaded ? <Button size="small" onClick={() => void load()}>重试</Button> : undefined} />}
|
{dictionaryError && <Alert showIcon type="error" message="术语字典读取失败" description={loaded ? `${dictionaryError};以下为上次成功读取的结果。` : dictionaryError} action={!loaded ? <Button size="small" onClick={() => void load()}>重试</Button> : undefined} />}
|
||||||
{loading && !loaded ? <div className="loading-panel"><Spin />读取术语定义…</div> : loaded ? items.length ? <div className="resource-table"><Table size="small" bordered columns={columns} dataSource={items} rowKey={row => String(row.code)} pagination={{ pageSize: TABLE_PAGE_SIZE, showSizeChanger: false }} scroll={{ x: 1100 }} /></div> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="暂无指标术语" /> : null}
|
{loading && !loaded ? <div className="loading-panel"><Spin />读取指标说明…</div> : loaded ? items.length ? <div className="resource-table"><Table size="small" bordered columns={columns} dataSource={items} rowKey={row => String(row.code)} pagination={{ pageSize: TABLE_PAGE_SIZE, showSizeChanger: false }} scroll={{ x: 1100 }} /></div> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="暂无指标说明" /> : null}
|
||||||
<Alert showIcon type="info" message="术语编辑不改变计算规则" description="公式来自当前查询数据所绑定的计算规则;编辑术语不会改变计算结果。" />
|
|
||||||
<Modal className="management-modal" open={Boolean(editing)} title={`编辑术语 · ${String(editing?.code || '')}`} okText="保存术语" confirmLoading={saving} onCancel={() => { setEditing(null); form.resetFields(); }} onOk={() => void save()}>
|
<Modal className="management-modal" open={Boolean(editing)} title={`编辑说明 · ${String(editing?.name || '')}`} okText="保存说明" confirmLoading={saving} onCancel={() => { setEditing(null); form.resetFields(); }} onOk={() => void save()}>
|
||||||
<Form form={form} layout="vertical">
|
<Form form={form} layout="vertical">
|
||||||
<Form.Item name="name" label="展示名称" rules={[{ required: true, whitespace: true, message: '请填写展示名称' }]}><Input maxLength={160} /></Form.Item>
|
<Form.Item name="name" label="展示名称" rules={[{ required: true, whitespace: true, message: '请填写展示名称' }]}><Input maxLength={160} /></Form.Item>
|
||||||
<Form.Item name="aliases" label="别名" extra="每行一个,也可用逗号分隔"><Input.TextArea rows={4} maxLength={1000} /></Form.Item>
|
<Form.Item name="aliases" label="别名" extra="每行一个,也可用逗号分隔"><Input.TextArea rows={4} maxLength={1000} /></Form.Item>
|
||||||
<Form.Item name="description" label="术语说明"><Input.TextArea rows={3} maxLength={1000} /></Form.Item>
|
<Form.Item name="description" label="指标说明"><Input.TextArea rows={3} maxLength={1000} /></Form.Item>
|
||||||
<Form.Item name="reason" label="修改原因" rules={[{ required: true, whitespace: true, message: '请填写修改原因' }]}><Input.TextArea rows={2} maxLength={300} /></Form.Item>
|
<Form.Item name="reason" label="修改原因" rules={[{ required: true, whitespace: true, message: '请填写修改原因' }]}><Input.TextArea rows={2} maxLength={300} /></Form.Item>
|
||||||
</Form>
|
</Form>
|
||||||
<Alert showIcon type="info" message="当前生效公式" description={editing ? currentMetricFormula(editing) : undefined} />
|
<Alert showIcon type="info" message="当前生效公式" description={editing ? currentMetricFormula(editing) : undefined} />
|
||||||
</Modal>
|
</Modal>
|
||||||
<Drawer className="management-drawer" open={Boolean(inspecting)} title={`指标术语 · ${String(inspecting?.name || '')}`} width={Math.min(760, window.innerWidth)} onClose={() => setInspecting(null)}>
|
<Drawer className="management-drawer" open={Boolean(inspecting)} title={`指标说明 · ${String(inspecting?.name || '')}`} width={Math.min(760, window.innerWidth)} onClose={() => setInspecting(null)}>
|
||||||
{inspecting && <dl className="completion-definition-list"><dt>名称</dt><dd>{toText(inspecting.name)}</dd><dt>别名</dt><dd>{Array.isArray(inspecting.aliases) ? inspecting.aliases.map(String).join('、') : toText(inspecting.aliases)}</dd><dt>说明</dt><dd>{toText(readableRuleDescription(inspecting.description))}</dd><dt>单位</dt><dd>{inspecting.unit === 'RATE' ? '%' : toText(inspecting.unit)}</dd><dt>适用维度</dt><dd><BusinessValue value={inspecting.dimensions} field="dimensions" /></dd><dt>当前生效公式</dt><dd>{currentMetricFormula(inspecting)}</dd><dt>状态</dt><dd><BusinessValue value={inspecting.enabled} /></dd></dl>}
|
{inspecting && <dl className="completion-definition-list"><dt>名称</dt><dd>{toText(inspecting.name)}</dd><dt>别名</dt><dd>{Array.isArray(inspecting.aliases) ? inspecting.aliases.map(String).join('、') : toText(inspecting.aliases)}</dd><dt>说明</dt><dd>{toText(readableRuleDescription(inspecting.description))}</dd><dt>单位</dt><dd>{inspecting.unit === 'RATE' ? '%' : toText(inspecting.unit)}</dd><dt>适用维度</dt><dd><BusinessValue value={inspecting.dimensions} field="dimensions" /></dd><dt>当前生效公式</dt><dd>{currentMetricFormula(inspecting)}</dd><dt>状态</dt><dd><BusinessValue value={inspecting.enabled} /></dd></dl>}
|
||||||
</Drawer>
|
</Drawer>
|
||||||
</section>;
|
</section></CompactManagementTables.Provider>;
|
||||||
}
|
}
|
||||||
|
|
||||||
function TaskTable({ items, importOnly, user, onUnauthorized, onRefresh }: { items: Record<string, unknown>[]; importOnly: boolean; user: AuthUser; onUnauthorized: (error: unknown) => boolean; onRefresh: () => void }) {
|
function TaskTable({ items, importOnly, user, onUnauthorized, onRefresh }: { items: Record<string, unknown>[]; importOnly: boolean; user: AuthUser; onUnauthorized: (error: unknown) => boolean; onRefresh: () => void }) {
|
||||||
|
|||||||
@@ -1,12 +1,14 @@
|
|||||||
import { Tabs } from 'antd';
|
import { Tabs } from 'antd';
|
||||||
import { useState, type ReactNode } from 'react';
|
import { useEffect, useState, type ReactNode } from 'react';
|
||||||
import { PageCacheContext, usePageCache } from './pageCache';
|
import { PageCacheContext, usePageCache } from './pageCache';
|
||||||
|
|
||||||
export function ManagementSections({ items, initialKey, onSelect }: { items: { key: string; label: ReactNode; children: ReactNode }[]; initialKey?: string; onSelect?: (key: string) => void }) {
|
export function ManagementSections({ items, initialKey, selectedKey, onSelect }: { items: { key: string; label: ReactNode; children: ReactNode }[]; initialKey?: string; selectedKey?: string; onSelect?: (key: string) => void }) {
|
||||||
const cache = usePageCache();
|
const cache = usePageCache();
|
||||||
const initialSelected = initialKey && items.some(item => item.key === initialKey) ? initialKey : items[0]?.key;
|
const initialSelected = initialKey && items.some(item => item.key === initialKey) ? initialKey : items[0]?.key;
|
||||||
const [selected, setSelected] = useState(initialSelected);
|
const [selected, setSelected] = useState(initialSelected);
|
||||||
const activeKey = items.some(item => item.key === selected) ? selected : items[0]?.key;
|
const requested = selectedKey ?? selected;
|
||||||
|
const activeKey = items.some(item => item.key === requested) ? requested : items[0]?.key;
|
||||||
const [visited, setVisited] = useState(() => new Set(activeKey ? [activeKey] : []));
|
const [visited, setVisited] = useState(() => new Set(activeKey ? [activeKey] : []));
|
||||||
return <Tabs className="management-sections" activeKey={activeKey} destroyOnHidden={false} onChange={key => { setSelected(key); setVisited(previous => new Set(previous).add(key)); onSelect?.(key); window.scrollTo({ top: 0 }); }} items={items.map(item => ({ ...item, children: <PageCacheContext.Provider value={{ ...cache, active: cache.active && item.key === activeKey }}>{visited.has(item.key) ? item.children : null}</PageCacheContext.Provider> }))} />;
|
useEffect(() => { if (activeKey) setVisited(previous => previous.has(activeKey) ? previous : new Set(previous).add(activeKey)); }, [activeKey]);
|
||||||
|
return <Tabs className="management-sections" activeKey={activeKey} destroyOnHidden={false} onChange={key => { setSelected(key); setVisited(previous => new Set(previous).add(key)); onSelect?.(key); window.scrollTo({ top: 0 }); }} items={items.map(item => ({ ...item, children: <PageCacheContext.Provider value={{ ...cache, active: cache.active && item.key === activeKey }}>{visited.has(item.key) || item.key === activeKey ? item.children : null}</PageCacheContext.Provider> }))} />;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -25,6 +25,7 @@ function compactColumns<T extends object>(columns: ColumnsType<T>): ColumnsType<
|
|||||||
type QualityTableProps<T extends object> = TableProps<T> & {
|
type QualityTableProps<T extends object> = TableProps<T> & {
|
||||||
/** Offset for tables whose page is controlled outside Ant Design. */
|
/** Offset for tables whose page is controlled outside Ant Design. */
|
||||||
indexOffset?: number;
|
indexOffset?: number;
|
||||||
|
showRowNumbers?: boolean;
|
||||||
};
|
};
|
||||||
|
|
||||||
export function QualityTable<T extends object>({
|
export function QualityTable<T extends object>({
|
||||||
@@ -32,6 +33,7 @@ export function QualityTable<T extends object>({
|
|||||||
dataSource,
|
dataSource,
|
||||||
pagination,
|
pagination,
|
||||||
indexOffset = 0,
|
indexOffset = 0,
|
||||||
|
showRowNumbers = true,
|
||||||
className,
|
className,
|
||||||
size = 'small',
|
size = 'small',
|
||||||
onChange,
|
onChange,
|
||||||
@@ -64,7 +66,7 @@ export function QualityTable<T extends object>({
|
|||||||
{...props}
|
{...props}
|
||||||
className={['quality-table', className].filter(Boolean).join(' ')}
|
className={['quality-table', className].filter(Boolean).join(' ')}
|
||||||
tableLayout={props.tableLayout ?? (compact ? 'fixed' : undefined)}
|
tableLayout={props.tableLayout ?? (compact ? 'fixed' : undefined)}
|
||||||
columns={[indexColumn, ...(compact ? compactColumns(columns ?? []) : columns ?? [])]}
|
columns={[...(showRowNumbers ? [indexColumn] : []), ...(compact ? compactColumns(columns ?? []) : columns ?? [])]}
|
||||||
dataSource={dataSource}
|
dataSource={dataSource}
|
||||||
pagination={pagination === false ? false : { defaultPageSize: 15, pageSizeOptions: ['15', '30', '50', '100'], ...pageConfig }}
|
pagination={pagination === false ? false : { defaultPageSize: 15, pageSizeOptions: ['15', '30', '50', '100'], ...pageConfig }}
|
||||||
onChange={handleChange}
|
onChange={handleChange}
|
||||||
|
|||||||
@@ -0,0 +1,95 @@
|
|||||||
|
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||||
|
import { Alert, App, Button, Checkbox, Empty, Form, Input, InputNumber, Modal, Popconfirm, Select, Spin } from 'antd';
|
||||||
|
import { PlusOutlined, ReloadOutlined } from '@ant-design/icons';
|
||||||
|
import { CompactManagementTables, QualityTable as Table } from './QualityTable';
|
||||||
|
import { ApiError, api } from './api';
|
||||||
|
import { METRIC_NAMES, matchingTarget, ruleObject as obj, ruleList, type RuleDefinition as Row } from './rulePresentation';
|
||||||
|
import { readableSelectPopup } from './readableSelectPopup';
|
||||||
|
|
||||||
|
const DIMENSIONS=['department','group','product','projectGroup'] as const;
|
||||||
|
const dimensionName={department:'产业部',group:'业务分组',product:'产品',projectGroup:'项目组'};
|
||||||
|
const percent=(value:unknown)=>typeof value==='number'&&Number.isFinite(value)?`${(value*100).toFixed(2)}%`:'未设置';
|
||||||
|
const dimensions=(v:unknown)=>Object.fromEntries(DIMENSIONS.flatMap(key=>obj(v)[key]?[ [key,String(obj(v)[key])] ]:[]));
|
||||||
|
const identity=(row:Row)=>JSON.stringify([row.metric,row.year,...DIMENSIONS.map(key=>String(obj(row.dimensions)[key]||''))]);
|
||||||
|
const targetInput=(row:Row)=>Object.fromEntries(['metric','periodType','year','periodIndex','dimensions','value','unit','source','note'].filter(key=>row[key]!==undefined).map(key=>[key,row[key]]));
|
||||||
|
type TargetForm={year:number;metric:string;scope:string;department?:string;group?:string;product?:string;projectGroup?:string;value:number|null;inherit:boolean};
|
||||||
|
|
||||||
|
export function QualityTargetsPanel({onUnauthorized}:{onUnauthorized:(error:unknown)=>boolean}){
|
||||||
|
const {message}=App.useApp();const [version,setVersion]=useState<Row|null>(null),[targets,setTargets]=useState<Row[]>([]),[references,setReferences]=useState<Row>({});
|
||||||
|
const [loading,setLoading]=useState(true),[error,setError]=useState(''),[saving,setSaving]=useState(false),[editing,setEditing]=useState<Row|null>(null);
|
||||||
|
const [year,setYear]=useState(new Date().getFullYear()),[metric,setMetric]=useState('COMPOSITE_RATE');
|
||||||
|
const [form]=Form.useForm<TargetForm>();const scope=Form.useWatch('scope',form),inherit=Form.useWatch('inherit',form),department=Form.useWatch('department',form);
|
||||||
|
const saveLock=useRef(false);
|
||||||
|
const selectedYear=Form.useWatch('year',form),selectedMetric=Form.useWatch('metric',form);
|
||||||
|
const load=useCallback(async()=>{
|
||||||
|
setLoading(true);setError('');
|
||||||
|
try{
|
||||||
|
const list=await api.targetVersions();const active=list.items.find(row=>String(row.status).toUpperCase()==='ACTIVE');
|
||||||
|
if(!active){setVersion(null);setTargets([]);return;}
|
||||||
|
const [detail,names]=await Promise.all([api.targetVersion(String(active.id)),api.referenceNames()]);
|
||||||
|
setVersion(obj(detail.version||active));setTargets(ruleList(detail.targets));setReferences(names);
|
||||||
|
}catch(e){if(!onUnauthorized(e))setError(e instanceof Error?e.message:'目标读取失败');}finally{setLoading(false);}
|
||||||
|
},[onUnauthorized]);
|
||||||
|
useEffect(()=>{void load();},[load]);
|
||||||
|
const annual=targets.filter(row=>String(row.periodType).toUpperCase()==='YEAR');
|
||||||
|
const years=[...new Set([new Date().getFullYear(),...annual.map(row=>Number(row.year))])].sort((a,b)=>a-b);
|
||||||
|
const overall=annual.find(row=>row.metric===metric&&row.year===year&&!Object.keys(dimensions(row.dimensions)).length);
|
||||||
|
const tableRows:Row[]=[];
|
||||||
|
if(version){
|
||||||
|
tableRows.push({...overall,metric,year,dimensions:{},key:'overall',scopeName:'总体',inherited:false,displayValue:overall?.value,exists:Boolean(overall)});
|
||||||
|
const scoped=annual.filter(row=>row.metric===metric&&row.year===year&&Object.keys(dimensions(row.dimensions)).length);
|
||||||
|
scoped.forEach(row=>tableRows.push({...row,key:identity(row),scopeName:Object.values(dimensions(row.dimensions)).join(' / '),inherited:false,displayValue:row.value,exists:true}));
|
||||||
|
const refGroups=obj(references.groupDepartments);
|
||||||
|
const known=[...(Array.isArray(references.departments)?references.departments as string[]:[]).filter(name=>!['美洲产业部','欧洲产业部','欧洲磁钢'].includes(name)).map(name=>({department:name})),...(Array.isArray(references.groups)?references.groups as string[]:[]).map(name=>({...refGroups[name]?{department:String(refGroups[name])}:{},group:name}))];
|
||||||
|
for(const d of known){
|
||||||
|
const item={metric,year,dimensions:d};if(scoped.some(row=>identity(row)===identity(item)))continue;
|
||||||
|
const matched=matchingTarget(annual.filter(row=>row.metric===metric&&row.year===year),d);
|
||||||
|
const parentName=Object.values(dimensions(matched?.dimensions)).join(' / ');
|
||||||
|
tableRows.push({...item,key:identity(item),scopeName:Object.values(d).join(' / '),inherited:true,displayValue:matched?.value,inheritSource:parentName?`沿用${parentName}目标`:'沿用总体目标',exists:false});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const open=(row?:Row)=>{
|
||||||
|
const d=dimensions(row?.dimensions);setEditing(row||{newRecord:true});
|
||||||
|
form.setFieldsValue({year:Number(row?.year||year),metric:String(row?.metric||metric),scope:Object.keys(d).length?'scope':'overall',...Object.fromEntries(DIMENSIONS.map(key=>[key,d[key]||undefined])),inherit:Boolean(row?.inherited),value:typeof row?.displayValue==='number'?row.displayValue*100:typeof row?.value==='number'?row.value*100:null});
|
||||||
|
};
|
||||||
|
const persist=async(next:Row[])=>{
|
||||||
|
if(!version||saveLock.current)return false;saveLock.current=true;setSaving(true);
|
||||||
|
try{await api.updateCurrentTargets({targets:next.map(targetInput),expectedRowVersion:Number(version.rowVersion||0)});message.success('目标已更新');setEditing(null);await load();return true;}
|
||||||
|
catch(e){if(!onUnauthorized(e))message.error(e instanceof ApiError&&e.status===409?'目标已被其他人修改,请刷新后核对':e instanceof Error?e.message:'目标保存失败');return false;}
|
||||||
|
finally{saveLock.current=false;setSaving(false);}
|
||||||
|
};
|
||||||
|
const save=async()=>{
|
||||||
|
try{
|
||||||
|
const f=await form.validateFields();const d=f.scope==='overall'?{}:dimensions(f);
|
||||||
|
if(f.scope==='scope'&&!Object.keys(d).length){message.error('请选择至少一个适用范围');return;}
|
||||||
|
const candidate={metric:f.metric,year:f.year,dimensions:d};const oldKey=editing&&!editing.newRecord&&editing.exists?identity(editing):null;const key=identity(candidate);
|
||||||
|
if(annual.some(row=>identity(row)===key&&identity(row)!==oldKey)&&!(editing?.inherited&&identity(editing)===key)){message.error('该年度、指标及范围已有目标,请编辑已有记录');return;}
|
||||||
|
let next=targets.filter(row=>!oldKey||String(row.periodType).toUpperCase()!=='YEAR'||identity(row)!==oldKey);
|
||||||
|
if(!(f.scope==='scope'&&f.inherit)){
|
||||||
|
const prior=oldKey?annual.find(row=>identity(row)===oldKey):undefined;
|
||||||
|
next=[...next,{...prior,metric:f.metric,periodType:'YEAR',year:f.year,dimensions:d,value:Number(f.value)/100,unit:'RATE'}];
|
||||||
|
}
|
||||||
|
if(!next.some(row=>String(row.periodType).toUpperCase()==='YEAR'&&!Object.keys(dimensions(row.dimensions)).length)){message.error('至少保留一项总体年度目标');return;}
|
||||||
|
await persist(next);
|
||||||
|
}catch{ /* 表单保留在原位置显示字段错误。 */ }
|
||||||
|
};
|
||||||
|
const defaultTarget=matchingTarget(annual.filter(row=>row.metric===selectedMetric&&row.year===selectedYear&&(!editing||identity(row)!==identity(editing))),dimensions(form.getFieldsValue(true)));
|
||||||
|
const groupDepartments=obj(references.groupDepartments);
|
||||||
|
return <CompactManagementTables.Provider value={true}><section className="panel section-panel quality-targets-panel">
|
||||||
|
<div className="rule-page-toolbar"><div className="target-filters"><Select aria-label="目标年度" value={year} onChange={setYear} options={years.map(value=>({value,label:`${value}年`}))}/><Select {...readableSelectPopup} aria-label="查看目标指标" value={metric} onChange={setMetric} options={Object.entries(METRIC_NAMES).map(([value,label])=>({value,label}))}/></div><div className="task-actions"><Button icon={<ReloadOutlined/>} onClick={()=>void load()}>刷新</Button><Button type="primary" icon={<PlusOutlined/>} disabled={!version||loading} onClick={()=>open()}>新增目标</Button></div></div>
|
||||||
|
{error&&<Alert type="error" showIcon title="目标读取失败" description={error} action={<Button onClick={()=>void load()}>重试</Button>}/>}
|
||||||
|
{loading&&!version?<div className="loading-panel"><Spin/>读取质量目标…</div>:version?<Table size="small" bordered rowKey="key" pagination={{pageSize:15,showSizeChanger:false}} scroll={{x:780}} dataSource={tableRows} columns={[
|
||||||
|
{title:'年度',dataIndex:'year',width:90},{title:'适用范围',dataIndex:'scopeName',width:270},{title:'指标',dataIndex:'metric',width:225,render:v=>METRIC_NAMES[String(v)]||String(v)},
|
||||||
|
{title:'目标值',dataIndex:'displayValue',width:120,render:percent},{title:'目标来源',width:150,render:(_,row)=>row.inherited?String(row.inheritSource||'沿用总体目标'):row.exists?'单独设置':'未设置'},
|
||||||
|
{title:'操作',width:185,render:(_,row)=><span className="task-actions"><Button type="link" onClick={()=>open(row)}>{row.inherited?'设置覆盖':'编辑'}</Button>{Boolean(row.exists)&&Object.keys(dimensions(row.dimensions)).length>0&&<Popconfirm title="删除该范围的单独目标?" onConfirm={()=>persist(targets.filter(item=>String(item.periodType).toUpperCase()!=='YEAR'||identity(item)!==identity(row)))}><Button type="link" danger disabled={saving}>删除覆盖值</Button></Popconfirm>}</span>},
|
||||||
|
]}/>:!loading&&!error?<Empty description="当前没有启用的质量目标"/>:null}
|
||||||
|
<Modal className="management-modal" open={Boolean(editing)} title={editing?.inherited?'设置范围目标':editing?.newRecord?'新增质量目标':'编辑质量目标'} okText="保存目标" confirmLoading={saving} onCancel={()=>setEditing(null)} onOk={()=>void save()} width={640}>
|
||||||
|
<Form form={form} layout="vertical"><div className="structured-config-form-grid"><Form.Item name="year" label="年度" rules={[{required:true}]}><InputNumber min={2000} max={2100} precision={0} style={{width:'100%'}}/></Form.Item><Form.Item name="metric" label="指标" rules={[{required:true}]}><Select {...readableSelectPopup} options={Object.entries(METRIC_NAMES).map(([value,label])=>({value,label}))}/></Form.Item></div>
|
||||||
|
<Form.Item name="scope" label="适用范围"><Select options={[{value:'overall',label:'总体'},{value:'scope',label:'指定产业部 / 分组 / 产品 / 项目组'}]}/></Form.Item>
|
||||||
|
{scope==='scope'&&<><div className="structured-config-form-grid">{DIMENSIONS.map(key=><Form.Item key={key} name={key} label={dimensionName[key]}>{key==='department'||key==='group'?<Select {...readableSelectPopup} allowClear showSearch optionFilterProp="label" options={(Array.isArray(references[key==='department'?'departments':'groups'])?references[key==='department'?'departments':'groups'] as string[]:[]).filter(name=>key!=='group'||!department||!groupDepartments[name]||groupDepartments[name]===department).map(value=>({value,label:value}))}/>:<Input maxLength={190}/>}</Form.Item>)}</div><Form.Item name="inherit" valuePropName="checked"><Checkbox>不单独设置,沿用匹配目标:{percent(defaultTarget?.value)}</Checkbox></Form.Item></>}
|
||||||
|
{!(scope==='scope'&&inherit)&&<Form.Item name="value" label="目标百分比" rules={[{required:true,message:'请填写目标值'}]}><InputNumber min={0} max={100} precision={2} suffix="%" style={{width:'100%'}}/></Form.Item>}
|
||||||
|
<p className="structured-config-note">保存后更新目标线和达标判断,实际合格率保持不变。</p>
|
||||||
|
</Form>
|
||||||
|
</Modal>
|
||||||
|
</section></CompactManagementTables.Provider>;
|
||||||
|
}
|
||||||
@@ -41,7 +41,7 @@ export type PageKey = 'overall' | 'department' | 'group' | 'product' | 'blackPro
|
|||||||
const pageNames: Record<PageKey, string> = {
|
const pageNames: Record<PageKey, string> = {
|
||||||
overall: '总体合格率', department: '产业部', group: '产业部-业务分组', product: '产品汇总', blackProduct: '黑片汇总', brightProduct: '亮片汇总',
|
overall: '总体合格率', department: '产业部', group: '产业部-业务分组', product: '产品汇总', blackProduct: '黑片汇总', brightProduct: '亮片汇总',
|
||||||
basis: '数据与计算依据', analysis: '智能分析', sources: '数据接入', imports: '导入与校验',
|
basis: '数据与计算依据', analysis: '智能分析', sources: '数据接入', imports: '导入与校验',
|
||||||
rules: '计算规则', mappings: '对应关系', masterData: '基础数据', tasks: '任务与监控', access: '权限与审计',
|
rules: '指标与目标', mappings: '对应关系', masterData: '基础数据', tasks: '任务与监控', access: '权限与审计',
|
||||||
};
|
};
|
||||||
|
|
||||||
const pageFromLocation = (): PageKey => {
|
const pageFromLocation = (): PageKey => {
|
||||||
@@ -86,7 +86,7 @@ const navGroups = [
|
|||||||
{
|
{
|
||||||
label: '规则与管理',
|
label: '规则与管理',
|
||||||
items: [
|
items: [
|
||||||
['rules', '计算规则', SettingOutlined],
|
['rules', '指标与目标', SettingOutlined],
|
||||||
['mappings', '对应关系', ToolOutlined],
|
['mappings', '对应关系', ToolOutlined],
|
||||||
['masterData', '基础数据', DatabaseOutlined],
|
['masterData', '基础数据', DatabaseOutlined],
|
||||||
['tasks', '任务与监控', LineChartOutlined],
|
['tasks', '任务与监控', LineChartOutlined],
|
||||||
@@ -95,10 +95,6 @@ const navGroups = [
|
|||||||
},
|
},
|
||||||
];
|
];
|
||||||
|
|
||||||
function shownDepartment(value: string): string {
|
|
||||||
return value === '质量管理部' ? '质量中心' : value;
|
|
||||||
}
|
|
||||||
|
|
||||||
type QualityWorkspaceProps = {
|
type QualityWorkspaceProps = {
|
||||||
appearance: (typeof workspaceThemes)[number];
|
appearance: (typeof workspaceThemes)[number];
|
||||||
onAppearanceChange: (themeId: WorkspaceThemeId) => void;
|
onAppearanceChange: (themeId: WorkspaceThemeId) => void;
|
||||||
@@ -219,13 +215,7 @@ export default function QualityWorkspace({ appearance, onAppearanceChange }: Qua
|
|||||||
</div>
|
</div>
|
||||||
))}
|
))}
|
||||||
</nav>
|
</nav>
|
||||||
<div className="user-block">
|
|
||||||
<button type="button" className="user-profile-trigger" aria-label="打开个人账户" onClick={() => setAccountTab('profile')}>
|
|
||||||
<span className="avatar">{(user.displayName || user.username).slice(0, 1)}</span>
|
|
||||||
<span className="user-copy"><strong>{user.displayName || user.username}</strong><small>{user.departments.map(shownDepartment).join('、') || '个人账户'}</small></span>
|
|
||||||
</button>
|
|
||||||
<Tooltip title="退出登录"><Button type="text" icon={<LogoutOutlined />} aria-label="退出登录" onClick={() => void logout()} /></Tooltip>
|
|
||||||
</div>
|
|
||||||
</aside>
|
</aside>
|
||||||
|
|
||||||
<main className="main-column">
|
<main className="main-column">
|
||||||
|
|||||||
@@ -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>;
|
||||||
|
}
|
||||||
@@ -0,0 +1,121 @@
|
|||||||
|
import { useEffect, useState } from 'react';
|
||||||
|
import { Alert, Button, Checkbox, Collapse, Dropdown, Form, Input, Modal, Select, Tabs } from 'antd';
|
||||||
|
import { MoreOutlined, PlusOutlined } from '@ant-design/icons';
|
||||||
|
import { CompactManagementTables, QualityTable as Table } from './QualityTable';
|
||||||
|
import { ConfigurationWorkbookActions } from './ConfigurationWorkbookActions';
|
||||||
|
import { ruleLogicIssues } from './ruleEditing';
|
||||||
|
import { ChineseFormulaEditor } from './ChineseFormulaEditor';
|
||||||
|
import { compileChineseFormula, metricFormulaFields } from './formulaLanguage';
|
||||||
|
import { ResultFormulaModal } from './ResultFormulaModal';
|
||||||
|
import { describeResultFormula, newResultIssue, planResultMove, replaceResultFormula, stageResultFormulas, type ResultFormula } from './resultFormulas';
|
||||||
|
import { displayFormula, policyDescription, ruleObject as obj, ruleList, type RuleDefinition } from './rulePresentation';
|
||||||
|
|
||||||
|
type Props = { value: RuleDefinition; onChange: (value: RuleDefinition) => void; schema: RuleDefinition | null; schemaError: string; showWorkbookActions?: boolean; focusMetric?: { code: string; request: number }; readOnly?: boolean };
|
||||||
|
const strings = (v: unknown): string[] => Array.isArray(v) ? v.map(String) : [];
|
||||||
|
const nullLabels: Record<string, string> = { PROPAGATE:'任一输入缺失,运算结果为空', ZERO:'空值按0参与运算', IGNORE:'忽略空项,全部为空时结果为空' };
|
||||||
|
const resultLabels = (rate: boolean): Record<string, string> => ({ ONE: rate ? '按100%处理' : '取1', ZERO: rate ? '按0%处理' : '取0', NULL:'保留空白', ERROR:'停止并报错' });
|
||||||
|
|
||||||
|
export function RuleSettingsEditor({ value, onChange, schema, schemaError, showWorkbookActions = true, focusMetric, readOnly = false }: Props) {
|
||||||
|
const [tab, setTab] = useState('black');
|
||||||
|
const [sourceEdit, setSourceEdit] = useState<{ stage: string; alias: string; header: string } | null>(null);
|
||||||
|
const [sourceForm] = Form.useForm<{ header: string }>();
|
||||||
|
const [resultEdit, setResultEdit] = useState<{ result: ResultFormula; existing: boolean } | null>(null);
|
||||||
|
const [metricEdit, setMetricEdit] = useState<string | null>(null);
|
||||||
|
const [metricForm] = Form.useForm<{ formula: string; useDefault: boolean; nullPolicy: string; zeroDenominatorPolicy: string; nullResultPolicy: string }>();
|
||||||
|
const [error, setError] = useState('');
|
||||||
|
const [orderError, setOrderError] = useState('');
|
||||||
|
const useDefault = Form.useWatch('useDefault', metricForm);
|
||||||
|
const nextFormula = Form.useWatch('formula', metricForm);
|
||||||
|
const metricFields = schema && metricEdit ? metricFormulaFields(schema,metricEdit) : [];
|
||||||
|
const fields = obj(schema?.sourceFields), targets = obj(schema?.rowTargets), labels = obj(schema?.componentLabels), metricLabels = obj(schema?.metricLabels);
|
||||||
|
const rows = ruleList(value.rowRules), metrics = obj(value.metricRules), defaults = obj(obj(schema?.defaultDefinition).metricRules);
|
||||||
|
const sourceFields = obj(value.sourceFields);
|
||||||
|
const metricCodes = strings(schema?.metricCodes);
|
||||||
|
const limits = obj(schema?.limits); const maxLength = Number(limits.maxFormulaLength || 500);
|
||||||
|
const hasNullResult = strings(schema?.nullResultPolicies).length > 0;
|
||||||
|
const label = (key: unknown) => String(labels[String(key)] || key || '');
|
||||||
|
const metricLabel = (key: string) => String(metricLabels[key] || key).replace('剔除本部报废', '不含本部报废');
|
||||||
|
const openMetric = (code: string) => {
|
||||||
|
const rule = obj(metrics[code]); const effective = Object.hasOwn(metrics, code) ? rule : obj(defaults[code]);
|
||||||
|
setMetricEdit(code); setError('');
|
||||||
|
metricForm.setFieldsValue({ formula: String(effective.formula || ''), useDefault: !Object.hasOwn(metrics, code), nullPolicy: String(effective.nullPolicy || 'PROPAGATE'), zeroDenominatorPolicy: String(effective.zeroDenominatorPolicy || 'ONE'), nullResultPolicy: String(effective.nullResultPolicy || 'NULL') });
|
||||||
|
};
|
||||||
|
useEffect(() => {
|
||||||
|
if (focusMetric && schema && metricCodes.includes(focusMetric.code)) { setTab('metrics'); openMetric(focusMetric.code); }
|
||||||
|
// 每次导航请求只打开一次,后续字段编辑由表单维护。
|
||||||
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
|
}, [focusMetric?.request, Boolean(schema)]);
|
||||||
|
if (!schema) return <Alert showIcon type={schemaError ? 'error' : 'info'} title={schemaError ? '计算设置读取失败' : '正在读取计算设置'} description={schemaError || undefined} />;
|
||||||
|
const workbook = showWorkbookActions ? <div className="structured-config-toolbar"><ConfigurationWorkbookActions value={value.schemaVersion === schema.schemaVersion ? value : obj(schema.defaultDefinition)} onChange={onChange} scope="rules" label="计算规则" readOnly={readOnly} /></div> : null;
|
||||||
|
if (value.schemaVersion !== schema.schemaVersion) return <div className="rule-settings">{workbook}<Alert showIcon type="info" title="当前沿用原始计算规则" /><Button disabled={readOnly} onClick={() => onChange(structuredClone(obj(schema.defaultDefinition)))}>开始维护字段与公式</Button></div>;
|
||||||
|
const policies = (rate: boolean) => <div className="structured-config-form-grid">
|
||||||
|
<Form.Item name="nullPolicy" label="输入缺失时"><Select options={strings(schema.nullPolicies).map(value => ({ value, label: nullLabels[value] || value }))} /></Form.Item>
|
||||||
|
<Form.Item name="zeroDenominatorPolicy" label="分母为0时"><Select options={strings(schema.zeroDenominatorPolicies).map(value => ({ value, label: resultLabels(rate)[value] || value }))} /></Form.Item>
|
||||||
|
{hasNullResult && <Form.Item name="nullResultPolicy" label="最终结果为空时"><Select options={strings(schema.nullResultPolicies).map(value => ({ value, label: resultLabels(rate)[value] || value }))} /></Form.Item>}
|
||||||
|
</div>;
|
||||||
|
const openResult = (result: ResultFormula | null, stage: string) => {
|
||||||
|
const target = strings(targets[stage]).find(target => !rows.some(row => row.stage === stage && row.target === target)) || '';
|
||||||
|
setResultEdit({ existing: Boolean(result), result: result || { stage, target, indexes: [], rules: [{ stage, target, formula: '' }] } });
|
||||||
|
};
|
||||||
|
const checkedChange = (next: RuleDefinition) => {
|
||||||
|
const old = new Set(ruleLogicIssues(value, schema).map(issue => issue.key));
|
||||||
|
const issue = ruleLogicIssues(next, schema).find(issue => !old.has(issue.key));
|
||||||
|
if (issue) { setError(issue.message); return false; }
|
||||||
|
onChange(next); setError(''); return true;
|
||||||
|
};
|
||||||
|
const move = (result: ResultFormula, direction: number) => {
|
||||||
|
const next = planResultMove(value, result.stage, result.target, direction, schema);
|
||||||
|
if (next.definition) { onChange(next.definition); setOrderError(''); } else setOrderError(next.reason || '该调整会破坏计算依赖');
|
||||||
|
};
|
||||||
|
const remove = (result: ResultFormula) => {
|
||||||
|
const next = replaceResultFormula(value, result, []), issue = newResultIssue(value, next, schema);
|
||||||
|
if (issue) setOrderError(issue); else { onChange(next); setOrderError(''); }
|
||||||
|
};
|
||||||
|
const rowColumns = [
|
||||||
|
{ title:'执行顺序', key:'sequence', width:90, render:(_: unknown, _row: ResultFormula, position: number) => position + 1 },
|
||||||
|
{ title:'计算结果', dataIndex:'target', width:200, render:label },
|
||||||
|
{ title:'完整公式', key:'formula', width:650, render:(_:unknown, result:ResultFormula) => describeResultFormula(result,schema) },
|
||||||
|
{ title:'操作', key:'actions', width:115, render:(_:unknown, result:ResultFormula, position: number) => <span className="task-actions"><Button type="link" disabled={readOnly} onClick={() => openResult(result,result.stage)}>编辑</Button><Dropdown trigger={['click']} disabled={readOnly} menu={{items:[{key:'up',label:'上移',disabled:position===0},{key:'down',label:'下移',disabled:position===stageResultFormulas(value,result.stage).length-1},{key:'remove',label:'移除',danger:true}],onClick:({key})=>key==='remove'?remove(result):move(result,key==='up'?-1:1)}}><Button type="text" size="small" aria-label={`计算结果${position+1}更多操作`} icon={<MoreOutlined/>}/></Dropdown></span> },
|
||||||
|
];
|
||||||
|
const sourcePanel = <div className="rule-source-sections">{['black','bright'].map(selected=><section key={selected}><h3>{selected==='black'?'黑片':'亮片'}来源字段</h3><Table size="small" bordered rowKey="alias" pagination={false} dataSource={Object.entries(obj(fields[selected])).map(([alias,header])=>({alias,header:String(header),source:String(obj(sourceFields[selected])[alias]??header)}))} columns={[
|
||||||
|
{title:'计算字段',dataIndex:'header',width:260},{title:'Excel 来源列',dataIndex:'source',width:320},{title:'操作',width:90,render:(_:unknown,row:{alias:string;header:string;source:string})=><Button type="link" disabled={readOnly} onClick={()=>{setSourceEdit({stage:selected,alias:row.alias,header:row.header});sourceForm.setFieldsValue({header:row.source});}}>编辑</Button>},
|
||||||
|
]} scroll={{x:600}}/></section>)}</div>;
|
||||||
|
const stagePanel = (selected: string) => <div>
|
||||||
|
<div className="rule-stage-toolbar"><span/><Button icon={<PlusOutlined/>} disabled={readOnly || rows.length >= Number(limits.maxRowRules || 100) || stageResultFormulas(value,selected).length >= strings(targets[selected]).length} onClick={() => openResult(null, selected)}>新增结果公式</Button></div>
|
||||||
|
<Table<ResultFormula> size="small" bordered showRowNumbers={false} rowKey="target" dataSource={stageResultFormulas(value,selected)} columns={rowColumns} pagination={false} scroll={{x:1000}}/>
|
||||||
|
</div>;
|
||||||
|
return <CompactManagementTables.Provider value={true}><div className="rule-settings">{workbook}
|
||||||
|
{orderError && <Alert className="rule-order-error" type="error" showIcon title="未调整执行顺序" description={orderError} closable onClose={()=>setOrderError('')}/>}
|
||||||
|
<ol className="rule-pipeline"><li>读取来源字段</li><li>计算黑片 / 亮片重量</li><li>汇总计算合格率</li></ol>
|
||||||
|
<Tabs activeKey={tab} onChange={setTab} items={[
|
||||||
|
{ key:'black', label:'黑片计算', children:stagePanel('black') },
|
||||||
|
{ key:'bright', label:'亮片计算', children:stagePanel('bright') },
|
||||||
|
{ key:'metrics', label:'合格率公式', children:<Table<{code:string;rule:RuleDefinition;custom:boolean}> size="small" bordered rowKey="code" pagination={false} scroll={{x:960}} dataSource={metricCodes.map(code=>({code,rule:Object.hasOwn(metrics,code)?obj(metrics[code]):obj(defaults[code]),custom:Object.hasOwn(metrics,code)}))} columns={[
|
||||||
|
{title:'指标',dataIndex:'code',width:220,render:metricLabel},
|
||||||
|
{title:'当前计算公式',width:360,render:(_:unknown,row:{rule:RuleDefinition})=>displayFormula(row.rule.formula)},
|
||||||
|
{title:'特殊情况处理',width:340,render:(_:unknown,row:{rule:RuleDefinition})=><span className="rule-policy-summary">{policyDescription(row.rule)}</span>},
|
||||||
|
{title:'操作',width:90,render:(_:unknown,row:{code:string})=><Button type="link" disabled={readOnly} onClick={()=>openMetric(row.code)}>编辑</Button>},
|
||||||
|
]}/> },
|
||||||
|
]}/>
|
||||||
|
<details className="rule-reference rule-advanced"><summary>高级设置</summary><p>来源字段仅兼容旧数据;正常上传以“数据接入”中选定的字段对应为准。</p>{sourcePanel}</details>
|
||||||
|
<Modal className="management-modal" open={Boolean(sourceEdit)} title={`修改来源列 · ${sourceEdit?.header || ''}`} okText="应用修改" onCancel={()=>setSourceEdit(null)} onOk={()=>void sourceForm.validateFields().then(fields=>{if(!sourceEdit)return;onChange({...value,sourceFields:{...sourceFields,[sourceEdit.stage]:{...obj(sourceFields[sourceEdit.stage]),[sourceEdit.alias]:fields.header.trim()}}});setSourceEdit(null);}).catch(()=>undefined)}>
|
||||||
|
<Form form={sourceForm} layout="vertical"><Form.Item name="header" label="Excel 来源列名" rules={[{required:true,whitespace:true,message:'请填写来源列名'}]}><Input maxLength={200}/></Form.Item><details className="rule-reference"><summary>公式引用名称</summary><code>{sourceEdit?.alias}</code></details></Form>
|
||||||
|
</Modal>
|
||||||
|
{resultEdit && <ResultFormulaModal result={resultEdit.result} existing={resultEdit.existing} schema={schema} availableTargets={strings(targets[resultEdit.result.stage]).filter(target=>!rows.some(row=>row.stage===resultEdit.result.stage&&row.target===target))} onCancel={()=>setResultEdit(null)} onApply={result=>{
|
||||||
|
const next = replaceResultFormula(value,result,result.rules);
|
||||||
|
if (ruleList(next.rowRules).length > Number(limits.maxRowRules || 100)) return '已超过允许的公式分支数量';
|
||||||
|
const issue = newResultIssue(value,next,schema); if (issue) return issue;
|
||||||
|
onChange(next); setResultEdit(null); return undefined;
|
||||||
|
}}/>}
|
||||||
|
<Modal className="management-modal rule-form-modal" open={Boolean(metricEdit)} title={`修改公式 · ${metricEdit?metricLabel(metricEdit):''}`} width={760} okText="应用修改" onCancel={()=>setMetricEdit(null)} onOk={()=>void metricForm.validateFields().then(checked=>{const fields={...metricForm.getFieldsValue(true),...checked};
|
||||||
|
if(!metricEdit)return;const compiled=compileChineseFormula(fields.formula,metricFields,maxLength);if(!fields.useDefault&&compiled.error){setError(compiled.error);return;}const next={...metrics};if(fields.useDefault)delete next[metricEdit];else next[metricEdit]={...obj(metrics[metricEdit]),formula:compiled.formula,nullPolicy:fields.nullPolicy,zeroDenominatorPolicy:fields.zeroDenominatorPolicy,...(hasNullResult?{nullResultPolicy:fields.nullResultPolicy}:{})};if(checkedChange({...value,metricRules:next}))setMetricEdit(null);
|
||||||
|
}).catch(()=>undefined)}>
|
||||||
|
<Form form={metricForm} layout="vertical"><Form.Item name="useDefault" valuePropName="checked"><Checkbox>沿用默认公式</Checkbox></Form.Item>
|
||||||
|
<Form.Item name="formula" label="计算公式" rules={[{required:!useDefault,whitespace:true,message:'请填写公式'}]}><ChineseFormulaEditor id="formula" label="计算公式" fields={metricFields} disabled={useDefault} maxLength={maxLength}/></Form.Item>
|
||||||
|
<div className="rule-change-preview"><div><span>当前公式</span><p>{metricEdit?displayFormula((Object.hasOwn(metrics,metricEdit)?obj(metrics[metricEdit]):obj(defaults[metricEdit])).formula):''}</p></div><div><span>修改后</span><p>{displayFormula(useDefault&&metricEdit?obj(defaults[metricEdit]).formula:nextFormula)}</p></div></div>
|
||||||
|
{!useDefault&&<Collapse items={[{key:'policies',label:'特殊情况处理',children:policies(true)}]}/>}
|
||||||
|
|
||||||
|
</Form>{error&&<Alert type="error" showIcon title="公式尚未应用" description={error}/>}
|
||||||
|
</Modal>
|
||||||
|
</div></CompactManagementTables.Provider>;
|
||||||
|
}
|
||||||
@@ -2,7 +2,7 @@ import { newMasterDataCode } from './masterDataIdentity';
|
|||||||
import { ConfigurationWorkbookActions } from './ConfigurationWorkbookActions';
|
import { ConfigurationWorkbookActions } from './ConfigurationWorkbookActions';
|
||||||
import { matchRuleConflicts } from './classificationMaintenance';
|
import { matchRuleConflicts } from './classificationMaintenance';
|
||||||
import { useEffect, useMemo, useState } from 'react';
|
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 type { ColumnsType } from 'antd/es/table';
|
||||||
import { QualityTable as Table } from './QualityTable';
|
import { QualityTable as Table } from './QualityTable';
|
||||||
import { PlusOutlined } from '@ant-design/icons';
|
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>;
|
}}>应用到草稿</Button>{error && <Alert type="error" showIcon message={error} />}</details>;
|
||||||
}
|
}
|
||||||
|
|
||||||
type RuleRow = Record<string, unknown>;
|
export { RuleSettingsEditor as RuleDefinitionEditor } from './RuleSettingsEditor';
|
||||||
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>;
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -0,0 +1,116 @@
|
|||||||
|
import { displayFormula, ruleObject as obj, type RuleDefinition } from './rulePresentation.ts';
|
||||||
|
|
||||||
|
export type FormulaField = { key: string; label: string; group: string };
|
||||||
|
const strings = (value: unknown): string[] => Array.isArray(value) ? value.map(String) : [];
|
||||||
|
export function rowFormulaFields(schema: RuleDefinition, stage: string): FormulaField[] {
|
||||||
|
return [
|
||||||
|
...Object.entries(obj(obj(schema.sourceFields)[stage])).filter(([key]) => !['inspectionNote','issueLocation','applicability'].includes(key)).map(([key, label]) => ({ key, label:String(label), group:'来源字段' })),
|
||||||
|
...strings(obj(schema.rowTargets)[stage]).map(key => ({ key, label:String(obj(schema.componentLabels)[key] || key), group:'计算结果' })),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
export function metricFormulaFields(schema: RuleDefinition, metric: string): FormulaField[] {
|
||||||
|
const inputs = ['blackGood','blackScrap','blackTotal','brightGood','brightScrap','brightTotal','headquartersScrap'];
|
||||||
|
const codes = strings(schema.metricCodes), at = codes.indexOf(metric);
|
||||||
|
return [...inputs.map(key => ({ key, label:displayFormula(key), group:'汇总重量' })), ...codes.slice(0, Math.max(0, at)).map(key => ({ key, label:String(obj(schema.metricLabels)[key] || displayFormula(key)), group:'已计算指标' }))];
|
||||||
|
}
|
||||||
|
export function formulaFieldName(field: FormulaField, fields: FormulaField[]): string {
|
||||||
|
if (fields.filter(item => item.label === field.label).length === 1) return field.label;
|
||||||
|
const peers = fields.filter(item => item.label === field.label && item.group === field.group);
|
||||||
|
return `${field.group}·${field.label}${peers.length > 1 ? `(${peers.findIndex(item => item.key === field.key) + 1})` : ''}`;
|
||||||
|
}
|
||||||
|
export const formulaFieldReference = (field: FormulaField, fields: FormulaField[]) => `[${formulaFieldName(field,fields).replaceAll(']',']]')}]`;
|
||||||
|
function bracketAt(text: string, at: number): { name: string; end: number } {
|
||||||
|
let name = '', i = at + 1;
|
||||||
|
while (i < text.length) {
|
||||||
|
if (text[i] !== ']') { name += text[i++]; continue; }
|
||||||
|
if (text[i+1] === ']') { name += ']'; i += 2; continue; }
|
||||||
|
return { name, end:i+1 };
|
||||||
|
}
|
||||||
|
throw new Error('字段引用缺少右方括号 ]');
|
||||||
|
}
|
||||||
|
/** 只翻译显示标记;不改写数字、空白、运算结构或保存的原公式。 */
|
||||||
|
export function chineseFormula(value: unknown, fields: FormulaField[]): string {
|
||||||
|
const text = String(value ?? ''), byKey = new Map(fields.map(field => [field.key,field]));
|
||||||
|
let result = '', i = 0;
|
||||||
|
while (i < text.length) {
|
||||||
|
if (text[i] === '[') {
|
||||||
|
try { const bracket=bracketAt(text,i); result += text.slice(i,bracket.end); i=bracket.end; continue; } catch { result += text.slice(i); break; }
|
||||||
|
}
|
||||||
|
const identifier = /^[A-Za-z_][A-Za-z0-9_]*/.exec(text.slice(i))?.[0];
|
||||||
|
if (identifier) { result += byKey.has(identifier) ? formulaFieldReference(byKey.get(identifier)!,fields) : identifier === 'SUM' ? '求和' : identifier; i += identifier.length; }
|
||||||
|
else { result += text[i] === '*' ? '×' : text[i] === '/' ? '÷' : text[i]; i++; }
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
type Token = { kind: 'number' | 'field' | 'function' | 'symbol'; value: string };
|
||||||
|
/** 中文引用编译为既有引擎语法,只检查结构,不在浏览器求值。 */
|
||||||
|
export function compileChineseFormula(input: unknown, fields: FormulaField[], maxLength = 500): { formula: string; error?: string } {
|
||||||
|
const text = String(input ?? ''), tokens: Token[] = [], parts: string[] = [];
|
||||||
|
try {
|
||||||
|
if (!text.trim()) throw new Error('请填写公式');
|
||||||
|
const names = new Map<string, FormulaField[]>();
|
||||||
|
for (const field of fields) for (const name of new Set([field.label,formulaFieldName(field,fields)])) names.set(name,[...(names.get(name)||[]),field]);
|
||||||
|
const resolve = (name: string) => {
|
||||||
|
const matches = names.get(name);
|
||||||
|
if (!matches?.length) throw new Error(`找不到字段“${name}”`);
|
||||||
|
if (matches.length > 1) throw new Error(`字段“${name}”重名,请从字段列表选择`);
|
||||||
|
return matches[0].key;
|
||||||
|
};
|
||||||
|
const aliases = new Set(fields.map(field => field.key));
|
||||||
|
const bareNames = [...names.keys()].sort((a,b)=>b.length-a.length);
|
||||||
|
const push = (kind: Token['kind'], value: string) => { tokens.push({kind,value}); parts.push(value); };
|
||||||
|
let i = 0;
|
||||||
|
while (i < text.length) {
|
||||||
|
const rest = text.slice(i), space = /^\s+/.exec(rest)?.[0];
|
||||||
|
if (space) { parts.push(space); i += space.length; continue; }
|
||||||
|
if (text[i] === '[') { const bracket=bracketAt(text,i); push('field',resolve(bracket.name)); i=bracket.end; continue; }
|
||||||
|
const fn = /^(求和|SUM)(?=\s*[((])/.exec(rest)?.[0];
|
||||||
|
if (fn) { push('function','SUM'); i += fn.length; continue; }
|
||||||
|
const knownAlias = /^[A-Za-z_][A-Za-z0-9_]*/.exec(rest)?.[0];
|
||||||
|
if (knownAlias && aliases.has(knownAlias)) { push('field',knownAlias); i += knownAlias.length; continue; }
|
||||||
|
const name = bareNames.find(name => rest.startsWith(name));
|
||||||
|
if (name) { push('field',resolve(name)); i += name.length; continue; }
|
||||||
|
const number = /^[\d.]+/.exec(rest)?.[0];
|
||||||
|
if (number) {
|
||||||
|
if (!/^(?:\d+(?:\.\d*)?|\.\d+)$/.test(number)) throw new Error('数值格式无效');
|
||||||
|
if (number.length > 50) throw new Error('数值常量不能超过50字');
|
||||||
|
push('number',number); i += number.length; continue;
|
||||||
|
}
|
||||||
|
const identifier = /^[A-Za-z_][A-Za-z0-9_]*/.exec(rest)?.[0];
|
||||||
|
if (identifier) { if (!aliases.has(identifier)) throw new Error(`找不到字段“${identifier}”`); push('field',identifier); i += identifier.length; continue; }
|
||||||
|
const symbols: Record<string,string> = { '×':'*','÷':'/','−':'-','+':'+','-':'-','(':'(',')':')',',':',' };
|
||||||
|
const symbol = symbols[text[i]] || text[i];
|
||||||
|
if ('+-*/(),'.includes(symbol)) { push('symbol',symbol); i++; continue; }
|
||||||
|
throw new Error(`无法识别“${rest.split(/[\s+\-*/(),]/)[0]}”,请从列表选择字段`);
|
||||||
|
}
|
||||||
|
const formula = parts.join('');
|
||||||
|
if (formula.length > maxLength) throw new Error(`公式过长,转换后最多${maxLength}字`);
|
||||||
|
let at = 0, depth = 0, count = 0;
|
||||||
|
const take = (value: string) => { if (tokens[at]?.value === value && tokens[at]?.kind === 'symbol') { at++; return true; } return false; };
|
||||||
|
const open = () => { if (++depth > 32) throw new Error('括号嵌套不能超过32层'); };
|
||||||
|
const factor = (): void => {
|
||||||
|
if (++count > 250) throw new Error('公式过于复杂');
|
||||||
|
if (take('+') || take('-')) { factor(); return; }
|
||||||
|
if (take('(')) { open(); expression(); if (!take(')')) throw new Error('括号不匹配'); depth--; return; }
|
||||||
|
const token = tokens[at++];
|
||||||
|
if (token?.kind === 'function') {
|
||||||
|
if (!take('(')) throw new Error('求和后需要括号'); open(); let args=0;
|
||||||
|
do { if (++args > 20) throw new Error('求和最多20个参数'); expression(); } while (take(','));
|
||||||
|
if (!take(')')) throw new Error('求和括号不匹配'); depth--; return;
|
||||||
|
}
|
||||||
|
if (!token || !['number','field'].includes(token.kind)) throw new Error('请补全数字、字段或括号');
|
||||||
|
};
|
||||||
|
const term = () => { factor(); while (take('*') || take('/')) factor(); };
|
||||||
|
const expression = () => { term(); while (take('+') || take('-')) term(); };
|
||||||
|
expression();
|
||||||
|
if (at !== tokens.length) throw new Error('请检查运算符、逗号及括号的位置');
|
||||||
|
return {formula};
|
||||||
|
} catch (error) { return {formula:text,error:error instanceof Error?error.message:'公式未填写完整'}; }
|
||||||
|
}
|
||||||
|
|
||||||
|
export function insertFormulaPart(text: string, start: number, end: number, part: string, fn = false): { text: string; caret: number } {
|
||||||
|
const from=Math.max(0,Math.min(start,text.length)),to=Math.max(from,Math.min(end,text.length));
|
||||||
|
const insertion=fn?`求和(${text.slice(from,to)})`:part;
|
||||||
|
return { text:text.slice(0,from)+insertion+text.slice(to),caret:from+insertion.length-(fn?1:0) };
|
||||||
|
}
|
||||||
@@ -0,0 +1,93 @@
|
|||||||
|
import { displayRowFormula, ruleLogicIssues } from './ruleEditing.ts';
|
||||||
|
import { ruleList, ruleObject as obj, type RuleDefinition } from './rulePresentation.ts';
|
||||||
|
|
||||||
|
export type ResultFormula = { stage: string; target: string; indexes: number[]; rules: RuleDefinition[] };
|
||||||
|
export const conditionOperators: Record<string, string> = { EQ:'等于', NE:'不等于', CONTAINS:'包含', NOT_CONTAINS:'不包含', IS_BLANK:'为空', IS_NOT_BLANK:'不为空', GT:'大于', GTE:'大于等于', LT:'小于', LTE:'小于等于' };
|
||||||
|
export const blankCondition = (operator: unknown) => ['IS_BLANK', 'IS_NOT_BLANK'].includes(String(operator));
|
||||||
|
|
||||||
|
/** 展示按结果归并;原始规则的位置、分支、策略和执行顺序均不变。 */
|
||||||
|
export function stageResultFormulas(definition: RuleDefinition, stage: string): ResultFormula[] {
|
||||||
|
const results = new Map<string, ResultFormula>();
|
||||||
|
ruleList(definition.rowRules).forEach((rule, index) => {
|
||||||
|
if (rule.stage !== stage) return;
|
||||||
|
const target = String(rule.target);
|
||||||
|
if (!results.has(target)) results.set(target, { stage, target, indexes: [], rules: [] });
|
||||||
|
const result = results.get(target)!;
|
||||||
|
result.indexes.push(index); result.rules.push(rule);
|
||||||
|
});
|
||||||
|
return [...results.values()];
|
||||||
|
}
|
||||||
|
|
||||||
|
export function describeCondition(rule: RuleDefinition, schema: RuleDefinition): string {
|
||||||
|
const when = obj(rule.when), fields = obj(obj(schema.sourceFields)[String(rule.stage)]);
|
||||||
|
return `${String(fields[String(when.field)] || when.field)}${conditionOperators[String(when.operator)] || String(when.operator)}${blankCondition(when.operator) ? '' : `“${String(when.value ?? '')}”`}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
type Expression = { text: string } | { condition: string; yes: string; no: Expression; signature: string };
|
||||||
|
const expressionText = (expression: Expression): string => 'text' in expression ? expression.text : `若${expression.condition},取${expression.yes};否则${'text' in expression.no ? `取${expression.no.text}` : `(${expressionText(expression.no)})`}`;
|
||||||
|
const choiceExpression = (expression: Expression) => 'text' in expression ? undefined : expression;
|
||||||
|
const policyKey = (rule: RuleDefinition) => JSON.stringify([rule.nullPolicy || 'PROPAGATE', rule.zeroDenominatorPolicy || 'ONE', rule.nullResultPolicy || 'NULL']);
|
||||||
|
|
||||||
|
export function describeResultFormula(result: ResultFormula, schema: RuleDefinition): string {
|
||||||
|
let expression: Expression = { text: '原计算结果' };
|
||||||
|
for (const rule of result.rules) {
|
||||||
|
const previous = expressionText(expression);
|
||||||
|
// 先替换自引用,再翻译业务字段名,保留对“此前值”的含义。
|
||||||
|
const translated = (value: unknown) => {
|
||||||
|
const raw = String(value ?? '').replace(new RegExp(`\\b${result.target}\\b`, 'g'), '__previous_result__');
|
||||||
|
return displayRowFormula({ ...rule, formula: raw }, schema).replaceAll('__previous_result__', `(${previous})`);
|
||||||
|
};
|
||||||
|
const yes = translated(rule.formula);
|
||||||
|
if (!rule.when) { expression = { text: yes }; continue; }
|
||||||
|
const no: Expression = rule.otherwiseFormula !== undefined ? { text: translated(rule.otherwiseFormula) } : expression;
|
||||||
|
const signature = JSON.stringify([rule.formula, policyKey(rule)]);
|
||||||
|
const condition = describeCondition(rule, schema);
|
||||||
|
// 只合并展示相同取值的“或”条件,不合并存储、求值或异常处理。
|
||||||
|
const selfReference = new RegExp(`\\b${result.target}\\b`).test(String(rule.formula));
|
||||||
|
const previousChoice = choiceExpression(no);
|
||||||
|
expression = rule.otherwiseFormula === undefined && !selfReference && previousChoice?.signature === signature
|
||||||
|
? { condition: `${condition} 或 ${previousChoice.condition}`, yes, no: previousChoice.no, signature }
|
||||||
|
: { condition, yes, no, signature };
|
||||||
|
}
|
||||||
|
return expressionText(expression);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 更新本结果的原位置;其他结果的规则对象与相对次序保持不变。 */
|
||||||
|
export function replaceResultFormula(definition: RuleDefinition, result: Pick<ResultFormula, 'stage' | 'target'>, rules: RuleDefinition[]): RuleDefinition {
|
||||||
|
if (rules.some(rule => rule.stage !== result.stage || rule.target !== result.target)) throw new Error('公式分支必须属于同一个计算结果');
|
||||||
|
const rows = ruleList(definition.rowRules);
|
||||||
|
const positions = rows.flatMap((row, index) => row.stage === result.stage && row.target === result.target ? [index] : []);
|
||||||
|
let next: RuleDefinition[];
|
||||||
|
if (!positions.length) {
|
||||||
|
const lastStage = rows.map(row => row.stage).lastIndexOf(result.stage);
|
||||||
|
const insert = lastStage < 0 ? rows.length : lastStage + 1;
|
||||||
|
next = [...rows.slice(0, insert), ...rules, ...rows.slice(insert)];
|
||||||
|
} else {
|
||||||
|
let position = 0;
|
||||||
|
next = rows.flatMap((row, index) => {
|
||||||
|
if (row.stage !== result.stage || row.target !== result.target) return [row];
|
||||||
|
const replacement = position < rules.length ? [rules[position]] : [];
|
||||||
|
position++;
|
||||||
|
return index === positions.at(-1) ? [...replacement, ...rules.slice(position)] : replacement;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return JSON.stringify(next) === JSON.stringify(rows) ? definition : { ...definition, rowRules: next };
|
||||||
|
}
|
||||||
|
|
||||||
|
export function newResultIssue(before: RuleDefinition, after: RuleDefinition, schema: RuleDefinition): string | undefined {
|
||||||
|
const prior = new Set(ruleLogicIssues(before, schema).map(issue => issue.key));
|
||||||
|
return ruleLogicIssues(after, schema).find(issue => !prior.has(issue.key))?.message;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 移动完整结果及其分支,仅交换两个相邻结果占用的位置。 */
|
||||||
|
export function planResultMove(definition: RuleDefinition, stage: string, target: string, direction: number, schema: RuleDefinition): { definition?: RuleDefinition; reason?: string } {
|
||||||
|
const results = stageResultFormulas(definition, stage), index = results.findIndex(result => result.target === target);
|
||||||
|
const current = results[index], other = results[index + direction];
|
||||||
|
if (!current || !other) return { reason: direction < 0 ? '已是当前阶段的第一项' : '已是当前阶段的最后一项' };
|
||||||
|
const positions = [...current.indexes, ...other.indexes].sort((a, b) => a - b);
|
||||||
|
const replacements = direction < 0 ? [...current.rules, ...other.rules] : [...other.rules, ...current.rules];
|
||||||
|
const next = ruleList(definition.rowRules).slice();
|
||||||
|
positions.forEach((position, i) => { next[position] = replacements[i]; });
|
||||||
|
const candidate = { ...definition, rowRules: next }, reason = newResultIssue(definition, candidate, schema);
|
||||||
|
return reason ? { reason } : { definition: candidate };
|
||||||
|
}
|
||||||
@@ -0,0 +1,81 @@
|
|||||||
|
import { displayFormula, ruleList, ruleObject as obj, type RuleDefinition } from './rulePresentation.ts';
|
||||||
|
|
||||||
|
export type RuleIssue = { index: number; key: string; message: string };
|
||||||
|
const strings = (value: unknown): string[] => Array.isArray(value) ? value.map(String) : [];
|
||||||
|
const identifiers = (formula: unknown): string[] => typeof formula === 'string' ? [...new Set(formula.match(/[A-Za-z_][A-Za-z0-9_]*/g) || [])] : [];
|
||||||
|
const metricInputs = ['blackGood','blackScrap','blackTotal','brightGood','brightScrap','brightTotal','headquartersScrap'];
|
||||||
|
const textFields = new Set(['issueLocation','inspectionNote','applicability']);
|
||||||
|
const conditionKey = (value: unknown) => { const when = obj(value); return JSON.stringify([when.field, when.operator, String(when.value ?? '')]); };
|
||||||
|
|
||||||
|
/** 仅检查显式编排与变量,不求值、不改写公式;语法和数值仍由正式规则引擎校验。 */
|
||||||
|
export function ruleLogicIssues(definition: RuleDefinition, schema: RuleDefinition): RuleIssue[] {
|
||||||
|
const rows = ruleList(definition.rowRules), issues: RuleIssue[] = [];
|
||||||
|
const label = (key: string) => String(obj(schema.componentLabels)[key] || obj(schema.metricLabels)[key] || key);
|
||||||
|
const add = (index: number, key: string, message: string) => issues.push({ index, key, message });
|
||||||
|
const step = (index: number) => `“${label(String(rows[index]?.target))}”`;
|
||||||
|
rows.forEach((row, index) => {
|
||||||
|
const stage = String(row.stage), target = String(row.target), stageTargets = strings(obj(schema.rowTargets)[stage]);
|
||||||
|
const source = obj(obj(schema.sourceFields)[stage]);
|
||||||
|
const allowed = new Set([...Object.keys(source).filter(key => !textFields.has(key)), ...stageTargets, 'SUM']);
|
||||||
|
if (!stageTargets.includes(target)) add(index, `target:${stage}:${target}`, `${step(index)}的计算结果不属于当前阶段`);
|
||||||
|
for (const key of ['formula', ...(row.when && row.otherwiseFormula ? ['otherwiseFormula'] : [])]) {
|
||||||
|
const formula = row[key];
|
||||||
|
if (typeof formula !== 'string' || !formula.trim()) add(index, `empty:${stage}:${target}:${key}`, `${step(index)}的公式不能为空`);
|
||||||
|
for (const variable of identifiers(formula)) {
|
||||||
|
if (!allowed.has(variable)) add(index, `variable:${stage}:${target}:${variable}`, `${step(index)}存在不可用的公式变量:${String(source[variable] || variable)}`);
|
||||||
|
// 未单独维护的结果继续沿用原计算。已维护的分量应完成全部覆盖后再被引用。
|
||||||
|
if (variable !== target && stageTargets.includes(variable) && rows.some((writer, i) => i > index && writer.stage === stage && writer.target === variable))
|
||||||
|
add(index, `dependency:${stage}:${target}:${variable}`, `${step(index)}引用了“${label(variable)}”,但后面还会修改它;应先完成分量计算,再计算“${label(target)}”`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (row.when) {
|
||||||
|
const when = obj(row.when);
|
||||||
|
if (!Object.hasOwn(source, String(when.field))) add(index, `condition:${stage}:${target}`, `${step(index)}的条件字段不可用`);
|
||||||
|
if (!strings(schema.conditionOperators).includes(String(when.operator))) add(index, `operator:${stage}:${target}`, `${step(index)}的判断方式不可用`);
|
||||||
|
if (!['IS_BLANK','IS_NOT_BLANK'].includes(String(when.operator)) && (when.value === undefined || when.value === null || String(when.value).trim() === ''))
|
||||||
|
add(index, `condition-value:${stage}:${target}`, `${step(index)}需要填写条件值`);
|
||||||
|
if (['GT','GTE','LT','LTE'].includes(String(when.operator)) && !/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)$/.test(String(when.value)))
|
||||||
|
add(index, `condition-number:${stage}:${target}`, `${step(index)}的比较条件需要填写数值`);
|
||||||
|
if (rows.some((later, i) => i > index && later.stage === stage && later.target === target && !later.when))
|
||||||
|
add(index, `overwrite:${stage}:${target}`, `${step(index)}的条件结果会被后面的“所有记录”公式覆盖;默认值应放在条件覆盖之前`);
|
||||||
|
const duplicate = rows.findIndex((earlier, i) => i < index && earlier.stage === stage && earlier.target === target && conditionKey(earlier.when) === conditionKey(row.when) && earlier.formula !== row.formula);
|
||||||
|
if (duplicate >= 0) add(index, `duplicate:${stage}:${target}:${conditionKey(row.when)}`, `${step(duplicate)}与${step(index)}的条件相同,计算方式却不一致`);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
const metricCodes = strings(schema.metricCodes), allowed = new Set([...metricInputs, 'SUM']);
|
||||||
|
for (const code of metricCodes) {
|
||||||
|
const rule = obj(obj(definition.metricRules)[code]);
|
||||||
|
if (Object.hasOwn(obj(definition.metricRules), code)) {
|
||||||
|
if (!String(rule.formula || '').trim()) add(-1, `metric-empty:${code}`, `“${label(code)}”的公式不能为空`);
|
||||||
|
for (const variable of identifiers(rule.formula)) if (!allowed.has(variable)) add(-1, `metric-variable:${code}:${variable}`, `“${label(code)}”引用了不可用或尚未计算的变量:${label(variable)}`);
|
||||||
|
}
|
||||||
|
allowed.add(code);
|
||||||
|
}
|
||||||
|
return issues;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function neighboringRuleIndex(rows: RuleDefinition[], index: number, direction: number): number | undefined {
|
||||||
|
const row = rows[index]; if (!row) return undefined;
|
||||||
|
const positions = rows.flatMap((item, i) => item.stage === row.stage ? [i] : []);
|
||||||
|
return positions[positions.indexOf(index) + direction];
|
||||||
|
}
|
||||||
|
|
||||||
|
export function planRuleMove(definition: RuleDefinition, index: number, direction: number, schema: RuleDefinition): { definition?: RuleDefinition; reason?: string } {
|
||||||
|
const rows = ruleList(definition.rowRules), other = neighboringRuleIndex(rows, index, direction);
|
||||||
|
if (other === undefined) return { reason: direction < 0 ? '已是当前阶段的第一步' : '已是当前阶段的最后一步' };
|
||||||
|
const next = rows.slice(); [next[index], next[other]] = [next[other], next[index]];
|
||||||
|
const candidate = { ...definition, rowRules: next };
|
||||||
|
const prior = new Set(ruleLogicIssues(definition, schema).map(issue => issue.key));
|
||||||
|
const introduced = ruleLogicIssues(candidate, schema).find(issue => !prior.has(issue.key));
|
||||||
|
return introduced ? { reason: introduced.message } : { definition: candidate };
|
||||||
|
}
|
||||||
|
|
||||||
|
export function displayRowFormula(row: RuleDefinition, schema: RuleDefinition): string {
|
||||||
|
const names = { ...obj(schema.componentLabels), ...obj(obj(schema.sourceFields)[String(row.stage)]) };
|
||||||
|
const formula = String(row.formula ?? '');
|
||||||
|
return formula.replace(/[A-Za-z_][A-Za-z0-9_]*/g, token => token === 'SUM' ? '求和' : String(names[token] || displayFormula(token))).replace(/\*/g, '×').replace(/\//g, '÷');
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isDefaultAssignment(row: RuleDefinition, index: number, rows: RuleDefinition[]): boolean {
|
||||||
|
return !row.when && rows.some((later, i) => i > index && later.stage === row.stage && later.target === row.target && Boolean(later.when));
|
||||||
|
}
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
import { readableMetricFormula } from './publicDataDisplay.ts';
|
||||||
|
|
||||||
|
export type RuleDefinition = Record<string, unknown>;
|
||||||
|
export const ruleObject = (value: unknown): RuleDefinition => value && typeof value === 'object' && !Array.isArray(value) ? value as RuleDefinition : {};
|
||||||
|
export const ruleList = (value: unknown): RuleDefinition[] => Array.isArray(value) ? value.map(ruleObject) : [];
|
||||||
|
export const METRIC_KEYS: Record<string, string> = {
|
||||||
|
BLACK_RATE: 'blackRate', BRIGHT_RATE: 'brightRate', COMPOSITE_RATE: 'compositeRate',
|
||||||
|
BRIGHT_RATE_WITHOUT_HEADQUARTERS_SCRAP: 'brightRateWithoutHeadquartersScrap',
|
||||||
|
COMPOSITE_RATE_WITHOUT_HEADQUARTERS_SCRAP: 'compositeRateWithoutHeadquartersScrap',
|
||||||
|
};
|
||||||
|
export const METRIC_NAMES: Record<string, string> = {
|
||||||
|
BLACK_RATE: '黑片合格率', BRIGHT_RATE: '亮片合格率', COMPOSITE_RATE: '综合合格率',
|
||||||
|
BRIGHT_RATE_WITHOUT_HEADQUARTERS_SCRAP: '亮片合格率(不含本部报废)',
|
||||||
|
COMPOSITE_RATE_WITHOUT_HEADQUARTERS_SCRAP: '综合合格率(不含本部报废)',
|
||||||
|
};
|
||||||
|
export function displayFormula(value: unknown): string {
|
||||||
|
return typeof value === 'string' && value.trim() ? readableMetricFormula(value) : '未单独设置';
|
||||||
|
}
|
||||||
|
export function formulaOnly(value: string): string { return value.split(/[;;]/)[0]; }
|
||||||
|
export function policyDescription(rule: RuleDefinition, rate = true): string {
|
||||||
|
const outcome = (key: unknown) => ({ ONE: rate ? '按100%处理' : '取1', ZERO: rate ? '按0%处理' : '取0', NULL: '保留空白', ERROR: '停止并报错' }[String(key)] || String(key));
|
||||||
|
const missing = ({ PROPAGATE: '运算结果为空', ZERO: '按0参与运算', IGNORE: '忽略空项,全部为空时结果为空' } as Record<string, string>)[String(rule.nullPolicy || 'PROPAGATE')];
|
||||||
|
return `输入缺失:${missing};分母为0:${outcome(rule.zeroDenominatorPolicy || 'ONE')};最终为空:${outcome(rule.nullResultPolicy || 'NULL')}`;
|
||||||
|
}
|
||||||
|
export function stageRuleRows(definition: RuleDefinition, stage: string): (RuleDefinition & { index: number })[] {
|
||||||
|
return ruleList(definition.rowRules).flatMap((rule, index) => rule.stage === stage ? [{ ...rule, index }] : []);
|
||||||
|
}
|
||||||
|
export function ruleChangeSummary(before: RuleDefinition, after: RuleDefinition): string[] {
|
||||||
|
const changes: string[] = [];
|
||||||
|
for (const stage of ['black', 'bright']) {
|
||||||
|
const a = ruleObject(ruleObject(before.sourceFields)[stage]), b = ruleObject(ruleObject(after.sourceFields)[stage]);
|
||||||
|
const count = [...new Set([...Object.keys(a), ...Object.keys(b)])].filter(key => a[key] !== b[key]).length;
|
||||||
|
if (count) changes.push(`${stage === 'black' ? '黑片' : '亮片'}来源字段 ${count} 项`);
|
||||||
|
}
|
||||||
|
const a = ruleList(before.rowRules), b = ruleList(after.rowRules);
|
||||||
|
const count = Array.from({ length: Math.max(a.length, b.length) }, (_, i) => i).filter(i => JSON.stringify(a[i]) !== JSON.stringify(b[i])).length;
|
||||||
|
if (count) changes.push(`行计算 ${count} 个位置`);
|
||||||
|
const am = ruleObject(before.metricRules), bm = ruleObject(after.metricRules);
|
||||||
|
const metrics = [...new Set([...Object.keys(am), ...Object.keys(bm)])].filter(key => JSON.stringify(am[key]) !== JSON.stringify(bm[key])).length;
|
||||||
|
if (metrics) changes.push(`合格率公式 ${metrics} 项`);
|
||||||
|
return changes;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 仅呈现服务端既有优先级:匹配维度更多者优先,同维度数量时业务分组优先。
|
||||||
|
export function matchingTarget(targets: RuleDefinition[], dimensions: RuleDefinition): RuleDefinition | undefined {
|
||||||
|
const keys = ['department', 'group', 'product', 'projectGroup'];
|
||||||
|
const filled = (value: unknown) => value !== null && value !== undefined && String(value).trim() !== '' && value !== '*';
|
||||||
|
const candidates = targets.filter(target => keys.every(key => !filled(ruleObject(target.dimensions)[key]) || ruleObject(target.dimensions)[key] === dimensions[key]));
|
||||||
|
const count = (target: RuleDefinition) => keys.filter(key => filled(ruleObject(target.dimensions)[key])).length;
|
||||||
|
return candidates.slice().sort((a, b) => count(b) - count(a) || Number(filled(ruleObject(b.dimensions).group)) - Number(filled(ruleObject(a.dimensions).group)))[0];
|
||||||
|
}
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
.rule-page-toolbar,.rule-stage-toolbar{display:flex;align-items:center;justify-content:space-between;gap:16px;margin-bottom:18px;flex-wrap:wrap}
|
||||||
|
.target-filters{display:flex;align-items:center;gap:10px;flex-wrap:wrap}.target-filters>.ant-select:first-child{min-width:110px}.target-filters>.ant-select:nth-child(2){min-width:240px}
|
||||||
|
.rule-pipeline{display:flex;gap:0;list-style:none;margin:0 0 22px;padding:0;border:1px solid var(--line,#e2e7f0);border-radius:4px;overflow:hidden}
|
||||||
|
.rule-pipeline li{flex:1;padding:13px 18px;color:var(--muted-ink,#62718a);background:var(--surface-subtle,#f7f9fc);font-size:13px;text-align:center}
|
||||||
|
.rule-pipeline li+li{border-left:1px solid var(--line,#e2e7f0)}.rule-pipeline li+li::before{content:'→';margin-right:16px;color:var(--blue,#647bea)}
|
||||||
|
.rule-source-sections{display:grid;gap:24px}.rule-source-sections h3{font-size:14px;margin:0 0 12px;font-weight:600}.rule-settings .ant-tabs-content{padding-top:8px}
|
||||||
|
.rule-stage-toolbar>span{font-size:12px;color:var(--muted-ink,#62718a)}
|
||||||
|
.rule-reference{margin:18px 0;color:var(--muted-ink,#62718a);font-size:12px}.rule-reference>summary{cursor:pointer;padding:4px 0;font-size:13px}.rule-reference p{margin:6px 0}.rule-reference code{color:var(--ink,#24324b)}
|
||||||
|
.rule-change-preview{display:grid;grid-template-columns:1fr 1fr;gap:16px;padding:14px;margin:0 0 20px;background:var(--surface-subtle,#f7f9fc);border:1px solid var(--line,#e2e7f0);border-radius:4px}.rule-change-preview span{font-size:12px;color:var(--muted-ink,#62718a)}.rule-change-preview p{margin:7px 0 0;line-height:1.7;overflow-wrap:anywhere}
|
||||||
|
.rule-pending-changes{display:flex;gap:14px;flex-wrap:wrap;padding:14px 0;border-top:1px solid var(--line,#e2e7f0);font-size:13px}.rule-pending-changes strong{font-weight:600}.rule-policy-summary{font-size:12px;line-height:1.8;white-space:normal;overflow-wrap:anywhere}
|
||||||
|
.rule-form-modal .ant-collapse{margin:14px 0}.quality-targets-panel .ant-table-cell{vertical-align:middle}
|
||||||
|
@media(max-width:700px){.rule-pipeline{flex-direction:column}.rule-pipeline li+li{border-left:0;border-top:1px solid var(--line,#e2e7f0)}.rule-pipeline li+li::before{content:'↓'}.rule-change-preview{grid-template-columns:1fr}.target-filters{width:100%}.target-filters>.ant-select:nth-child(2){flex:1;min-width:170px}.rule-page-toolbar>.task-actions{width:100%;justify-content:flex-end}}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
.rule-settings .ant-tabs-tab-btn{color:var(--muted-ink,#62718a)}.rule-settings .ant-tabs-tab-active .ant-tabs-tab-btn{color:var(--blue,#607ae1)}
|
||||||
|
|
||||||
|
|
||||||
|
.rule-form-logic{grid-template-columns:1fr}.rule-order-error{margin-bottom:16px}
|
||||||
|
|
||||||
|
.result-condition-branch{border:1px solid var(--line,#e2e7f0);border-radius:4px;padding:12px 14px;margin:12px 0}
|
||||||
|
.result-branch-heading{display:flex;align-items:center;justify-content:space-between;margin-bottom:10px}.result-branch-heading strong{font-size:13px;font-weight:600}
|
||||||
|
.result-condition-fields{display:grid;grid-template-columns:minmax(0,1.5fr) minmax(110px,.8fr) minmax(0,1fr);gap:12px}
|
||||||
|
.result-formula-modal .ant-form-item{margin-bottom:12px}.result-formula-modal .rule-change-preview{padding:10px 12px;margin-bottom:14px}.result-formula-modal .result-rule-options{margin:4px 0}.result-rule-options>summary{font-size:12px}
|
||||||
|
.result-priority-hint,.result-fallback{font-size:12px;color:var(--muted-ink,#62718a);margin:14px 0 8px}.result-fallback{display:flex;align-items:center;justify-content:space-between;gap:12px}
|
||||||
|
@media(max-width:600px){.result-condition-fields{grid-template-columns:1fr 1fr}.result-condition-fields>.ant-form-item:first-child{grid-column:1/-1}.result-condition-branch{padding:10px}.result-formula-modal .rule-change-preview p{font-size:13px}}
|
||||||
|
|
||||||
|
.formula-input-toolbar{display:flex;align-items:center;justify-content:space-between;gap:8px;flex-wrap:wrap;margin-bottom:6px}.formula-operator-buttons{display:flex;align-items:center;gap:2px}.formula-operator-buttons .ant-btn{min-width:28px;padding-inline:6px}
|
||||||
|
.chinese-formula-editor textarea{font-family:inherit;line-height:1.7}.formula-input-error{font-size:12px;color:var(--danger,#d14343);margin-top:5px;line-height:1.5}.formula-field-chooser{width:min(310px,calc(100vw - 56px))}.formula-field-list{max-height:280px;overflow:auto;margin-top:8px}.formula-field-list h4{font-size:12px;font-weight:500;color:var(--muted-ink,#62718a);margin:10px 6px 4px}.formula-field-list .ant-btn{height:auto;min-height:30px;justify-content:flex-start;white-space:normal;text-align:left;font-size:13px;padding:5px 8px}.formula-field-list .ant-btn>span{white-space:normal;overflow-wrap:anywhere}.formula-field-list>p{font-size:12px;color:var(--muted-ink,#62718a);padding:8px}
|
||||||
|
.result-formula-modal .formula-editor-disabled{opacity:.65}.result-formula-modal .ant-alert{margin-bottom:12px}
|
||||||
|
@media(max-width:600px){.formula-input-toolbar{gap:4px}.formula-operator-buttons .ant-btn{min-width:24px;padding-inline:4px}}
|
||||||
|
|
||||||
|
.result-formula-fallback{margin-top:16px;padding-top:14px;border-top:1px solid var(--line,#e2e7f0)}
|
||||||
@@ -0,0 +1,63 @@
|
|||||||
|
import test from 'node:test';
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import { chineseFormula, compileChineseFormula, formulaFieldReference, insertFormulaPart, rowFormulaFields, metricFormulaFields } from '../src/formulaLanguage.ts';
|
||||||
|
const schema={sourceFields:{black:{platingWeight:'送电镀重量',shipmentWeight:'黑片出货重量',inspectionNote:'检验备注',issueLocation:'发料地点'},bright:{scrapWeight:'检包入废品库重量',applicability:'是否电镀来料/二等品库来料'}},rowTargets:{black:['black_good_weight','black_scrap_weight','black_total_weight'],bright:['bright_scrap_weight']},componentLabels:{black_good_weight:'黑片合格重量',black_scrap_weight:'黑片报废重量',black_total_weight:'黑片总重量',bright_scrap_weight:'亮片报废重量'},metricCodes:['blackRate','brightRate','compositeRate'],metricLabels:{blackRate:'黑片合格率',brightRate:'亮片合格率'}};
|
||||||
|
const fields=rowFormulaFields(schema,'black');
|
||||||
|
test('formula catalogs are stage-specific, exclude text, and forbid future metric references',()=>{
|
||||||
|
assert.ok(fields.some(f=>f.key==='platingWeight'));assert.ok(!fields.some(f=>['inspectionNote','issueLocation','scrapWeight'].includes(f.key)));
|
||||||
|
assert.ok(rowFormulaFields(schema,'bright').some(f=>f.key==='scrapWeight'));
|
||||||
|
assert.deepEqual(metricFormulaFields(schema,'brightRate').filter(f=>f.group==='已计算指标').map(f=>f.key),['blackRate']);
|
||||||
|
assert.ok(!metricFormulaFields(schema,'blackRate').some(f=>f.key==='compositeRate'));
|
||||||
|
});
|
||||||
|
test('existing formulas display Chinese references, including SUM and arithmetic',()=>{
|
||||||
|
assert.equal(chineseFormula('platingWeight + shipmentWeight',fields),'[送电镀重量] + [黑片出货重量]');
|
||||||
|
assert.equal(chineseFormula('SUM(black_good_weight, black_scrap_weight) / black_total_weight',fields),'求和([黑片合格重量], [黑片报废重量]) ÷ [黑片总重量]');
|
||||||
|
});
|
||||||
|
test('raw formulas round-trip exactly, including whitespace, numbers and nesting',()=>{
|
||||||
|
for(const source of ['platingWeight + shipmentWeight','SUM(black_good_weight, black_scrap_weight) / black_total_weight',' ( -platingWeight + .50 ) * 2.00\n','0']){
|
||||||
|
assert.deepEqual(compileChineseFormula(chineseFormula(source,fields),fields),{formula:source});
|
||||||
|
assert.deepEqual(compileChineseFormula(source,fields),{formula:source});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
test('users can type Chinese names with or without field brackets',()=>{
|
||||||
|
assert.equal(compileChineseFormula('送电镀重量 + 黑片出货重量',fields).formula,'platingWeight + shipmentWeight');
|
||||||
|
assert.equal(compileChineseFormula('求和([黑片合格重量],[黑片报废重量]) ÷ [黑片总重量]',fields).formula,'SUM(black_good_weight,black_scrap_weight) / black_total_weight');
|
||||||
|
assert.equal(compileChineseFormula('−[送电镀重量] × 2 + 1',fields).formula,'-platingWeight * 2 + 1');
|
||||||
|
});
|
||||||
|
test('longest field name wins without rewriting raw alias prefixes',()=>{
|
||||||
|
const catalog=[{key:'a',label:'重量',group:'来源字段'},{key:'ab',label:'重量合计',group:'来源字段'},{key:'goodWeight',label:'合格',group:'来源字段'},{key:'g',label:'good',group:'计算结果'}];
|
||||||
|
assert.equal(compileChineseFormula('重量合计 - 重量',catalog).formula,'ab - a');
|
||||||
|
assert.equal(compileChineseFormula('goodWeight + g',catalog).formula,'goodWeight + g');
|
||||||
|
});
|
||||||
|
test('duplicate display names require a qualified Chinese selection',()=>{
|
||||||
|
const catalog=[{key:'source',label:'合格重量',group:'来源字段'},{key:'result',label:'合格重量',group:'计算结果'}];
|
||||||
|
assert.match(compileChineseFormula('[合格重量]',catalog).error,/重名/);
|
||||||
|
assert.equal(chineseFormula('source + result',catalog),'[来源字段·合格重量] + [计算结果·合格重量]');
|
||||||
|
assert.equal(compileChineseFormula('[来源字段·合格重量] + [计算结果·合格重量]',catalog).formula,'source + result');
|
||||||
|
});
|
||||||
|
test('field references escape closing brackets and never translate identifiers inside a label',()=>{
|
||||||
|
const catalog=[{key:'a',label:'字段]a',group:'来源字段'}];
|
||||||
|
const reference=formulaFieldReference(catalog[0],catalog);assert.equal(reference,'[字段]]a]');
|
||||||
|
assert.equal(chineseFormula(reference,catalog),reference);assert.equal(compileChineseFormula(reference,catalog).formula,'a');
|
||||||
|
});
|
||||||
|
test('unrecognized and text fields cannot be silently dropped',()=>{
|
||||||
|
for(const text of ['[不存在] + 1','[检验备注]','missingWeight','[送电镀重量'])assert.ok(compileChineseFormula(text,fields).error,text);
|
||||||
|
assert.match(compileChineseFormula('compositeRate',metricFormulaFields(schema,'blackRate')).error,/找不到字段/);
|
||||||
|
});
|
||||||
|
test('syntax validation catches incomplete arithmetic and unsupported functions without evaluating',()=>{
|
||||||
|
for(const text of ['','[送电镀重量] +','([送电镀重量]','[送电镀重量][黑片出货重量]','求和()','求和(1,)','1,2','1.2.3','2[送电镀重量]','IF(1,2,3)','1e3'])assert.ok(compileChineseFormula(text,fields).error,text);
|
||||||
|
for(const text of ['1 / 0','[送电镀重量] - -2','SUM(1,2,(3+4))'])assert.equal(compileChineseFormula(text,fields).error,undefined,text);
|
||||||
|
});
|
||||||
|
test('editor validation mirrors engine bounds on length, nesting, function arguments and numbers',()=>{
|
||||||
|
assert.match(compileChineseFormula('('.repeat(33)+'1'+')'.repeat(33),fields).error,/32/);
|
||||||
|
assert.match(compileChineseFormula('求和('+Array(21).fill('1').join(',')+')',fields).error,/20/);
|
||||||
|
assert.match(compileChineseFormula('1'.repeat(51),fields).error,/50/);
|
||||||
|
assert.match(compileChineseFormula('[送电镀重量] + 1',fields,10).error,/最多10/);
|
||||||
|
assert.equal(compileChineseFormula('求和('+Array(20).fill('1').join(',')+')',fields).error,undefined);
|
||||||
|
});
|
||||||
|
test('inserting fields replaces only the selected range and returns the new caret',()=>{
|
||||||
|
const text='[送电镀重量] + [黑片出货重量]',start=text.indexOf('[黑片出货重量]');
|
||||||
|
assert.deepEqual(insertFormulaPart(text,start,text.length,'[黑片报废重量]'),{text:'[送电镀重量] + [黑片报废重量]',caret:start+'[黑片报废重量]'.length});
|
||||||
|
assert.deepEqual(insertFormulaPart('1 + 2',4,5,'',true),{text:'1 + 求和(2)',caret:8});
|
||||||
|
assert.deepEqual(insertFormulaPart('',0,0,'',true),{text:'求和()',caret:3});
|
||||||
|
});
|
||||||
@@ -0,0 +1,73 @@
|
|||||||
|
import test from 'node:test';
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import { stageResultFormulas, describeResultFormula, replaceResultFormula, planResultMove, newResultIssue } from '../src/resultFormulas.ts';
|
||||||
|
const row=(stage,target,formula,when)=>({stage,target,formula,...(when?{when}:{}),nullPolicy:'PROPAGATE',zeroDenominatorPolicy:'ONE',nullResultPolicy:'NULL'});
|
||||||
|
const condition=value=>({field:'issueLocation',operator:'CONTAINS',value});
|
||||||
|
const schema={sourceFields:{black:{goodWeight:'合格重量',externalScrap:'外废重量',inspectionNote:'检验备注',issueLocation:'发料地点'},bright:{goodWeight:'合格重量',scrapWeight:'检包入废品库重量',applicability:'是否电镀来料/二等品库来料'}},componentLabels:{good:'黑片合格重量',scrap:'黑片报废重量',external:'黑片外废',reuse:'利用料报废扣减',reuseGood:'利用料合格扣减',total:'黑片总重量',brightGood:'亮片合格重量',brightScrap:'亮片报废重量'},rowTargets:{black:['good','external','scrap','reuse','reuseGood','total'],bright:['brightGood','brightScrap']},conditionOperators:['EQ','CONTAINS','IS_BLANK'],metricCodes:[]};
|
||||||
|
const base={schemaVersion:'v1',sourceFields:{black:{externalScrap:'外废重量'}},rowRules:[
|
||||||
|
row('black','good','goodWeight'),row('black','external','externalScrap'),row('black','external','0',{field:'inspectionNote',operator:'CONTAINS',value:'过账'}),row('black','scrap','external'),
|
||||||
|
row('black','reuse','0'),row('black','reuseGood','0'),row('black','reuse','scrap',condition('利用料')),row('black','reuseGood','good',condition('利用料')),row('black','reuse','scrap',condition('废品')),row('black','reuseGood','good',condition('废品')),
|
||||||
|
row('black','total','good + scrap - reuse - reuseGood'),row('bright','brightGood','0'),row('bright','brightGood','goodWeight',{field:'applicability',operator:'EQ',value:'是'}),row('bright','brightScrap','0'),row('bright','brightScrap','scrapWeight',{field:'applicability',operator:'EQ',value:'是'})
|
||||||
|
],metricRules:{}};
|
||||||
|
const result=(def,stage,target)=>stageResultFormulas(def,stage).find(row=>row.target===target);
|
||||||
|
test('one result per row retains every noncontiguous original step without mutation',()=>{
|
||||||
|
const before=JSON.stringify(base),black=stageResultFormulas(base,'black'),bright=stageResultFormulas(base,'bright');
|
||||||
|
assert.equal(black.length,6);assert.equal(bright.length,2);assert.deepEqual(result(base,'black','reuse').indexes,[4,6,8]);
|
||||||
|
const all=[...black,...bright].flatMap(r=>r.rules.map((rule,i)=>({rule,index:r.indexes[i]}))).sort((a,b)=>a.index-b.index);
|
||||||
|
assert.deepEqual(all.map(r=>r.rule),base.rowRules);assert.equal(JSON.stringify(base),before);
|
||||||
|
});
|
||||||
|
test('opening and applying every result is byte-identical, including omitted policies and metadata',()=>{
|
||||||
|
const def=structuredClone(base);delete def.rowRules[0].nullPolicy;def.rowRules[0].custom='preserve';def.rowRules[2].when.custom='condition metadata';
|
||||||
|
const text=JSON.stringify(def);let current=def;
|
||||||
|
for(const stage of ['black','bright'])for(const item of stageResultFormulas(def,stage))current=replaceResultFormula(current,item,structuredClone(item.rules));
|
||||||
|
assert.equal(current,def);assert.equal(JSON.stringify(current),text);
|
||||||
|
});
|
||||||
|
test('full formula includes default and conditional values for black and bright',()=>{
|
||||||
|
assert.equal(describeResultFormula(result(base,'black','external'),schema),'若检验备注包含“过账”,取0;否则取外废重量');
|
||||||
|
assert.equal(describeResultFormula(result(base,'black','reuse'),schema),'若发料地点包含“废品” 或 发料地点包含“利用料”,取黑片报废重量;否则取0');
|
||||||
|
assert.equal(describeResultFormula(result(base,'bright','brightScrap'),schema),'若是否电镀来料/二等品库来料等于“是”,取检包入废品库重量;否则取0');
|
||||||
|
});
|
||||||
|
test('different overlapping branches preserve later-write priority and explicit otherwise formulas',()=>{
|
||||||
|
const item=result(base,'black','reuse');item.rules=structuredClone(item.rules);item.rules[2].formula='2';
|
||||||
|
assert.equal(describeResultFormula(item,schema),'若发料地点包含“废品”,取2;否则(若发料地点包含“利用料”,取黑片报废重量;否则取0)');
|
||||||
|
item.rules[2].otherwiseFormula='3';assert.equal(describeResultFormula(item,schema),'若发料地点包含“废品”,取2;否则取3');
|
||||||
|
});
|
||||||
|
test('conditions with differing special policies are never coalesced',()=>{
|
||||||
|
const item=structuredClone(result(base,'black','reuse'));item.rules[2].nullResultPolicy='ERROR';
|
||||||
|
assert.match(describeResultFormula(item,schema),/否则(若/);assert.doesNotMatch(describeResultFormula(item,schema),/ 或 /);
|
||||||
|
});
|
||||||
|
test('self references retain the previous value in the combined expression',()=>{
|
||||||
|
const item={stage:'black',target:'reuse',indexes:[0,1],rules:[row('black','reuse','4'),row('black','reuse','reuse + 1',condition('利用料'))]};
|
||||||
|
assert.equal(describeResultFormula(item,schema),'若发料地点包含“利用料”,取(4) + 1;否则取4');
|
||||||
|
});
|
||||||
|
test('editing one branch preserves every other rule and field, including interleaved results',()=>{
|
||||||
|
const item=result(base,'black','reuse'),rules=structuredClone(item.rules);rules[2].formula='scrap + 1';const next=replaceResultFormula(base,item,rules);
|
||||||
|
assert.equal(next.rowRules[8].formula,'scrap + 1');for(let i=0;i<base.rowRules.length;i++)if(i!==8)assert.deepEqual(next.rowRules[i],base.rowRules[i]);
|
||||||
|
assert.equal(base.rowRules[8].formula,'scrap');assert.equal(next.metricRules,base.metricRules);assert.equal(next.sourceFields,base.sourceFields);
|
||||||
|
});
|
||||||
|
test('adding or removing conditions keeps other results and their relative order intact',()=>{
|
||||||
|
const item=result(base,'black','reuse'),rules=[...item.rules,row('black','reuse','1',condition('新条件'))];const added=replaceResultFormula(base,item,rules);
|
||||||
|
assert.equal(result(added,'black','reuse').rules.length,4);assert.deepEqual(added.rowRules.filter(r=>r.target!=='reuse'),base.rowRules.filter(r=>r.target!=='reuse'));
|
||||||
|
const removed=replaceResultFormula(added,item,rules.slice(0,1));assert.equal(result(removed,'black','reuse').rules.length,1);assert.deepEqual(removed.rowRules.filter(r=>r.target!=='reuse'),base.rowRules.filter(r=>r.target!=='reuse'));
|
||||||
|
});
|
||||||
|
test('conditional-only legacy formulas retain their original fallback rather than acquiring a zero default',()=>{
|
||||||
|
const item={stage:'black',target:'reuse',indexes:[0],rules:[row('black','reuse','2',condition('利用料'))]};
|
||||||
|
assert.equal(describeResultFormula(item,schema),'若发料地点包含“利用料”,取2;否则取原计算结果');
|
||||||
|
assert.equal(replaceResultFormula({rowRules:item.rules},item,item.rules).rowRules.length,1);
|
||||||
|
});
|
||||||
|
test('whole-result moves retain all branches and reject totals ahead of dependencies',()=>{
|
||||||
|
const moved=planResultMove(base,'black','good',1,schema);assert.ok(moved.definition);assert.equal(stageResultFormulas(moved.definition,'black')[0].target,'external');
|
||||||
|
assert.deepEqual(result(moved.definition,'black','external').rules,result(base,'black','external').rules);
|
||||||
|
assert.deepEqual(planResultMove(moved.definition,'black','good',-1,schema).definition,base);
|
||||||
|
assert.match(planResultMove(base,'black','total',-1,schema).reason,/后面还会修改/);
|
||||||
|
assert.equal(planResultMove(base,'bright','brightGood',-1,schema).definition,undefined);
|
||||||
|
});
|
||||||
|
test('new results stay in their stage and mismatched branches cannot be merged',()=>{
|
||||||
|
const next=replaceResultFormula(base,{stage:'black',target:'added'},[row('black','added','0')]);
|
||||||
|
assert.equal(next.rowRules[11].target,'added');assert.equal(next.rowRules[12].stage,'bright');
|
||||||
|
assert.throws(()=>replaceResultFormula(base,{stage:'black',target:'reuse'},[row('bright','reuse','0')]),/同一个/);
|
||||||
|
});
|
||||||
|
test('invalid branch variables remain blocked by the existing rule checker',()=>{
|
||||||
|
const item=result(base,'bright','brightScrap'),rules=structuredClone(item.rules);rules[1].formula='missingWeight';const next=replaceResultFormula(base,item,rules);
|
||||||
|
assert.match(newResultIssue(base,next,schema),/不可用的公式变量/);assert.equal(result(base,'bright','brightScrap').rules[1].formula,'scrapWeight');
|
||||||
|
});
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
import test from 'node:test';
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import { ruleLogicIssues, planRuleMove, neighboringRuleIndex, displayRowFormula, isDefaultAssignment } from '../src/ruleEditing.ts';
|
||||||
|
const schema={sourceFields:{black:{platingWeight:'送电镀重量',shipmentWeight:'黑片出货重量',responsibilityScrap:'责废总重量',materialScrap:'料废重量',externalScrap:'外废重量',inspectionNote:'检验备注'},bright:{goodWeight:'合格重量',scrapWeight:'检包入废品库重量',applicability:'是否电镀来料/二等品库来料'}},rowTargets:{black:['black_good_weight','black_responsibility_scrap','black_material_scrap','black_external_scrap','black_scrap_weight','black_total_weight'],bright:['bright_good_weight','bright_scrap_weight']},componentLabels:{black_good_weight:'黑片合格重量',black_scrap_weight:'黑片报废重量',black_total_weight:'黑片总重量'},conditionOperators:['EQ','CONTAINS','GT','IS_BLANK'],metricCodes:['blackRate','brightRate','compositeRate'],metricLabels:{blackRate:'黑片合格率'}};
|
||||||
|
const base={schemaVersion:'unchanged',sourceFields:{},rowRules:[
|
||||||
|
{stage:'black',target:'black_good_weight',formula:'platingWeight + shipmentWeight'},
|
||||||
|
{stage:'black',target:'black_responsibility_scrap',formula:'responsibilityScrap'},
|
||||||
|
{stage:'black',target:'black_material_scrap',formula:'materialScrap'},
|
||||||
|
{stage:'black',target:'black_external_scrap',formula:'externalScrap'},
|
||||||
|
{stage:'black',target:'black_external_scrap',formula:'0',when:{field:'inspectionNote',operator:'CONTAINS',value:'过账'}},
|
||||||
|
{stage:'black',target:'black_scrap_weight',formula:'SUM(black_responsibility_scrap, black_material_scrap, black_external_scrap)'},
|
||||||
|
{stage:'black',target:'black_total_weight',formula:'black_good_weight + black_scrap_weight'},
|
||||||
|
{stage:'bright',target:'bright_good_weight',formula:'0'},
|
||||||
|
{stage:'bright',target:'bright_good_weight',formula:'goodWeight',when:{field:'applicability',operator:'EQ',value:'是'}},
|
||||||
|
{stage:'bright',target:'bright_scrap_weight',formula:'0'},
|
||||||
|
{stage:'bright',target:'bright_scrap_weight',formula:'scrapWeight',when:{field:'applicability',operator:'EQ',value:'是'}},
|
||||||
|
],metricRules:{blackRate:{formula:'blackGood / blackTotal'},brightRate:{formula:'brightGood / brightTotal'},compositeRate:{formula:'blackRate * brightRate'}}};
|
||||||
|
test('baseline formulas and ordered conditional assignments remain valid without any mutation',()=>{const text=JSON.stringify(base);assert.deepEqual(ruleLogicIssues(base,schema),[]);assert.equal(JSON.stringify(base),text);});
|
||||||
|
test('a move swaps exactly two same-stage rows, retaining every other row and metadata',()=>{
|
||||||
|
const text=JSON.stringify(base),result=planRuleMove(base,0,1,schema);assert.ok(result.definition);assert.equal(result.definition.rowRules[0].target,'black_responsibility_scrap');assert.equal(result.definition.rowRules[1].target,'black_good_weight');
|
||||||
|
assert.deepEqual(result.definition.rowRules.slice(2),base.rowRules.slice(2));assert.equal(JSON.stringify(base),text);assert.deepEqual(planRuleMove(result.definition,1,-1,schema).definition,base);
|
||||||
|
});
|
||||||
|
test('moves do not cross stage boundaries',()=>{assert.equal(neighboringRuleIndex(base.rowRules,6,1),undefined);assert.equal(neighboringRuleIndex(base.rowRules,7,-1),undefined);assert.equal(planRuleMove(base,7,-1,schema).definition,undefined);});
|
||||||
|
test('moving a conditional assignment above its default is rejected',()=>{const result=planRuleMove(base,8,-1,schema);assert.equal(result.definition,undefined);assert.match(result.reason,/默认值应放在条件覆盖之前/);});
|
||||||
|
test('moving totals ahead of their component assignments is rejected',()=>{const result=planRuleMove(base,5,-1,schema);assert.equal(result.definition,undefined);assert.match(result.reason,/后面还会修改/);});
|
||||||
|
test('unknown variables, text arithmetic and forward metric references are caught',()=>{
|
||||||
|
for(const formula of ['typoWeight','inspectionNote + 1']){const def=structuredClone(base);def.rowRules[0].formula=formula;assert.ok(ruleLogicIssues(def,schema).some(issue=>issue.key.startsWith('variable:')));}
|
||||||
|
const def=structuredClone(base);def.metricRules.blackRate.formula='compositeRate';assert.ok(ruleLogicIssues(def,schema).some(issue=>issue.key.startsWith('metric-variable:')));
|
||||||
|
});
|
||||||
|
test('duplicate conditions with different formulas are rejected regardless of JSON property order',()=>{const def=structuredClone(base);def.rowRules.push({stage:'bright',target:'bright_scrap_weight',formula:'1',when:{value:'是',operator:'EQ',field:'applicability'}});assert.ok(ruleLogicIssues(def,schema).some(issue=>issue.key.startsWith('duplicate:')));});
|
||||||
|
test('legacy partial overrides keep access to baseline components',()=>{const def={rowRules:[{stage:'black',target:'black_total_weight',formula:'black_good_weight + black_scrap_weight'}]};assert.deepEqual(ruleLogicIssues(def,schema),[]);});
|
||||||
|
test('source aliases are rendered in Chinese while the original formula is retained',()=>{const row=base.rowRules[10];assert.equal(displayRowFormula(row,schema),'检包入废品库重量');assert.equal(row.formula,'scrapWeight');assert.equal(isDefaultAssignment(base.rowRules[9],9,base.rowRules),true);assert.equal(isDefaultAssignment(row,10,base.rowRules),false);});
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
import test from 'node:test';
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import { displayFormula, stageRuleRows, ruleChangeSummary, matchingTarget, policyDescription } from '../src/rulePresentation.ts';
|
||||||
|
const original={sourceFields:{black:{platingWeight:'送电镀重量'},bright:{goodWeight:'合格重量'}},rowRules:Array.from({length:22},(_,i)=>({stage:i<13?'black':'bright',target:i%3===0?'black_good_weight':i%3===1?'black_scrap_weight':'black_reuse_good',formula:String(i),when:{field:'inspectionNote',operator:'CONTAINS',value:'过账'}})),metricRules:{blackRate:{formula:'blackGood / blackTotal'}}};
|
||||||
|
test('stage tables keep every execution index and full rule unchanged',()=>{
|
||||||
|
const before=JSON.stringify(original);const all=[...stageRuleRows(original,'black'),...stageRuleRows(original,'bright')].sort((a,b)=>a.index-b.index);
|
||||||
|
assert.equal(all.length,22);assert.deepEqual(all.map(({index,...row})=>row),original.rowRules);assert.equal(JSON.stringify(original),before);assert.deepEqual(ruleChangeSummary(original,structuredClone(original)),[]);
|
||||||
|
});
|
||||||
|
test('business formula translation explains percentages without mutating source rules',()=>{
|
||||||
|
assert.equal(displayFormula('blackRate * brightRate'),'黑片合格率 × 亮片合格率');assert.match(policyDescription({zeroDenominatorPolicy:'ONE',nullResultPolicy:'NULL'}),/分母为0:按100%处理/);assert.match(policyDescription({zeroDenominatorPolicy:'ONE'},false),/分母为0:取1/);
|
||||||
|
const next=structuredClone(original);next.metricRules.blackRate.formula='(blackGood / blackTotal)';assert.deepEqual(ruleChangeSummary(original,next),['合格率公式 1 项']);assert.notEqual(original.metricRules.blackRate.formula,next.metricRules.blackRate.formula);
|
||||||
|
});
|
||||||
|
test('target display preserves existing specificity and group tie-break precedence',()=>{
|
||||||
|
const overall={dimensions:{},value:.955},department={dimensions:{department:'A'},value:.96},group={dimensions:{group:'G'},value:.97},specific={dimensions:{department:'A',group:'G'},value:.98};const list=[overall,department,group,specific];const before=JSON.stringify(list);
|
||||||
|
assert.equal(matchingTarget(list,{department:'A',group:'G'}),specific);assert.equal(matchingTarget(list.slice(0,3),{department:'A',group:'G'}),group);assert.equal(matchingTarget(list,{department:'A',group:'OTHER'}),department);assert.equal(matchingTarget(list,{department:'B'}),overall);assert.equal(JSON.stringify(list),before);
|
||||||
|
});
|
||||||
|
test('stage table reflects the actual row order without business grouping',()=>{
|
||||||
|
const definition={rowRules:[{stage:'black',target:'black_responsibility_scrap',formula:'1'},{stage:'black',target:'black_good_weight',formula:'2'},{stage:'black',target:'black_material_scrap',formula:'3'}]};
|
||||||
|
assert.deepEqual(stageRuleRows(definition,'black').map(row=>row.target),['black_responsibility_scrap','black_good_weight','black_material_scrap']);
|
||||||
|
});
|
||||||
Reference in New Issue
Block a user