优化:完善分类规则与Excel配置维护并加速查询翻页

This commit is contained in:
2026-10-31 17:50:14 +08:00
parent 9dbe85c65c
commit aa7c320dc6
56 changed files with 1709 additions and 440 deletions
@@ -0,0 +1,55 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { editClassification, classificationRuleId } from '../src/classificationMaintenance.ts';
const source = {stage:'black',department:'产业部A',product:'产品A',pdtCode:'',salesRegion:'销售区A'};
const selection={kind:'group',row:source};
const defaults=[{id:'default',target:'group',value:'默认分类'}];
test('blank-key source creates a narrowly scoped rule and preserves inherited defaults',()=>{
const base={projectGroupLookup:{'001|G':'项目组A'},extra:['keep']};
const result=editClassification(base,selection,'业务组A',defaults);
assert.deepEqual(result.matchRules[0].conditions,[
{field:'@department',operator:'EQUALS',value:'产业部A'},
{field:'@product',operator:'EQUALS',value:'产品A'},
{field:'PDT代码',operator:'IS_BLANK',value:''},
{field:'销售片区',operator:'EQUALS',value:'销售区A'},
]);
assert.equal(result.matchRules[0].stage,'black');assert.deepEqual(result.matchRules[1],defaults[0]);
assert.deepEqual(base,{projectGroupLookup:{'001|G':'项目组A'},extra:['keep']});
const changed=editClassification(result,selection,'业务组A',defaults);
assert.equal(changed.matchRules.length,2);assert.equal(changed.matchRules[0].value,'业务组A');
assert.throws(()=>editClassification(result,selection,'业务组B',defaults),/相同条件/);
assert.notEqual(classificationRuleId(source),classificationRuleId({...source,stage:'bright'}));
});
test('successive group and project edits accumulate without replacing other mappings or explicit empty rules',()=>{
let result=editClassification({matchRules:[],categoryLookup:{keep:'category'}},selection,'G',defaults);
result=editClassification(result,{kind:'projectGroup',row:{mappingType:'PROJECT_GROUP',customerCode:'001',businessGroup:'G',sourceKey:'001|G'}},'P',defaults);
assert.equal(result.projectGroupLookup['001|G'],'P');assert.equal(result.matchRules.length,1);assert.deepEqual(result.categoryLookup,{keep:'category'});
assert.throws(()=>editClassification(result,selection,' ',defaults));
assert.throws(()=>editClassification(result,{kind:'projectGroup',row:{customerCode:'001',businessGroup:'G',sourceKey:'002|G'}},'P',defaults));
});
test('interval overrides and conflicting rule identities cannot silently mask a classification edit',()=>{
const project={kind:'projectGroup',row:{mappingType:'PROJECT_GROUP',customerCode:'001',businessGroup:'G',sourceKey:'001|G'}};
assert.throws(()=>editClassification({effectiveRanges:[{mappingType:'PROJECT_GROUP',sourceKey:'001|G'}]},project,'P',[]),/期间规则/);
const id=classificationRuleId(source);
assert.throws(()=>editClassification({matchRules:[{id,stage:'bright',conditions:[]}]},selection,'G',[]),/冲突/);
});
test('editing a disabled project relationship enables only that relationship and rejects unavailable targets',()=>{
const selection={kind:'projectGroup',row:{mappingType:'PROJECT_GROUP',customerCode:'001',businessGroup:'G',sourceKey:'001|G'}};
const base={masterData:{projectGroups:[{code:'P',name:'项目组A',enabled:true}]},disabledMappings:{projectGroupLookup:['001|G','002|G']}};
const result=editClassification(base,selection,'项目组A',[]);
assert.deepEqual(result.disabledMappings.projectGroupLookup,['002|G']);
assert.deepEqual(base.disabledMappings.projectGroupLookup,['001|G','002|G']);
assert.throws(()=>editClassification(base,selection,'不存在的项目组',[]),/未登记/);
});
test('removable conditions apply to all matching rows without an implicit unclassified predicate',()=>{
const options={stage:'all',conditions:[{field:'@department',operator:'EQUALS',value:'产业部A'},{field:'销售片区',operator:'EQUALS',value:'销售区A'}]};
const result=editClassification({matchRules:[]},selection,'G',[],options);
assert.deepEqual(result.matchRules[0].conditions,options.conditions);assert.equal(result.matchRules[0].stage,'all');
assert.equal(result.matchRules[0].conditions.some(c=>c.field==='@group'),false);
assert.equal(classificationRuleId(source,options),classificationRuleId(source,{...options,conditions:[...options.conditions].reverse()}));
const specific=editClassification({matchRules:[]},selection,'G',[],{stage:'all'});
assert.ok(specific.matchRules[0].priority<result.matchRules[0].priority);
assert.throws(()=>editClassification({},selection,'G',[],{stage:'all',conditions:[]}),/至少一项/);
});
@@ -0,0 +1,48 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { configurationTables, importConfigurationTables, createConfigurationWorkbook, readConfigurationWorkbook } from '../src/configurationWorkbook.ts';
const rule={id:'rule_001',name:'指定分类',priority:-9900,stage:'all',enabled:true,target:'group',value:'G',conditions:[{field:'PDT代码',operator:'EQUALS',value:'00001'},{field:'销售片区',operator:'IS_BLANK',value:''}]};
const base={schemaVersion:3,unknown:{retain:[1,null]},masterData:{departments:[{code:'0001',name:'A',enabled:true}],groups:[{code:'002',name:'G',enabled:true,department:'A',unknown:'keep'}],products:[],projectGroups:[]},
categoryLookup:{'00001|欧洲':'G','00002|空':null},projectGroupLookup:{'00003|G':'P'},departmentLookup:{raw:'A'},productLookup:{RAW:'P'},disabledMappings:{categoryLookup:['00002|空']},matchRules:[rule],organizationHierarchy:[{code:'A',parentCode:'',name:'保留名称'}],effectiveRanges:[{mappingType:'CATEGORY',sourceKey:'00001|欧洲',fromMonth:'2026-01',toMonth:'2026-12',mappedValue:null}]};
test('all configuration sheets round-trip through a real xlsx with codes, nulls, conditions and omitted keys preserved',async()=>{
const source=structuredClone(base);const workbook=await createConfigurationWorkbook(source,'all');
const tables=await readConfigurationWorkbook(await workbook.xlsx.writeBuffer());
for(const mode of ['MERGE','REPLACE'])assert.deepEqual(importConfigurationTables(source,tables,'all',mode).definition,source);
assert.equal(tables.find(t=>t.name==='产业部名录').rows[0][0],'0001');
assert.deepEqual(source,base);assert.equal(workbook.getWorksheet('产业部名录').getCell('A2').numFmt,'@');
});
test('edits upsert by source key, and replace removes only records in supplied tables',()=>{
const tables=configurationTables(base,'categoryLookup');tables[0].rows[0][2]='新分组';
const imported=importConfigurationTables(base,tables,'categoryLookup','MERGE');
assert.equal(imported.definition.categoryLookup['00001|欧洲'],'新分组');assert.equal(imported.definition.categoryLookup['00002|空'],null);
assert.equal(imported.changes[0].updated,1);assert.equal(base.categoryLookup['00001|欧洲'],'G');
tables[0].rows=tables[0].rows.slice(0,1);const replaced=importConfigurationTables(base,tables,'all','REPLACE');
assert.equal(Object.keys(replaced.definition.categoryLookup).length,1);assert.deepEqual(replaced.definition.projectGroupLookup,base.projectGroupLookup);assert.equal(replaced.changes[0].removed,1);
});
test('multiple conditions are grouped by rule id; changing raw and computed fields cannot conflate them',async()=>{
const source={matchRules:[{...rule,conditions:[{field:'产业部',operator:'EQUALS',value:'原始A'},{field:'@department',operator:'EQUALS',value:'计算A'}]}]};
const book=await createConfigurationWorkbook(source,'matchRules');book.getWorksheet('条件匹配').getCell('F2').value='新分组';book.getWorksheet('条件匹配').getCell('F3').value='新分组';
const imported=importConfigurationTables(source,await readConfigurationWorkbook(await book.xlsx.writeBuffer()),'matchRules','MERGE').definition;
assert.deepEqual(imported.matchRules[0].conditions,source.matchRules[0].conditions);assert.equal(imported.matchRules[0].value,'新分组');
const rows=configurationTables(base,'matchRules');rows[0].rows[1][5]='不同分组';assert.throws(()=>importConfigurationTables(base,rows,'matchRules','MERGE'),/不一致/);
});
test('legacy defaults remain inherited on unchanged export/import; clearing the sheet explicitly disables them',async()=>{
const source={categoryLookup:{a:'G'}};const book=await createConfigurationWorkbook(source,'matchRules',[rule]);
const tables=await readConfigurationWorkbook(await book.xlsx.writeBuffer());assert.deepEqual(importConfigurationTables(source,tables,'matchRules','MERGE',[rule]).definition,source);
tables[0].rows=[];assert.deepEqual(importConfigurationTables(source,tables,'matchRules','REPLACE',[rule]).definition.matchRules,[]);
});
test('invalid headers, duplicate identities, hierarchy cycles and formulas are rejected before any change',async()=>{
let tables=configurationTables(base,'departments');tables[0].headers[0]='错误';assert.throws(()=>importConfigurationTables(base,tables,'departments','MERGE'),/表头/);
tables=configurationTables(base,'departments');tables[0].rows.push([...tables[0].rows[0]]);assert.throws(()=>importConfigurationTables(base,tables,'departments','MERGE'),/重复/);
tables=configurationTables(base,'all').filter(t=>t.name==='组织层级');tables[0].rows[0][1]='A';assert.throws(()=>importConfigurationTables(base,tables,'all','MERGE'),/循环/);
const book=await createConfigurationWorkbook(base,'departments');book.getWorksheet('产业部名录').getCell('A2').value={formula:'1+1',result:2};
await assert.rejects(async()=>readConfigurationWorkbook(await book.xlsx.writeBuffer()),/Excel公式/);
});
test('query fields and calculation definitions round-trip, preserve formulas as text, and accept edits',async()=>{
const rules={schemaVersion:'rule-v1',sourceFields:{black:{qualified:'合格重量'},bright:{qualified:'亮片重量'}},rowRules:[{stage:'black',target:'total',formula:'qualified+scrap',nullPolicy:'PROPAGATE',zeroDenominatorPolicy:'ONE'}],metricRules:{RATE:{formula:'qualified/total',zeroDenominatorPolicy:'ONE'}},unknown:'keep'};
const workbook=await createConfigurationWorkbook(rules,'rules');let tables=await readConfigurationWorkbook(await workbook.xlsx.writeBuffer());assert.deepEqual(importConfigurationTables(rules,tables,'rules','REPLACE').definition,rules);
tables.find(t=>t.name==='指标计算公式').rows[0][1]='qualified/(qualified+scrap)';const imported=importConfigurationTables(rules,tables,'rules','MERGE').definition;assert.equal(imported.metricRules.RATE.formula,'qualified/(qualified+scrap)');assert.equal(imported.metricRules.RATE.nullPolicy,undefined);
const fields={filterFields:[{key:'0001',label:'客户',blackColumn:'客户代码',brightColumn:'客户代码',enabled:false,allowEmpty:true,sortOrder:1}]};const book=await createConfigurationWorkbook(fields,'filterFields');tables=await readConfigurationWorkbook(await book.xlsx.writeBuffer());assert.deepEqual(importConfigurationTables(fields,tables,'filterFields','REPLACE').definition,fields);
});
+12 -5
View File
@@ -101,18 +101,18 @@ test('the actual summary click stores release A and filters until a new detail i
function drawerFixture() {
const source=read('QueryPage.tsx');const code=source.slice(source.indexOf('function RecordsDrawer(')).replace(/export \{ fullYearTrend \};/, '');
const requests=[],exports=[];let downloaded=0;
const requests=[],exports=[];let downloaded=0,refreshKey=0;
const props={open:true,row:null,stage:'black',onStage(){},onClose(){},query:freezeSourceRecordsQuery(baseQuery,'release-A','overall',null),onUnauthorized:()=>false};
const renderer=hookRenderer(hooks=>new Function('React','hooks','api',transpile(`
const {useState,useRef,useMemo,useEffect}=hooks;const TABLE_PAGE_SIZE=20,MONTHS=Array.from({length:12},(_,i)=>i+1+'月');
const {useState,useRef,useMemo,useEffect}=hooks;const usePageCache=()=>({refreshKey:api.refreshKey()});const TABLE_PAGE_SIZE=20,MONTHS=Array.from({length:12},(_,i)=>i+1+'月');
const Drawer='Drawer',Segmented='Segmented',Select='Select',Button='Button',Alert='Alert',Spin='Spin',Table='Table',Pagination='Pagination',SearchOutlined='SearchOutlined',DownloadOutlined='DownloadOutlined';
const Input='Input',readableSelectPopup={},Empty=Object.assign(()=>null,{PRESENTED_IMAGE_SIMPLE:'empty'}),App={useApp:()=>({message:{success(){},error(){}}})};
const isSystemVersionField=()=>false,chooseError=e=>e.message,withoutSystemVersionFields=v=>v;
const window={innerWidth:1400,setTimeout:fn=>fn()},document={createElement:()=>({click(){api.downloaded();},remove(){}}),body:{appendChild(){}}};
${code}
return RecordsDrawer;
`))(React,hooks,{records(params,signal){const d=deferred();requests.push({params,signal,...d});return d.promise;},async exportRecords(params,signal){exports.push({params,signal});return {blob:new Blob(['fixture']),filename:'fixture.xlsx'};},downloaded(){downloaded++;}}));
return {requests,exports,props,render:()=>renderer.render(props),unmount:()=>renderer.unmount(),get downloaded(){return downloaded;}};
`))(React,hooks,{refreshKey:()=>refreshKey,records(params,signal){const d=deferred();requests.push({params,signal,...d});return d.promise;},async exportRecords(params,signal){exports.push({params,signal});return {blob:new Blob(['fixture']),filename:'fixture.xlsx'};},downloaded(){downloaded++;}}));
return {requests,exports,props,render:()=>renderer.render(props),unmount:()=>renderer.unmount(),invalidate(){refreshKey++;},get downloaded(){return downloaded;}};
}
test('actual drawer clears prior rows during page load/failure and offers retry on the same frozen release',async()=>{
@@ -136,7 +136,14 @@ test('closing and reopening a different month remounts page/search state and ign
const next=drawerFixture();next.props.query=freezeSourceRecordsQuery({...baseQuery,month:2},'release-A','overall',null);next.render();
assert.equal(next.requests[0].params.page,1);assert.equal(next.requests[0].params.search,undefined);assert.equal(next.requests[0].params.month,2);
assert.equal(find(next.render(),n=>n.type==='Table'),undefined);next.unmount();
assert.match(read('QueryPage.tsx'),/recordsOpen && recordQuerySnapshot && <RecordsDrawer/);
assert.match(read('QueryPage.tsx'),/recordQuerySnapshot && <RecordsDrawer/);
assert.match(read('QueryPage.tsx'),/open=\{recordsOpen\}/);
});
test('reopening the same frozen drawer reuses its page until the workspace revision changes',async()=>{
const ui=drawerFixture();ui.render();ui.requests[0].resolve({rows:[{id:'cached'}],total:1,pageSize:20,page:1});await tick();ui.render();
ui.props.open=false;ui.render();ui.props.open=true;let tree=ui.render();assert.equal(ui.requests.length,1);assert.equal(find(tree,n=>n.type==='Table').props.dataSource[0].id,'cached');
ui.invalidate();tree=ui.render();assert.equal(ui.requests.length,2);assert.equal(find(tree,n=>n.type==='Table'),undefined);ui.unmount();
});
test('export from the actual drawer keeps the clicked release even after current publication changes',async()=>{
+13
View File
@@ -140,3 +140,16 @@ test('本部报废原口径紧随扩散废,调整口径隐藏并在表格及Ex
}
assert.equal(data.bright.scrapWeight,100);
});
test('合格率说明图标仅在去本部报废口径下显示,黑片总重说明始终保留', () => {
for(const basis of ['original','withoutHeadquartersScrap']) {
const ui=fixture({rows:[row],view:'overall',rateBasis:basis});
const columns=find(ui.tree,n=>n.type==='Table').props.columns;
const leaves=columns.flatMap(c=>c.children||[c]);
for(const key of ['bright-rate','compositeRate']) {
const header=leaves.find(c=>c.key===key).title;
assert.equal(Boolean(find(header,n=>n.type==='Info')),basis!=='original');
}
assert.ok(find(leaves.find(c=>c.key==='black-totalWeight').title,n=>n.type==='Info'));
}
});
@@ -23,3 +23,10 @@ test('product rows sort by selected stage total descending without mutating rows
assert.deepEqual(sortStageRowsByTotalWeight(rows,'bright').map(row=>row.key),['small','tie','large','unknown','negative']);
assert.deepEqual(rows.map(row=>row.key),['unknown','small','large','tie','negative']);
});
test('stage query includes unclassified source rows even when an old link excluded them',()=>{
for(const stage of ['black','bright']) {
const base={year:2026,includeUnassigned:false};
assert.equal(stageProductQuery(base,stage,[]).includeUnassigned,true);
assert.equal(base.includeUnassigned,false);
}
});