修复:分类规则仅处理未分类并保留已有归属

This commit is contained in:
2026-10-31 19:18:46 +08:00
parent aa7c320dc6
commit cbe7fc17bb
20 changed files with 320 additions and 36 deletions
+2 -2
View File
@@ -41,7 +41,7 @@ export function ClassificationRuleEditor({ children, onUnauthorized }: {
catch(value){setError(value instanceof Error?value.message:'规则保存失败');}
};
return <>{children(open)}<Modal className="management-modal classification-rule-modal" width={880} open={!!selection}
title={project?'编辑项目组分类':'编辑业务分组分类'} okText={project?'保存到基础对应':'保存到条件匹配'} okButtonProps={{disabled:busy||(!project&&!preview)||!context?.ready}}
title={project?'编辑项目组分类':'编辑业务分组分类'} okText={project?'保存到基础对应':preview?'保存到条件匹配':'请先预览影响'} okButtonProps={{disabled:busy||(!project&&!preview)||!context?.ready}}
onOk={save} onCancel={()=>{revision.current++;setBusy(false);setSelection(null);}}>
{project?<p>客户代码 {String(selection?.row.customerCode)} · 业务分组 {String(selection?.row.businessGroup)}</p>:<><div className="classification-rule-fields">
<label>规则名称<Input aria-label="分类规则名称" value={name} maxLength={160} placeholder="默认使用业务分组名称" onChange={e=>{setName(e.target.value);}}/></label>
@@ -59,7 +59,7 @@ export function ClassificationRuleEditor({ children, onUnauthorized }: {
</div>)}</div></>}
<label className="classification-target">{project?'项目组':'业务分组'}<AutoComplete aria-label={project?'目标项目组':'目标业务分组'} value={target} maxLength={160} options={(project?context?.projectGroups??[]:context?.groups??[]).map(value=>({value}))}
filterOption={(input,option)=>String(option?.value).includes(input)} placeholder={project?'选择项目组':'选择业务分组'} onChange={value=>{setTarget(value);resetPreview();setBusy(false);}}/></label>
{!project&&<div className="classification-preview-action"><span>保留条件同时满足时匹配,覆盖全部月份和来源文件。</span><Button loading={busy} onClick={()=>void inspect()}>预览影响</Button></div>}
{!project&&<div className="classification-preview-action"><span>只处理未分类记录,覆盖全部月份和来源文件;已有分类保持不动。</span><Button loading={busy} onClick={()=>void inspect()}>预览影响</Button></div>}
{error&&<Alert type="error" showIcon message={error}/>}
{preview&&<div className="classification-impact"><Space wrap><Tag color="blue">命中 {Number(preview.matchedRows).toLocaleString()} 行</Tag><Tag>总重量 {Number(preview.totalWeight).toLocaleString()} kg</Tag><Tag color={Number(preview.changedRows)>0?'orange':'default'}>当前归属不同 {Number(preview.changedRows).toLocaleString()} 行</Tag></Space>
<Table size="small" bordered scroll={{x:720}} pagination={{pageSize:15,showSizeChanger:false}} rowKey={row=>JSON.stringify([row.stage,row.department,row.month,row.currentGroup])} dataSource={(preview.items??[]) as Record<string,unknown>[]}
+1 -1
View File
@@ -555,7 +555,7 @@ function ConfigManagementPage({ kind, user, onUnauthorized, onNavigate, extraSec
</span> },
];
const simpleStageLabel: Record<string, string> = { QUEUED: '等待处理', VALIDATING: '检查配置与来源', VERSION_CREATED: '保存配置', REBUILDING: '重新计算报表', PUBLISHING: '更新当前报表', COMPLETED: '已完成', FAILED: '处理失败' };
const simpleStageLabel: Record<string, string> = { QUEUED: '等待处理', VALIDATING: '检查配置与来源', VERSION_CREATED: '保存配置', CLASSIFYING_UNASSIGNED:'处理未分类记录', REBUILDING: '重新计算报表', PUBLISHING: '更新当前报表', COMPLETED: '已完成', FAILED: '处理失败' };
const applyCurrent = async () => {
try {
await form.validateFields();
+4 -4
View File
@@ -198,7 +198,7 @@ export function MappingDefinitionEditor({ value, onChange, simplified = false, r
}
type MatchCondition = { field: string; operator: string; value?: string };
type MatchRule = { id?: string; name: string; enabled: boolean; priority: number; stage: string; conditions: MatchCondition[]; target: string; value: string };
type MatchRule = { onlyUnclassified?:boolean; id?: string; name: string; enabled: boolean; priority: number; stage: string; conditions: MatchCondition[]; target: string; value: string };
type MatchMetadata = { fields?: unknown[]; operators?: unknown[]; targets?: unknown[]; stages?: unknown[]; defaultRules?: unknown[]; limits?: Record<string, unknown> };
const defaultMatchRules: MatchRule[] = [{ id: 'default-vcm-group', name: '成品规格含VCM归入工业电机-VCM', enabled: true, priority: 100, stage: 'all', conditions: [{ field: '成品规格', operator: 'CONTAINS', value: 'VCM' }], target: 'group', value: '工业电机-VCM' }];
const plainObject = (value: unknown) => value && typeof value === 'object' && !Array.isArray(value) ? value as Record<string, unknown> : {};
@@ -229,11 +229,11 @@ export function MatchRulesDefinitionEditor({ value, onChange, metadata, readOnly
const sourceRules = Array.isArray(value.matchRules) ? value.matchRules : (metadata?.defaultRules ?? defaultMatchRules);
const rules = sourceRules.map((item, index) => {
const row = plainObject(item);
return { id: String(row.id || `match-${index + 1}`), name: String(row.name || `条件规则 ${index + 1}`), enabled: row.enabled !== false, priority: Number(row.priority ?? (index + 1) * 100), stage: String(row.stage || 'all'), conditions: Array.isArray(row.conditions) ? row.conditions.map(condition => { const conditionRow = plainObject(condition); return { field: String(conditionRow.field || ''), operator: String(conditionRow.operator || 'EQUALS'), ...(conditionRow.value === undefined ? {} : { value: String(conditionRow.value) }) }; }) : [], target: String(row.target || 'group'), value: String(row.value || '') } as MatchRule;
return { ...(row.onlyUnclassified===undefined?{}:{onlyUnclassified:row.onlyUnclassified===true}), id: String(row.id || `match-${index + 1}`), name: String(row.name || `条件规则 ${index + 1}`), enabled: row.enabled !== false, priority: Number(row.priority ?? (index + 1) * 100), stage: String(row.stage || 'all'), conditions: Array.isArray(row.conditions) ? row.conditions.map(condition => { const conditionRow = plainObject(condition); return { field: String(conditionRow.field || ''), operator: String(conditionRow.operator || 'EQUALS'), ...(conditionRow.value === undefined ? {} : { value: String(conditionRow.value) }) }; }) : [], target: String(row.target || 'group'), value: String(row.value || '') } as MatchRule;
});
const labelFor = (options: MatchOption[], id: string) => options.find(option => option.value === id)?.label || id;
const conditionText = (condition: MatchCondition) => `${labelFor(fields, condition.field)} ${labelFor(operators, condition.operator)}${['IS_BLANK', 'IS_NOT_BLANK'].includes(condition.operator) ? '' : ` ${condition.value || '…'}`}`;
const readableRule = (rule: MatchRule) => `当 ${rule.conditions.map(conditionText).join(' 且 ') || '(未设置条件)'} → ${labelFor(targets, rule.target)}:${rule.value || '(未填写)'}`;
const readableRule = (rule: MatchRule) => `${rule.onlyUnclassified?'仅未分类:':''}当 ${rule.conditions.map(conditionText).join(' 且 ') || '(未设置条件)'} → ${labelFor(targets, rule.target)}:${rule.value || '(未填写)'}`;
const commit = (next: MatchRule[]) => onChange({ ...value, matchRules: next.map((rule, index) => ({ ...rule, id: rule.id || `match-${index + 1}` })) });
const open = (rule?: MatchRule) => {
setError('');
@@ -268,7 +268,7 @@ export function MatchRulesDefinitionEditor({ value, onChange, metadata, readOnly
{ title: '判断值', render: (_, condition, index) => ['IS_BLANK', 'IS_NOT_BLANK'].includes(condition.operator) ? <span className="structured-config-muted">无需填写</span> : <Input value={condition.value} onChange={event => setEditing({ ...editing, conditions: editing.conditions.map((row, rowIndex) => rowIndex === index ? { ...row, value: event.target.value } : row) })} /> },
{ title: '', width: 82, render: (_, __, index) => <Button type="link" danger disabled={editing.conditions.length <= 1} onClick={() => setEditing({ ...editing, conditions: editing.conditions.filter((__, rowIndex) => rowIndex !== index) })}>移除</Button> },
]} />
<div className="structured-config-form-grid" style={{ marginTop: 16 }}><Form.Item label="目标类型"><Select value={editing.target} options={targets} onChange={target => setEditing({ ...editing, target })} /></Form.Item><Form.Item label="匹配结果" required><Input value={editing.value} maxLength={190} onChange={event => setEditing({ ...editing, value: event.target.value })} placeholder="例如:工业电机-VCM" /></Form.Item></div>
<Form.Item label="处理范围"><Switch checked={editing.onlyUnclassified===true} disabled={editing.target!=='group' || rules.some(rule=>rule.id===editing.id && rule.onlyUnclassified===true)} checkedChildren="仅未分类" unCheckedChildren="全部匹配行" onChange={onlyUnclassified=>setEditing({...editing,onlyUnclassified})}/></Form.Item><div className="structured-config-form-grid" style={{ marginTop: 16 }}><Form.Item label="目标类型"><Select value={editing.target} options={targets} disabled={editing.onlyUnclassified===true} onChange={target => setEditing({ ...editing, target })} /></Form.Item><Form.Item label="匹配结果" required><Input value={editing.value} maxLength={190} onChange={event => setEditing({ ...editing, value: event.target.value })} placeholder="例如:工业电机-VCM" /></Form.Item></div>
{error && <Alert showIcon type="error" message={error} />}
</Form>}
</Modal>
+4 -3
View File
@@ -7,7 +7,7 @@ export function classificationConditions(row: Record<string, unknown>) {
return [['@department', row.department], ['@product', row.product], ['PDT代码', row.pdtCode], ['销售片区', row.salesRegion]].map(([field,value]) => ({field: String(field), operator: text(value) ? 'EQUALS' : 'IS_BLANK', value: text(value)}));
}
export function classificationSignature(stage: string, conditions: ClassificationCondition[]) {
return JSON.stringify([stage, (Array.isArray(conditions) ? conditions : []).map(c => [c.field, c.operator, c.value ?? '']).sort((a,b)=>JSON.stringify(a).localeCompare(JSON.stringify(b)))]);
return JSON.stringify([stage, (Array.isArray(conditions) ? conditions : []).map(c => [c.field, c.operator, c.value ?? '']).sort((a,b)=>JSON.stringify(a)<JSON.stringify(b)?-1:JSON.stringify(a)>JSON.stringify(b)?1:0)]);
}
export function classificationRuleId(row: Record<string, unknown>, options: ClassificationRuleOptions = {}) {
const scope = classificationSignature(options.stage ?? text(row.stage), options.conditions ?? classificationConditions(row));
@@ -45,12 +45,13 @@ export function editClassification(base: Definition, selection: ClassificationSe
if (!conditions.length || conditions.length > 4 || new Set(conditions.map(c=>c.field)).size !== conditions.length) throw new Error('请保留至少一项且不重复的匹配条件');
if (conditions.some(c=>!['@department','@product','PDT代码','销售片区'].includes(c.field) || !['EQUALS','IS_BLANK'].includes(c.operator) || (c.operator === 'EQUALS' && !c.value.trim()))) throw new Error('请检查匹配条件');
const rules = Array.isArray(result.matchRules) ? result.matchRules as Definition[] : structuredClone(defaultRules) as Definition[];
const id = classificationRuleId(row, {conditions,stage});
const same = rules.find(rule=>rule.target==='group' && rule.value===target && classificationSignature(String(rule.stage),rule.conditions as ClassificationCondition[])===classificationSignature(stage,conditions));
const id = same?.id ? String(same.id) : classificationRuleId(row, {conditions,stage});
const prior = rules.find(rule => rule.id === id);
if (prior && classificationSignature(String(prior.stage), prior.conditions as ClassificationCondition[]) !== classificationSignature(stage,conditions)) throw new Error('规则标识冲突,请在条件匹配中维护');
const duplicate = rules.find(rule=>rule.enabled !== false && rule.target === 'group' && rule.value !== target && classificationSignature(String(rule.stage), rule.conditions as ClassificationCondition[]) === classificationSignature(stage,conditions));
if (duplicate) throw new Error(`相同条件已指向“${String(duplicate.value)}”,请在条件匹配中编辑已有规则`);
result.matchRules = [{ id, name: options.name?.trim() || `${target}分类规则`, enabled: true, priority: -10000 + (4-conditions.length)*100 + (stage === 'all' ? 10 : 0), stage, conditions, target: 'group', value: target }, ...rules.filter(rule => rule.id !== id)];
result.matchRules = [{ id, name: options.name?.trim() || `${target}分类规则`, enabled: true, onlyUnclassified:true, priority: -10000 + (4-conditions.length)*100 + (stage === 'all' ? 10 : 0), stage, conditions, target: 'group', value: target }, ...rules.filter(rule => rule.id !== id)];
if ((result.matchRules as unknown[]).length > 100) throw new Error('条件规则已满100条,请先整理规则');
}
return result;
+8 -6
View File
@@ -45,8 +45,8 @@ export function configurationTables(value:Definition,scope:ConfigurationScope='a
}
if(scope==='all'||scope==='matchRules'){
const rules=Array.isArray(value.matchRules)?value.matchRules:defaults;
tables.push({name:'条件匹配',headers:['规则编号','规则名称','优先级','适用范围','目标类型','目标分类','状态','条件序号','条件字段','字段说明','判断方式','判断值'],rows:array(rules).flatMap((rule,index)=>array(rule.conditions).map((condition,n)=>[
text(rule.id)||`match-${index+1}`,text(rule.name),text(rule.priority),STAGES[text(rule.stage)]??text(rule.stage),TARGETS[text(rule.target)]??text(rule.target),text(rule.value),state(rule.enabled),String(n+1),text(condition.field),FIELDS[text(condition.field)]??text(condition.field),OPERATORS[text(condition.operator)]??text(condition.operator),text(condition.value)]))});
tables.push({name:'条件匹配',headers:['规则编号','规则名称','优先级','适用范围','目标类型','目标分类','状态','条件序号','条件字段','字段说明','判断方式','判断值','仅未分类'],rows:array(rules).flatMap((rule,index)=>array(rule.conditions).map((condition,n)=>[
text(rule.id)||`match-${index+1}`,text(rule.name),text(rule.priority),STAGES[text(rule.stage)]??text(rule.stage),TARGETS[text(rule.target)]??text(rule.target),text(rule.value),state(rule.enabled),String(n+1),text(condition.field),FIELDS[text(condition.field)]??text(condition.field),OPERATORS[text(condition.operator)]??text(condition.operator),text(condition.value),yes(rule.onlyUnclassified===true)]))});
}
if(scope==='all'){
tables.push({name:'组织层级',headers:['组织编码','上级组织编码'],rows:array(value.organizationHierarchy).map(row=>[text(row.code),text(row.parentCode)])});
@@ -64,8 +64,10 @@ export function configurationTables(value:Definition,scope:ConfigurationScope='a
export function importConfigurationTables(base:Definition,tables:ConfigurationTable[],scope:ConfigurationScope,mode:ImportMode,defaults:unknown[]=[]){
const result=structuredClone(base);const expected=configurationTables(base,scope,defaults);const changes:{name:string;rows:number;added:number;updated:number;removed:number}[]=[];
const names=new Set<string>();
for(const table of tables){
for(const incomingTable of tables){
let table=incomingTable;
const original=expected.find(item=>item.name===table.name);if(!original)throw new Error(`工作表“${table.name}”不属于当前配置类型`);
if(table.name==='条件匹配'&&equal(table.headers,original.headers.slice(0,-1))){const prior=new Map(array(Array.isArray(base.matchRules)?base.matchRules:defaults).map(rule=>[text(rule.id),rule]));table={...table,headers:original.headers,rows:table.rows.map(row=>[...row,yes(prior.get(row[0])?.onlyUnclassified===true)])};}
if(names.has(table.name))throw new Error(`重复工作表:${table.name}`);names.add(table.name);
if(!equal(table.headers,original.headers))throw new Error(`${table.name}表头不匹配,请使用本页面导出的表格`);
if(table.rows.length>20000)throw new Error(`${table.name}超过20000行上限`);
@@ -98,12 +100,12 @@ export function importConfigurationTables(base:Definition,tables:ConfigurationTa
}else if(table.name==='条件匹配'){
const previous=array(Array.isArray(base.matchRules)?base.matchRules:defaults);oldIds=previous.map(row=>text(row.id));const byId=new Map<string,Definition>();
for(const [n,cells] of table.rows.entries()){
const [id,name,priority,stageLabel,targetLabel,value,status,position,fieldLabel,_fieldDescription,operatorLabel,conditionValue]=cells;
const [id,name,priority,stageLabel,targetLabel,value,status,position,fieldLabel,_fieldDescription,operatorLabel,conditionValue,unclassifiedOnly]=cells;
const stage=reverse(STAGES,stageLabel),target=reverse(TARGETS,targetLabel),field=fieldLabel,operator=reverse(OPERATORS,operatorLabel);
if(!/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/.test(id)||!name||!value||name.length>200||value.length>200)throw new Error(`条件匹配第${n+2}行规则编号、名称或目标分类无效`);
if(!STAGES[stage]||!TARGETS[target]||!OPERATORS[operator]||!field||(field.startsWith('@')&&!Object.hasOwn(FIELDS,field))||field.length>200||(!['IS_BLANK','IS_NOT_BLANK'].includes(operator)&&!conditionValue)||conditionValue.length>200)throw new Error(`条件匹配第${n+2}行条件无效`);
if(['IS_BLANK','IS_NOT_BLANK'].includes(operator)&&conditionValue)throw new Error(`条件匹配第${n+2}行空值判断不应填写判断值`);
const metadata={id,name,priority:number(priority,'优先级',-10000,10000),stage,target,value,enabled:enabled(status)};
const prior=previous.find(rule=>rule.id===id);const scope=enabled(unclassifiedOnly,false);const metadata={id,name,priority:number(priority,'优先级',-10000,10000),stage,target,value,enabled:enabled(status),...(scope||Object.hasOwn(prior??{},'onlyUnclassified')?{onlyUnclassified:scope}:{})};if(scope&&target!=='group')throw new Error('仅未分类只适用于业务分组规则');
const row=byId.get(id);if(row&&!equal({...row,conditions:undefined},{...metadata,conditions:undefined}))throw new Error(`规则${id}各行的名称、目标、优先级或状态不一致`);
const rule=row??{...metadata,conditions:[]};const conditions=rule.conditions as Definition[];const order=number(position,'条件序号',1,20);
if(conditions.some(c=>c.order===order))throw new Error(`规则${id}条件序号重复`);conditions.push({order,field,operator,value:conditionValue});byId.set(id,rule);
@@ -148,7 +150,7 @@ export async function createConfigurationWorkbook(value:Definition,scope:Configu
table.rows.forEach(row=>sheet.addRow(row.map((value,index)=>numeric.has(table.headers[index])&&value!==''?Number(value):value)));sheet.columns.forEach((column,index)=>{column.numFmt=numeric.has(table.headers[index])?'0':'@';column.alignment={vertical:'middle',wrapText:true};});
sheet.getRow(1).font={bold:true,color:{argb:'FFFFFFFF'}};sheet.getRow(1).fill={type:'pattern',pattern:'solid',fgColor:{argb:'FF5769B8'}};sheet.getRow(1).height=30;
sheet.autoFilter={from:{row:1,column:1},to:{row:Math.max(1,table.rows.length+1),column:table.headers.length}};
sheet.eachRow((row,n)=>{if(n>1){let lines=1;row.eachCell((cell,index)=>{const width=Number(sheet.getColumn(index).width)||22;const length=Array.from(cell.text).reduce((sum,char)=>sum+(char.charCodeAt(0)>255?2:1),0);lines=Math.max(lines,Math.ceil(length/Math.max(8,width-2)));const header=table.headers[index-1];const choices=header==='状态'?['启用','停用']:['明确不设归属','允许空值','使用默认对应'].includes(header)?['是','否']:header==='适用范围'||header==='阶段'?Object.values(STAGES):header==='目标类型'?Object.values(TARGETS):header==='判断方式'&&table.name==='条件匹配'?Object.values(OPERATORS):null;if(choices)cell.dataValidation={type:'list',allowBlank:false,formulae:['"'+choices.join(',')+'"']};});row.height=Math.min(409,Math.max(24,lines*16));}});
sheet.eachRow((row,n)=>{if(n>1){let lines=1;row.eachCell((cell,index)=>{const width=Number(sheet.getColumn(index).width)||22;const length=Array.from(cell.text).reduce((sum,char)=>sum+(char.charCodeAt(0)>255?2:1),0);lines=Math.max(lines,Math.ceil(length/Math.max(8,width-2)));const header=table.headers[index-1];const choices=header==='状态'?['启用','停用']:['明确不设归属','允许空值','使用默认对应','仅未分类'].includes(header)?['是','否']:header==='适用范围'||header==='阶段'?Object.values(STAGES):header==='目标类型'?Object.values(TARGETS):header==='判断方式'&&table.name==='条件匹配'?Object.values(OPERATORS):null;if(choices)cell.dataValidation={type:'list',allowBlank:false,formulae:['"'+choices.join(',')+'"']};});row.height=Math.min(409,Math.max(24,lines*16));}});
}
return workbook;
}