'use strict'; const test=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs'),os=require('node:os'),path=require('node:path'); const {RuleStore}=require('../../src/modules/order-rules/store.cjs'); const {OrderExecutionCoordinator}=require('../../src/modules/order-execution/coordinator.cjs'); const {OrderRuleDispatcher}=require('../../src/modules/order-rules/dispatcher.cjs'); const {activateReferenceMapping}=require('../fixtures/activate-field-mapping.cjs'); const cutoff='2026-10-26T03:00:00.000Z',principal={sessionId:'fixture',user:{username:'admin',role:'admin'}}; function fixture(t,{captureMs=0,archiveMs=0,startMs=0}={}){ const dir=fs.mkdtempSync(path.join(os.tmpdir(),'slow-cutoff-'));let now=new Date(Date.parse(cutoff)+startMs),archives=0,captures=0; const store=new RuleStore(dir,{clock:()=>now});t.after(()=>{store.close();fs.rmSync(dir,{recursive:true,force:true});}); const base=activateReferenceMapping(store).sample,old=store.get('rules','bs-change').draft; const rule=store.saveRule({...old,archiveDirectory:'\\\\fixture\\orders',to:['2639266652@qq.com'],cc:[],filenameDate:'receivedAt',bodyTemplateId:''},'fixture');store.put('rules',{...store.get('rules',rule.id),published:{...rule,status:'enabled'}}); const row={...base,connectionId:'c1',taskId:'slow',instanceId:'instance',receivedAt:'2026-10-26T02:00:00Z'}; const connection={id:'c1',owner:'admin',status:'connected'},workspace={snapshot:()=>({connections:[connection]}),getConnection:()=>connection}; const provider={scan:async()=>[row],capabilities:async()=>({liveTodo:true,pdfExport:true}),capture:async()=>{captures++;now=new Date(+now+captureMs);return {sample:row,snapshot:{processVersion:row.processVersion,fields:[]}};}}; const archive={supportsRecovery:true,capabilities:async()=>({automaticArchive:true,pdfExport:true}),archive:async()=>{archives++;now=new Date(+now+archiveMs);return {archivedAt:now.toISOString(),files:[{name:'x.pdf',path:'C:\\fixture\\x.pdf',sha256:'a'.repeat(64),size:1,kind:'pdf'}]};}}; const execution=new OrderExecutionCoordinator({store,workspace,provider,archive,clock:()=>now,onException:async()=>{}}); return {dir,store,row,provider,archive,workspace,execution,clock:()=>now,setNow:value=>{now=new Date(value);},counts:()=>({captures,archives})}; } for(const delays of [{captureMs:61001},{archiveMs:61001},{captureMs:30000,archiveMs:31001}])test(`original intake survives asynchronous cutoff crossing ${JSON.stringify(delays)}`,async t=>{ const f=fixture(t,delays);await f.execution.scan({connectionId:'c1',idempotencyKey:'scan'},principal); assert.equal(f.store.all('orders')[0].status,'pending');assert.equal(f.store.all('execution-tasks')[0].step,'complete');assert.equal(f.counts().archives,1); assert.equal(f.store.prepare(cutoff,'fixture').length,1); }); test('restart resumes original intake and dispatcher freezes within delivery grace',async t=>{ const f=fixture(t);f.provider.capture=async()=>{throw Error('transient');};await f.execution.scan({connectionId:'c1',idempotencyKey:'failed'},principal); f.setNow(Date.parse(cutoff)+61001);f.provider.capture=async()=>({sample:f.row,snapshot:{processVersion:f.row.processVersion,fields:[]}}); const store=new RuleStore(f.dir,{clock:f.clock});try{ const resumed=new OrderExecutionCoordinator({...f.execution,store});await resumed.scan({connectionId:'c1',idempotencyKey:'restart'},principal); assert.equal(store.all('orders')[0]?.status,'pending'); let sends=0;store.put('settings',{...store.get('settings','main'),enabled:true,channelId:'mail'}); const dispatcher=new OrderRuleDispatcher({store,clock:f.clock,settings:()=>({schedule:store.schedule()}),providersReady:()=>true,mail:{exclusive:async(_,fn)=>fn()}}); dispatcher.dispatch=async batch=>{sends++;assert.equal(batch.cutoff,cutoff);};await dispatcher.tick();assert.equal(sends,1); }finally{store.close();} }); test('newly observed old arrival after intake allowance cannot join original window',async t=>{ const f=fixture(t,{startMs:61001});await f.execution.scan({connectionId:'c1',idempotencyKey:'late'},principal);assert.equal(f.counts().archives,0);assert.equal(f.store.prepare(cutoff,'fixture').length,0); }); for(const startMs of [60000,60001])test(`intake start allowance boundary ${startMs}ms`,async t=>{ const f=fixture(t,{startMs,captureMs:1});await f.execution.scan({connectionId:'c1',idempotencyKey:'edge'},principal);assert.equal(f.counts().archives,startMs===60000?1:0); }); for(const captureMs of [1800000,1800001])test(`original intake completion grace boundary ${captureMs}ms`,async t=>{ const f=fixture(t,{captureMs});await f.execution.scan({connectionId:'c1',idempotencyKey:'grace'},principal); const order=f.store.all('orders')[0];assert.equal(order.status,captureMs===1800000?'pending':'blocked');assert.equal(f.counts().archives,captureMs===1800000?1:0); }); test('five minute arrival boundary still defers capture to the following window',async t=>{ const f=fixture(t);f.row.receivedAt='2026-10-26T02:55:00.000Z';await f.execution.scan({connectionId:'c1',idempotencyKey:'arrival'},principal);assert.equal(f.counts().captures,0);assert.equal(f.store.all('execution-tasks')[0].step,'waiting_window'); }); test('original frozen category remains immutable when a slow task finishes',async t=>{ const f=fixture(t,{captureMs:61001});const frozen={id:'frozen',categoryId:'bs-change',cutoff,window:require('../../src/modules/order-rules/window.cjs').windowForCutoff(cutoff,f.store.schedule()),status:'sent',orderIds:[],text:'original'};f.store.put('batches',frozen); await f.execution.scan({connectionId:'c1',idempotencyKey:'frozen'},principal);assert.equal(f.store.all('orders')[0].status,'blocked');assert.equal(f.counts().archives,0);assert.deepEqual(f.store.get('batches','frozen'),frozen); }); test('unknown archive outcome cannot be replayed by intake grace after restart',async t=>{ const f=fixture(t);f.archive.supportsRecovery=false;f.archive.archive=async()=>{throw Error('outcome uncertain');};await f.execution.scan({connectionId:'c1',idempotencyKey:'unknown'},principal); f.setNow(Date.parse(cutoff)+61001);const resumed=new OrderExecutionCoordinator({...f.execution});await resumed.scan({connectionId:'c1',idempotencyKey:'again'},principal); assert.equal(f.store.all('execution-tasks')[0].status,'unknown');assert.equal(f.store.prepare(cutoff,'fixture').length,0); }); test('capture enrichment preserves original intake identity through grace',async t=>{ const f=fixture(t,{captureMs:61001}),capture=f.provider.capture;f.provider.capture=async()=>{const result=await capture();result.sample.extraCaptureEvidence='detail';return result;}; await f.execution.scan({connectionId:'c1',idempotencyKey:'enriched'},principal);assert.equal(f.store.all('orders')[0].status,'pending'); }); test('expired original intake remains blocked for review instead of becoming ignored history',async t=>{ const f=fixture(t);await f.execution.scan({connectionId:'c1',idempotencyKey:'finished'},principal);f.setNow('2026-10-26T09:00:00Z'); f.store.prepare('2026-10-26T09:00:00Z','fixture');assert.equal(f.store.all('orders')[0].status,'blocked');assert.match(f.store.all('orders')[0].error,/30分钟/); }); test('explicit backlog admission retains its accepted time only for the persisted original window',async t=>{ const f=fixture(t);await f.execution.scan({connectionId:'c1',idempotencyKey:'accepted'},principal); const row=f.store.all('orders')[0].sample,keys=['source','portalSource','taskId','instanceId','revision','processName','nodeName','processVersion','receivedAt'],snapshot=Object.fromEntries(keys.filter(k=>Object.hasOwn(row,k)).map(k=>[k,row[k]])),snapshotHash=require('node:crypto').createHash('sha256').update(JSON.stringify(Object.fromEntries(Object.keys(snapshot).sort().map(k=>[k,snapshot[k]])))).digest('hex'); f.store.put('restricted-test',{id:'main',value:{id:'run',rules:[],enabled:true,currentBacklog:[{snapshot,snapshotHash,testRunId:'run',admittedAt:'2026-10-26T02:00:00Z'}]}});f.setNow(Date.parse(cutoff)+61001); const restricted=require('../../src/modules/order-rules/restricted-test.cjs'),window=require('../../src/modules/order-rules/window.cjs').windowForCutoff(cutoff,f.store.schedule()); assert.equal(restricted.orderInWindow(f.store,f.store.all('orders')[0],window),true); f.setNow(Date.parse(cutoff)+1800001);assert.equal(restricted.orderInWindow(f.store,f.store.all('orders')[0],window),false); }); test('slow source discovery preserves the window at scan start before its first asynchronous read',async t=>{ const f=fixture(t);f.provider.scan=async()=>{f.setNow(Date.parse(cutoff)+61001);return [f.row];}; await f.execution.scan({connectionId:'c1',idempotencyKey:'slow-discovery'},principal);assert.equal(f.store.all('orders')[0].status,'pending');assert.equal(f.store.prepare(cutoff,'fixture').length,1); }); async function companionFixture(t,outcome){ const f=fixture(t);await f.execution.scan({connectionId:'c1',idempotencyKey:'dual'},principal); const order=f.store.all('orders')[0],record=f.store.get('rules','bs-change'),rule={...order.ruleSnapshot,huizhouEnabled:true,huizhouTemplateId:'hui'}; f.store.put('rules',{...record,published:rule});order.ruleSnapshot=rule;order.event.titleOrders=[{orderNo:'H-200',businessMode:'惠州数字',customer:'客户',text:'订单号:H-200业务模式:惠州数字客户简称:客户'}];order.notifications.huizhou={status:'pending',batchId:null,error:null,orderNos:['H-200'],issues:[]};f.store.put('orders',order); f.store.templateResolver=(_,__,mode)=>{if(mode==='huizhou')throw Error('missing Hui template');return null;}; const batches=f.store.prepare(cutoff,'fixture');assert.equal(batches.length,1);const normal=batches[0];assert.equal(normal.huizhouPlanned,true); f.store.beginSending(normal.id);f.store.finishSending(normal.id,outcome,'fixture');const task=f.store.all('execution-tasks')[0];f.store.put('execution-tasks',{...task,status:outcome,step:'complete'}); f.store.put('settings',{...f.store.get('settings','main'),enabled:true,channelId:'mail'}); const dispatcher=new OrderRuleDispatcher({store:f.store,clock:f.clock,settings:()=>({schedule:f.store.schedule()}),providersReady:()=>true,mail:{exclusive:async(_,fn)=>fn()}});dispatcher.dispatch=async()=>true; f.store.templateResolver=(_,__,mode)=>mode==='huizhou'?{id:'hui',version:1,status:'active',notificationMode:'huizhou',subject:'惠州 {{订单号}}',text:'{{订单明细}}',html:'
{{订单明细}}
'}:null; return {...f,normal:f.store.get('batches',normal.id),orderId:order.id,dispatcher}; } for(const outcome of ['sent','unknown'])test(`original Hui companion repairs after normal ${outcome} without changing its frozen receipt`,async t=>{ const f=await companionFixture(t,outcome);f.setNow(Date.parse(cutoff)+61001);await f.dispatcher.tick(); const hui=f.store.all('batches').filter(batch=>batch.notificationMode==='huizhou');assert.equal(hui.length,1);assert.deepEqual(f.store.get('batches',f.normal.id),f.normal);assert.equal(f.store.get('orders',f.orderId).status,outcome); f.store.beginSending(hui[0].id);f.store.finishSending(hui[0].id,'unknown','unknown fixture');await f.dispatcher.tick();assert.equal(f.store.all('batches').length,2);assert.equal(f.store.get('batches',hui[0].id).status,'unknown'); }); for(const outcome of ['sent','unknown'])test(`expired Hui companion blocks independently of normal ${outcome}`,async t=>{ const f=await companionFixture(t,outcome);f.setNow(Date.parse(cutoff)+1800001);await f.dispatcher.tick(); const order=f.store.get('orders',f.orderId);assert.equal(order.status,outcome);assert.equal(order.notifications.huizhou.status,'blocked');assert.match(order.notifications.huizhou.error,/30分钟/);assert.equal(order.notifications.huizhou.missedWindow.end,cutoff);assert.equal(order.missedWindow,undefined);assert.deepEqual(f.store.get('batches',f.normal.id),f.normal); });