perf: optimize full interface loading and refresh paths
This commit is contained in:
1 parent
649a0df832
commit
f317314a3c
57 files changed
+791
-136
No files matched your search
@@ -102,7 +102,7 @@ function dispatchFixture(t,{ready=true,capabilities=true,enabled=true,verify,sen
|
||||
const record={prepared:0,begun:0,smtp:0,locked:0,status:'prepared',messages:[],sent:[]};
|
||||
const config={version:1,enabled,channelId:'channel1'};
|
||||
const caps={liveTodo:capabilities,pdfExport:capabilities,automaticArchive:capabilities};
|
||||
const store={discoveryBlockers:()=>[],batchIncomplete:()=>false,settings:()=>({...config}),snapshot:()=>({capabilities:{...caps},batches:[structuredClone({...batch,status:record.status})]}),prepare:(date,actor,window)=>{record.prepared++;assert.equal(date,dispatchCutoff);assert.equal(actor,'系统调度');assert.equal(window.start,'2026-10-19T09:00:00.000Z');assert.equal(window.end,dispatchCutoff);assert.equal(window.startInclusive,true);assert.equal(window.endInclusive,false);return [batch];},beginSending:id=>{assert.equal(id,'batch1');record.begun++;record.status='sending';},finishSending:(id,status,message)=>{assert.equal(id,'batch1');record.status=status;record.messages.push(message);}};
|
||||
const store={discoveryBlockers:()=>[],batchIncomplete:()=>false,settings:()=>({...config}),capabilities:caps,all:kind=>kind==='batches'?[structuredClone({...batch,status:record.status})]:[],prepare:(date,actor,window)=>{record.prepared++;assert.equal(date,dispatchCutoff);assert.equal(actor,'系统调度');assert.equal(window.start,'2026-10-19T09:00:00.000Z');assert.equal(window.end,dispatchCutoff);assert.equal(window.startInclusive,true);assert.equal(window.endInclusive,false);return [batch];},beginSending:id=>{assert.equal(id,'batch1');record.begun++;record.status='sending';},finishSending:(id,status,message)=>{assert.equal(id,'batch1');record.status=status;record.messages.push(message);}};
|
||||
const mail={exclusive:async(id,fn)=>{assert.equal(id,'channel1');record.locked++;return fn();},store:{channelSecret:id=>({id,version:2,email:'sender@example.com',name:'通知',smtp:{host:'unused.invalid'}}),guard:(id,version)=>{assert.equal(id,'channel1');assert.equal(version,2);}},smtpFactory:()=>{record.smtp++;return {verify:async()=>{if(verify)await verify({batch,config,caps,file});},sendMail:async message=>{record.sent.push(message);if(send)return send(message);return result||{accepted:['2639266652@qq.com'],rejected:[]};},close:()=>{}};}};
|
||||
const schedule={times:['09:00','17:00'],timezone:'Asia/Shanghai',weekends:false,mode:'product_line',missed:'next_window'};
|
||||
let now=new Date('2026-10-20T00:59:00.000Z');
|
||||
|
||||
@@ -88,6 +88,19 @@ test('status reads only effective settings and in-memory capabilities',async t=>
|
||||
assert.deepEqual(await response.json(),{settings:{enabled:false},capabilities:{liveTodo:true,pdfExport:false,automaticArchive:false}});
|
||||
});
|
||||
|
||||
test('catalog and notification settings avoid history and unrelated configuration resources',async t=>{
|
||||
const rules=memoryRules(t);poisonHistory(rules);
|
||||
for(const kind of ['field-adapters','scope-catalog','scope-process-catalog'])rules.db.prepare('INSERT OR REPLACE INTO records VALUES(?,?,?)').run(kind,'corrupt',Buffer.from('not encrypted'));
|
||||
const f=await dashboard(t,{rules});
|
||||
const catalogResponse=await f.request('/api/order-rules/catalog');assert.equal(catalogResponse.status,200);
|
||||
const catalog=await catalogResponse.json();assert.equal(catalog.rules.length,15);assert.equal(catalog.templateUsage.length,15);
|
||||
assert.deepEqual(Object.keys(catalog.rules[0]).sort(),['categoryId','name']);assert.equal(catalog.templateUsage[0].status,'draft');
|
||||
assert.doesNotMatch(JSON.stringify(catalog),/"orders":|"fields":|"adapters":|"draft":/);
|
||||
const settingsResponse=await f.request('/api/order-rules/notification-settings');assert.equal(settingsResponse.status,200);
|
||||
assert.deepEqual(await settingsResponse.json(),{settings:rules.settings(),restrictedTest:null});
|
||||
for(const route of ['/api/order-rules/catalog','/api/order-rules/notification-settings'])assert.equal((await f.request(route,{role:'anonymous'})).status,401);
|
||||
});
|
||||
|
||||
test('rule write receipts retain complete editor versions without historic reads or relaxing stale-version validation',async t=>{
|
||||
const rules=memoryRules(t),{captured}=activateReferenceMapping(rules,'bs-change',{connectionId:'own',instanceId:'i',taskId:'t',revision:'1'});
|
||||
const draft=rules.saveRule({...rules.get('rules','bs-change').draft,to:['admin@example.test'],attachPdf:false,archiveDirectory:'\\\\server\\orders',filenameDate:'appDate'},'admin');rules.capturedPreview(captured.id);
|
||||
|
||||
@@ -6,7 +6,7 @@ const at='2026-10-27T03:30:00.000Z';
|
||||
function fixture({verifyError,sendError,result,channelId='mail',expired=false}={}){
|
||||
const batch={id:'batch',status:'prepared',cutoff:expired?'2026-10-27T02:00:00.000Z':at,channelId,to:['2639266652@qq.com'],cc:[],attachments:[],orderIds:['order'],ruleSnapshot:{}};
|
||||
const completions=[];let submissions=0,begun=0;
|
||||
const store={get:()=>null,now:()=>at,settings:()=>({enabled:true,channelId:'mail'}),snapshot:()=>({batches:[batch],capabilities:{liveTodo:true,pdfExport:true,automaticArchive:true}}),discoveryBlockers:()=>[],batchIncomplete:()=>false,beginSending:()=>{begun++;},finishSending:(...args)=>completions.push(args)};
|
||||
const store={get:()=>null,now:()=>at,settings:()=>({enabled:true,channelId:'mail'}),all:kind=>kind==='batches'?[structuredClone(batch)]:[],capabilities:{liveTodo:true,pdfExport:true,automaticArchive:true},discoveryBlockers:()=>[],batchIncomplete:()=>false,beginSending:()=>{begun++;},finishSending:(...args)=>completions.push(args)};
|
||||
const mail={store:{channelSecret:()=>({id:'mail',version:1,email:'sender@example.com',smtp:{}}),guard:()=>{}},smtpFactory:()=>({verify:async()=>{if(verifyError)throw verifyError;},sendMail:async()=>{submissions++;if(sendError)throw sendError;return result||{accepted:['2639266652@qq.com'],rejected:[]};},close:()=>{}})};
|
||||
const dispatcher=new OrderRuleDispatcher({store,mail,settings:()=>({}),clock:()=>new Date(at),providersReady:()=>true});
|
||||
return {dispatcher,batch,store,completions,counts:()=>({submissions,begun})};
|
||||
|
||||
@@ -19,7 +19,7 @@ test('authorized users can explicitly revalidate only the original departed task
|
||||
});
|
||||
test('test settings and rule editor name uncovered flows even when all categories are ready',{timeout:90000},async t=>{
|
||||
const {page}=await orderDrivenUI(t,'#notification-orders'),name='零售国内返工订单更改评审<待适配>';
|
||||
await page.route('**/api/order-rules?view=summary',async route=>{const response=await route.fetch(),data=await response.json();data.restrictedTest={id:'coverage-test',version:1,enabled:true,ruleCount:15,readyCount:15,recipient:'2639266652@qq.com',archiveRoot:'C:\\isolated',since:'2026-10-26T00:00:00Z',uncovered:[{categoryId:'domestic-change',processName:name}]};await route.fulfill({json:data});});
|
||||
await page.route(/\/api\/order-rules\/(notification-settings|configuration)$/,async route=>{const response=await route.fetch(),data=await response.json();data.restrictedTest={id:'coverage-test',version:1,enabled:true,ruleCount:15,readyCount:15,recipient:'2639266652@qq.com',archiveRoot:'C:\\isolated',since:'2026-10-26T00:00:00Z',uncovered:[{categoryId:'domestic-change',processName:name}]};await route.fulfill({json:data});});
|
||||
for(const hash of ['notification-settings','order-rules']){await page.goto(new URL('/#'+hash,page.url()).href);await page.getByText(name,{exact:true}).waitFor();assert.equal(await page.locator('待适配').count(),0);assert.match(await page.locator('#content').innerText(),/domestic-change/);}
|
||||
});
|
||||
test('failure modal shows field sources and actionable diagnosis without offering an unsafe immediate retry',{timeout:90000},async t=>{
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
'use strict';
|
||||
const test=require('node:test'),assert=require('node:assert/strict');
|
||||
const {fixture}=require('../fixtures/query-performance.cjs');
|
||||
const query=require('../../src/modules/order-rules/query.cjs');
|
||||
for(const operation of ['queryOrders','queryBatches','summary'])test(operation+' decrypts each task set once per read, including window checks',t=>{
|
||||
const f=fixture(40);t.after(()=>f.close());
|
||||
const result=operation==='summary'?query.summary(f.context,f.actor):query[operation](f.context,{},f.actor);
|
||||
if(operation==='queryOrders'){assert.equal(result.total,40);assert.equal(result.items.length,25);}
|
||||
if(operation==='queryBatches'){assert.equal(result.total,1);assert.equal(result.items[0].orderCount,40);}
|
||||
if(operation==='summary'){assert.equal(result.counts.orders,40);assert.equal(result.home.pendingOrders,40);}
|
||||
assert.ok((f.counts.all['execution-tasks']||0)<=1,JSON.stringify(f.counts));
|
||||
assert.ok((f.counts.all.orders||0)<=1,JSON.stringify(f.counts));
|
||||
assert.ok(f.counts.decode<200,JSON.stringify(f.counts));
|
||||
});
|
||||
test('completed modes perform no intake eligibility reads',t=>{
|
||||
const f=fixture(40,{status:'sent'});t.after(()=>f.close());
|
||||
const groups=require('../../src/modules/order-rules/collecting-batches.cjs').list(f.store);assert.deepEqual(groups,[]);
|
||||
assert.equal(f.counts.all['execution-tasks']||0,0);
|
||||
});
|
||||
test('a frozen normal category excludes eligibility while a pending Hui mode remains independent',t=>{
|
||||
const f=fixture(1,{status:'sent',huizhou:true});t.after(()=>f.close());
|
||||
f.store.put('batches',{id:'frozen',categoryId:'bs-change',status:'unknown',cutoff:'2026-10-26T03:00:00.000Z',orderIds:['o0']});
|
||||
const collecting=require('../../src/modules/order-rules/collecting-batches.cjs');
|
||||
assert.deepEqual(collecting.list(f.store).map(b=>[b.notificationMode,b.orderIds]),[['huizhou',['o0']]]);
|
||||
const order=f.store.get('orders','o0');order.status='pending';order.notifications.huizhou.status='unknown';f.store.put('orders',order);f.reset();
|
||||
assert.deepEqual(collecting.list(f.store),[]);assert.equal(f.counts.all['execution-tasks']||0,0);
|
||||
});
|
||||
test('queries see writes even when the connection-local change counter is unchanged',t=>{
|
||||
const f=fixture(1);t.after(()=>f.close());f.store.queryRevision=()=>1;
|
||||
assert.equal(query.queryOrders(f.context,{},f.actor).items[0].status,'pending');
|
||||
const order=f.store.get('orders','o0');order.status='sent';f.store.put('orders',order);
|
||||
assert.equal(query.queryOrders(f.context,{},f.actor).items[0].status,'sent');
|
||||
});
|
||||
test('a later read rechecks window time and returned objects cannot change durable notices',t=>{
|
||||
const f=fixture(1,{huizhou:true});t.after(()=>f.close());
|
||||
const first=query.queryOrders(f.context,{},f.actor);assert.equal(first.items[0].collectingBatches.length,2);
|
||||
first.items[0].notifications.huizhou.status='sent';
|
||||
assert.equal(f.store.get('orders','o0').notifications.huizhou.status,'pending');
|
||||
f.setNow('2026-10-26T04:00:00Z');assert.deepEqual(query.queryOrders(f.context,{},f.actor).items[0].collectingBatches,[]);
|
||||
});
|
||||
test('identity candidates scale with matching tasks while legacy portal overlap remains ambiguous',()=>{
|
||||
const identity=require('../../src/modules/order-rules/task-identity.cjs'),{readStore}=require('../../src/modules/order-rules/read-context.cjs');let visits=0;
|
||||
const tasks=Array.from({length:100},(_,i)=>({id:'t'+i,row:{get source(){visits++;return 'todo';},taskId:String(i),portalSource:'v4'}}));
|
||||
const store=readStore({all:()=>tasks,get:()=>null});
|
||||
for(let i=0;i<100;i++)assert.equal(identity.lookup(store,'execution-tasks',{source:'todo',taskId:String(i),portalSource:'v4'}).id,'t'+i);
|
||||
assert.ok(visits<=400,'identity lookup revisited '+visits+' task sources');
|
||||
const legacy=readStore({all:()=>[{id:'native',row:{source:'todo',taskId:'1',portalSource:'v4'}},{id:'legacy',row:{source:'todo',taskId:'1'}}],get:()=>null});
|
||||
assert.throws(()=>identity.lookup(legacy,'execution-tasks',{source:'todo',taskId:'1',portalSource:'v4'}),e=>e.status===409);
|
||||
assert.deepEqual(identity.records(legacy,'execution-tasks',{source:'todo',taskId:'1',portalSource:'v8'}).map(row=>row.id),['legacy']);
|
||||
});
|
||||
for(const status of ['sent','unknown','ignored','failed'])test('intake expiry skips inactive '+status+' history without scanning task eligibility',t=>{
|
||||
const f=fixture(40,{status});t.after(()=>f.close());const before=f.store.queryRevision();
|
||||
f.store.expireIntakes();
|
||||
assert.equal(f.store.queryRevision(),before,'history must remain untouched');
|
||||
assert.equal(f.counts.all['execution-tasks']||0,0,JSON.stringify(f.counts));
|
||||
assert.equal(f.counts.get.batches||0,0,JSON.stringify(f.counts));
|
||||
});
|
||||
|
||||
for(const huizhou of [false,true])test('active carry advancement skips eligibility for 300 archived sent orders '+(huizhou?'with disabled Hui records':'without a Hui notice'),t=>{
|
||||
const f=fixture(300,{status:'sent',huizhou});t.after(()=>f.close());
|
||||
const settings=f.store.get('settings','main');f.store.put('settings',{...settings,enabled:true,processingEnabled:true});
|
||||
for(const order of f.store.all('orders'))f.store.put('orders',{...order,ruleSnapshot:{...order.ruleSnapshot,huizhouEnabled:false},archive:{archivedAt:'2026-10-26T00:45:00Z',files:[{name:'notice.pdf',path:'C:\\fixture\\notice.pdf',sha256:'a'.repeat(64),size:128,kind:'pdf'}]}});
|
||||
const revision=f.store.queryRevision();f.reset();
|
||||
assert.deepEqual(require('../../src/modules/order-rules/carry-forward.cjs').advance(f.store),{moved:[]});
|
||||
assert.equal(f.counts.all['execution-tasks']||0,0,JSON.stringify(f.counts));
|
||||
assert.equal(f.counts.get['capture-samples']||0,0,JSON.stringify(f.counts));
|
||||
assert.equal(f.store.queryRevision(),revision,'completed and disabled modes must stay untouched');
|
||||
});
|
||||
@@ -4,9 +4,9 @@ const {orderDrivenUI}=require('../fixtures/order-driven-ui.cjs');
|
||||
test('healthy todo without matched orders shows pending verification without loosening capability gates',{timeout:60000},async t=>{
|
||||
const {page,runtime}=await orderDrivenUI(t,'#notification-settings'),s=runtime.orderRules;
|
||||
s.put('settings',{...s.get('settings','main'),enabled:true,processingEnabled:true});s.capabilities={liveTodo:true,pdfExport:false,automaticArchive:false};
|
||||
await page.getByRole('button',{name:'刷新数据',exact:true}).click();await page.getByRole('link',{name:'自动通知待验证',exact:true}).waitFor();
|
||||
await page.getByRole('button',{name:'刷新数据',exact:true}).click();await page.getByRole('link',{name:'自动通知待核验',exact:true}).waitFor();
|
||||
assert.equal(s.providersReady(),false);assert.equal(s.settings().enabled,true);
|
||||
s.put('execution-scans',{id:'failed-source',status:'failed',error:'fixture failure'});
|
||||
await page.getByRole('button',{name:'刷新数据',exact:true}).click();await page.getByRole('link',{name:'自动通知受阻',exact:true}).waitFor();
|
||||
await page.getByRole('button',{name:'刷新数据',exact:true}).click();await page.getByRole('link',{name:'自动通知待核验',exact:true}).waitFor();
|
||||
assert.equal(s.providersReady(),false);
|
||||
});
|
||||
@@ -3,11 +3,11 @@ const test=require('node:test'),assert=require('node:assert/strict'),fs=require(
|
||||
const {loadPlaywright,browserOptions}=require('../../src/platform/browser.cjs');
|
||||
async function setup(t,section,owner='OrderNotificationViews',mailFailure=false){
|
||||
const browser=await loadPlaywright().chromium.launch(browserOptions());t.after(()=>browser.close());const page=await browser.newPage();page.setDefaultTimeout(5000);await page.setContent('<main id="root"></main>');
|
||||
for(const file of ['order-notifications/shared.js','order-rules/view.js','order-notifications/view.js'])await page.addScriptTag({content:await fs.readFile(path.resolve('web/modules',file),'utf8')});
|
||||
await page.evaluate(async({section,owner,mailFailure})=>{window.calls=[];window.active=true;window.PageLifecycle={requestKey:()=> 'key',dirty:()=>false,onDispose:()=>{},afterSave:async reload=>reload(),guard:fn=>fn()};window.BusinessRecordViews={render:async(host,options,kind)=>{host.textContent='授权分页 '+kind;}};window.OrderExecutionViews={fields:async panel=>{panel.textContent='字段映射';}};const snapshot={rules:[],adapters:[],settings:{enabled:false,processingEnabled:false,version:1},counts:{orders:3,blocked:1,unknown:1,activeBatches:2},capabilities:{},window:{available:true,start:'2026-10-19T00:00:00Z',end:'2026-10-19T11:00:00Z'}};window[owner].configure(window.viewHelpers={api:async(url,body)=>{window.calls.push(url);if(body)return new Promise(r=>window.releaseAction=()=>r({version:2}));if(url==='/mail'&&mailFailure)throw Error('SMTP目录暂不可读');return url==='/mail'?{channels:[]}:snapshot;},esc:value=>String(value??'').replaceAll('&','&').replaceAll('<','<'),formatDate:v=>v||'—',user:{role:'admin'}});await window[owner].render(document.querySelector('#root'),()=>window.active,section);},{section,owner,mailFailure});return page;
|
||||
for(const file of ['navigation/lifecycle.js','order-notifications/home.js','order-notifications/shared.js','order-rules/view.js','order-notifications/view.js'])await page.addScriptTag({content:await fs.readFile(path.resolve('web/modules',file),'utf8')});
|
||||
await page.evaluate(async({section,owner,mailFailure})=>{window.calls=[];window.active=true;window.BusinessRecordViews={render:async(host,options,kind)=>{host.textContent='授权分页 '+kind;}};window.OrderExecutionViews={fields:async panel=>{panel.textContent='字段映射';}};const snapshot={rules:[],adapters:[],settings:{enabled:false,processingEnabled:false,version:1},counts:{orders:3,blocked:1,unknown:1,activeBatches:2},capabilities:{},window:{available:true,start:'2026-10-19T00:00:00Z',end:'2026-10-19T11:00:00Z'}};window[owner].configure(window.viewHelpers={api:async(url,body)=>{window.calls.push(url);if(body)return new Promise(r=>window.releaseAction=()=>r({version:2}));if(url==='/mail'&&mailFailure)throw Error('SMTP目录暂不可读');return url==='/mail'?{channels:[]}:snapshot;},esc:value=>String(value??'').replaceAll('&','&').replaceAll('<','<'),formatDate:v=>v||'—',user:{role:'admin'}});await window[owner].render(document.querySelector('#root'),()=>window.active,section);},{section,owner,mailFailure});return page;
|
||||
}
|
||||
test('order and batch sections delegate to bounded query views without loading full snapshots',async t=>{const page=await setup(t,'orders');assert.equal(await page.locator('main').innerText(),'授权分页 orders');assert.deepEqual(await page.evaluate(()=>calls),[]);await page.evaluate(()=>OrderNotificationViews.render(document.querySelector('#root'),()=>active,'pending'));assert.equal(await page.locator('main').innerText(),'授权分页 batches');assert.deepEqual(await page.evaluate(()=>calls),[]);});
|
||||
test('fields delegate their lifecycle without notification runtime reads',async t=>{const page=await setup(t,'fields','OrderRuleViews');await page.getByText('字段映射',{exact:true}).waitFor();assert.deepEqual(await page.evaluate(()=>calls),[]);});
|
||||
test('business homepage uses bounded summary and concrete remediation links',async t=>{const page=await setup(t,'workbench');assert.match(await page.locator('main').innerText(),/2026-10-19T11:00:00Z/);for(const hash of ['#rule-fields','#bpm','#storage','#notification-orders'])assert.ok(await page.locator('a[href="'+hash+'"]').count());assert.deepEqual(await page.evaluate(()=>calls),['/order-rules?view=summary']);});
|
||||
test('mailbox failure is explicit and cannot save an empty catalog',async t=>{const page=await setup(t,'settings','OrderNotificationViews',true);assert.match(await page.locator('main').innerText(),/邮箱目录读取失败/);await page.getByRole('button',{name:'保存设置'}).click();assert.deepEqual(await page.evaluate(()=>calls),['/order-rules?view=summary','/mail']);});
|
||||
test('late settings action after departure starts no readback or saved feedback',async t=>{const page=await setup(t,'settings');await page.getByRole('button',{name:'保存设置'}).click();await page.waitForFunction(()=>typeof releaseAction==='function');await page.evaluate(()=>{active=false;releaseAction();});await page.waitForFunction(()=>!document.querySelector('#order-rule-settings button').disabled);assert.deepEqual(await page.evaluate(()=>calls),['/order-rules?view=summary','/mail','/order-rules/settings']);assert.equal(await page.locator('form [role=alert]').innerText(),'');});
|
||||
test('business homepage uses bounded summary and concrete remediation links',async t=>{const page=await setup(t,'workbench');assert.equal(await page.locator('[data-home-next-send]').innerText(),'19:00');for(const hash of ['#rule-fields','#bpm','#storage','#notification-orders'])assert.ok(await page.locator('a[href="'+hash+'"]').count());assert.deepEqual(await page.evaluate(()=>calls),['/order-rules?view=summary']);});
|
||||
test('mailbox failure is explicit and cannot save an empty catalog',async t=>{const page=await setup(t,'settings','OrderNotificationViews',true);assert.match(await page.locator('main').innerText(),/邮箱目录读取失败/);await page.getByRole('button',{name:'保存设置'}).click();assert.deepEqual(await page.evaluate(()=>calls),['/order-rules/notification-settings','/mail']);});
|
||||
test('late settings action after departure starts no readback or saved feedback',async t=>{const page=await setup(t,'settings');await page.getByRole('button',{name:'保存设置'}).click();await page.waitForFunction(()=>typeof releaseAction==='function');await page.evaluate(()=>{active=false;releaseAction();});await page.waitForFunction(()=>!document.querySelector('#order-rule-settings button').disabled);assert.deepEqual(await page.evaluate(()=>calls),['/order-rules/notification-settings','/mail','/order-rules/settings']);assert.equal(await page.locator('form [role=alert]').innerText(),'');});
|
||||
Reference in new issue
Block a user