fix: make order processing authorized and recoverable
This commit is contained in:
1 parent
0ab7d62aa6
commit
7e42a6dcc6
15 files changed
+219
-129
No files matched your search
@@ -94,7 +94,7 @@ test('batch refuses inverted windows and windows that do not end at its cutoff',
|
||||
|
||||
const {OrderRuleDispatcher}=require('../../src/modules/order-rules/dispatcher.cjs');
|
||||
const dispatchCutoff='2026-10-20T01:00:00.000Z';
|
||||
const dispatchWindow={start:'2026-10-19T16:00:00.000Z',end:dispatchCutoff,label:'当天首时段',startInclusive:true,endInclusive:false};
|
||||
const dispatchWindow={start:'2026-10-19T09:00:00.000Z',end:dispatchCutoff,label:'当天首时段',startInclusive:true,endInclusive:false};
|
||||
function dispatchFixture(t,{ready=true,capabilities=true,enabled=true,verify,send,result}={}){
|
||||
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'rule-batch-'));t.after(()=>fs.rmSync(dir,{recursive:true,force:true}));
|
||||
const content=Buffer.from('%PDF-1.7\ntrusted evidence');const file=path.join(dir,'order.pdf');fs.writeFileSync(file,content);
|
||||
@@ -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-19T16: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}),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 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:['user@example.com','copy@example.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');
|
||||
@@ -120,7 +120,7 @@ test('dispatcher never prepares or touches SMTP while disabled or any provider i
|
||||
test('dispatcher verifies recorded bytes and sends the frozen recipients and content once per schedule',async t=>{
|
||||
const f=dispatchFixture(t,{verify:({batch})=>{batch.subject='changed';batch.to=['intruder@example.com'];}});
|
||||
await due(f);await f.dispatcher.tick();
|
||||
assert.equal(f.record.status,'sent');assert.equal(f.record.prepared,1);assert.equal(f.record.begun,1);assert.equal(f.record.locked,1);
|
||||
assert.equal(f.record.status,'sent');assert.equal(f.record.prepared,2);assert.equal(f.record.begun,1);assert.equal(f.record.locked,2);
|
||||
const sent=f.record.sent[0];assert.equal(sent.subject,'已冻结 SO-1');assert.deepEqual(sent.to,['user@example.com']);assert.deepEqual(sent.cc,['copy@example.com']);
|
||||
assert.equal(sent.attachments[0].content.toString(),'%PDF-1.7\ntrusted evidence');assert.equal(sent.disableFileAccess,true);assert.equal(sent.disableUrlAccess,true);assert.equal(sent.attachments[0].path,undefined);
|
||||
await f.dispatcher.stop();
|
||||
@@ -171,7 +171,7 @@ test('dispatcher never carries a prepared morning batch into the afternoon slot
|
||||
await due(f);assert.equal(f.record.begun,0);
|
||||
f.config.enabled=true;f.setNow('2026-10-20T08:59:00.000Z');await f.dispatcher.tick();
|
||||
f.setNow('2026-10-20T09:00:00.000Z');await f.dispatcher.tick();
|
||||
assert.equal(f.record.status,'prepared');assert.equal(f.record.sent.length,0);await f.dispatcher.stop();
|
||||
assert.equal(f.record.status,'failed');assert.equal(f.record.sent.length,0);await f.dispatcher.stop();
|
||||
});
|
||||
|
||||
test('dispatcher ignores old, future and mismatched-window prepared batches at the current slot',async t=>{
|
||||
@@ -188,13 +188,13 @@ test('dispatcher resumes a paused prepared batch only within the same slot grace
|
||||
assert.equal(f.record.sent.length,1);await f.dispatcher.stop();
|
||||
});
|
||||
|
||||
test('dispatcher does not resume a prepared batch after its slot grace expires',async t=>{
|
||||
test('dispatcher resumes a frozen batch after collection ends within queue allowance',async t=>{
|
||||
const f=dispatchFixture(t);const exclusive=f.mail.exclusive;let busy=true;
|
||||
f.mail.exclusive=async(id,work)=>{if(busy)throw Object.assign(Error('busy'),{status:409});return exclusive(id,work);};
|
||||
await due(f);busy=false;f.setNow('2026-10-20T01:01:01.000Z');await f.dispatcher.tick();assert.equal(f.record.prepared,0);assert.equal(f.record.sent.length,0);await f.dispatcher.stop();
|
||||
await due(f);busy=false;f.setNow('2026-10-20T01:01:01.000Z');await f.dispatcher.tick();assert.equal(f.record.prepared,0);assert.equal(f.record.sent.length,1);await f.dispatcher.stop();
|
||||
});
|
||||
|
||||
test('dispatcher rechecks slot expiration after asynchronous SMTP verification',async t=>{
|
||||
const f=dispatchFixture(t,{verify:()=>f.setNow('2026-10-20T01:01:01.000Z')});
|
||||
test('dispatcher rechecks thirty minute queue expiration after asynchronous SMTP verification',async t=>{
|
||||
const f=dispatchFixture(t,{verify:()=>f.setNow('2026-10-20T01:30:01.000Z')});
|
||||
await due(f);assert.equal(f.record.begun,0);assert.equal(f.record.sent.length,0);assert.equal(f.record.status,'failed');await f.dispatcher.stop();
|
||||
});
|
||||
@@ -12,7 +12,7 @@ function fixture(t){
|
||||
let captures=0,exports=0,failCapture=false;
|
||||
const row={source:'todo',instanceId:'i1',taskId:'t1',revision:'1',processName:'备损订单更改评审',nodeName:'订单专员(订单通知书)',processVersion:'1.4',receivedAt:'2026-10-19T01:00:00Z',serialNum:'S1',title:'订单号:SO-1 客户简称:真实客户'};
|
||||
const provider={capabilities:()=>({liveTodo:true,pdfExport:true,message:'actual probe'}),scan:async(c,p)=>{assert.equal(p.sessionId,'test-session');return [row];},capture:async()=>{captures++;if(failCapture)throw Error('capture unavailable');return {sample:{...row,connectionId:'c1',brief:'摘要',fields:{order:'SO-1',brief:'真实摘要'}},snapshot:{processVersion:'1.4',html:'<p>real fixture</p>',fields:[{path:'order',label:'订单号',value:'SO-1'},{path:'brief',label:'摘要',value:'真实摘要'}]}};}};
|
||||
const archive={probe:async()=>({automaticArchive:true,pdfExport:true,message:'runtime'}),capabilities:()=>({automaticArchive:true,pdfExport:true}),archive:async()=>{exports++;const content=Buffer.from('%PDF-1.7\nfixture');const file=path.join(dir,'order.pdf');fs.writeFileSync(file,content);return {archivedAt:now().toISOString(),files:[{name:'order.pdf',path:file,size:content.length,sha256:crypto.createHash('sha256').update(content).digest('hex'),kind:'pdf'}]};}};
|
||||
const archive={read:async file=>fs.promises.readFile(file.path),probe:async()=>({automaticArchive:true,pdfExport:true,message:'runtime'}),capabilities:()=>({automaticArchive:true,pdfExport:true}),archive:async()=>{exports++;const content=Buffer.from('%PDF-1.7\nfixture');const file=path.join(dir,'order.pdf');fs.writeFileSync(file,content);return {archivedAt:now().toISOString(),files:[{name:'order.pdf',path:file,size:content.length,sha256:crypto.createHash('sha256').update(content).digest('hex'),kind:'pdf'}]};}};
|
||||
const execution=new OrderExecutionCoordinator({store,workspace,provider,archive,clock:now});
|
||||
return {store,execution,row,provider,archive,principal,setFail:v=>{failCapture=v;},counts:()=>({captures,exports})};
|
||||
}
|
||||
@@ -51,11 +51,11 @@ test('cold restart probes archived pending work and restores dispatch gates with
|
||||
const execution=new OrderExecutionCoordinator({...f.execution,provider,archive});
|
||||
assert.equal(execution.snapshot().capabilities.pdfExport,false);
|
||||
await execution.scan({connectionId:'c1',idempotencyKey:'cold-restart'},principal);
|
||||
assert.deepEqual(execution.snapshot().capabilities,{liveTodo:true,pdfExport:true,automaticArchive:true});assert.equal(captured,true);assert.equal(probed,true);assert.equal(f.counts().exports,before.exports);assert.equal(f.store.all('orders')[0].status,'pending');
|
||||
assert.deepEqual(execution.snapshot().capabilities,{liveTodo:true,pdfExport:true,automaticArchive:true});assert.equal(captured,false);assert.equal(probed,true);assert.equal(f.counts().exports,before.exports);assert.equal(f.store.all('orders')[0].status,'pending');
|
||||
await execution.stop();
|
||||
f.store.prepare('2026-10-19T03:00:00Z','admin');captured=false;probed=false;
|
||||
const batchedRestart=new OrderExecutionCoordinator({...f.execution,provider,archive});await batchedRestart.scan({connectionId:'c1',idempotencyKey:'cold-batched-restart'},principal);
|
||||
assert.equal(batchedRestart.snapshot().tasks[0].status,'batched');assert.equal(f.store.providersReady(),true);assert.equal(f.counts().exports,before.exports);assert.equal(captured,true);assert.equal(probed,true);await batchedRestart.stop();
|
||||
assert.equal(batchedRestart.snapshot().tasks[0].status,'batched');assert.equal(f.store.providersReady(),true);assert.equal(f.counts().exports,before.exports);assert.equal(captured,false);assert.equal(probed,true);await batchedRestart.stop();
|
||||
});
|
||||
for(const supportsRecovery of [false,true])test(`committed archive receipt reconciles interrupted task before uncertainty classification (recovery=${supportsRecovery})`,async t=>{
|
||||
const f=fixture(t);await configure(f);await f.execution.scan({connectionId:'c1',idempotencyKey:'archived'},principal);
|
||||
@@ -65,12 +65,12 @@ for(const supportsRecovery of [false,true])test(`committed archive receipt recon
|
||||
await execution.scan({connectionId:'c1',idempotencyKey:'reconciled'},principal);assert.equal(f.counts().exports,before.exports);assert.deepEqual(f.store.get('orders',order.id).archive,order.archive);assert.equal(f.store.prepare('2026-10-19T03:00:00Z','admin').length,1);
|
||||
await execution.stop();
|
||||
});
|
||||
test('unavailable original source leaves archived work blocked without replay or discarding its receipt',async t=>{
|
||||
test('unavailable original source does not block valid archived receipts',async t=>{
|
||||
const f=fixture(t);await configure(f);await f.execution.scan({connectionId:'c1',idempotencyKey:'archived'},principal);
|
||||
const before=f.counts(),receipt=f.store.all('orders')[0].archive;
|
||||
const provider={scan:async()=>[],capabilities:()=>({liveTodo:true,pdfExport:false}),capture:async()=>{throw Error('原任务已不在已核验节点');}};
|
||||
const execution=new OrderExecutionCoordinator({...f.execution,provider});await execution.scan({connectionId:'c1',idempotencyKey:'source-unavailable'},principal);
|
||||
assert.equal(f.store.providersReady(),false);assert.equal(execution.snapshot().tasks[0].runtimeCheck.status,'blocked');assert.match(execution.snapshot().tasks[0].error,/原任务已不在/);assert.equal(f.counts().exports,before.exports);assert.deepEqual(f.store.all('orders')[0].archive,receipt);assert.equal(f.store.prepare('2026-10-19T03:00:00Z','admin').length,0);await execution.stop();
|
||||
assert.equal(f.store.providersReady(),true);assert.equal(execution.snapshot().tasks[0].runtimeCheck.status,'ready');assert.equal(f.counts().exports,before.exports);assert.deepEqual(f.store.all('orders')[0].archive,receipt);assert.equal(f.store.prepare('2026-10-19T03:00:00Z','admin').length,1);await execution.stop();
|
||||
});
|
||||
test('failed frozen batch resend is versioned admin-only idempotent and cannot replay unknown',async t=>{
|
||||
const f=fixture(t);await configure(f);await f.execution.scan({connectionId:'c1',idempotencyKey:'second'},principal);
|
||||
@@ -93,7 +93,7 @@ test('scope, calendar and pause gates survive actual persisted capture provenanc
|
||||
f.execution.systemPrincipal=principal;await f.execution.background();assert.equal(scans,0);
|
||||
f.store.saveSettings({...f.store.settings(),enabled:true,channelId:'channel1'},'admin');f.execution.settings=()=>({schedule:{times:['11:00','17:00'],weekends:false}});f.execution.calendar=()=>[{date:'2026-10-19',kind:'pause',scan:false,send:false}];
|
||||
await f.execution.background();assert.equal(scans,0);
|
||||
f.execution.calendar=()=>[];await f.execution.background();assert.equal(scans,1);
|
||||
f.execution.calendar=()=>[];f.store.put('settings',{...f.store.get('settings','main'),processingEnabled:true,processingSince:'2026-10-19T00:00:00Z'});await f.execution.notifyDiscovery({connectionId:'c1',runId:'calendar-resume',rows:[f.row],startedAt:f.execution.now(),finishedAt:f.execution.now()});await f.execution.background();assert.equal(scans,0);
|
||||
const captured=f.store.fields().samples[0],adapter=f.store.fields().adapters.find(a=>a.sampleId===captured.id);
|
||||
activateFieldMapping(f.store,{sampleId:captured.id,processName:captured.processName,processVersion:captured.processVersion,fields:adapter.fields,version:adapter.draftVersion},admin);
|
||||
assert.equal(f.store.get('rules','bs-change').published.status,'paused');
|
||||
@@ -159,7 +159,7 @@ test('all fifteen categories capture actual fixture fields, archive to temporary
|
||||
let now=new Date('2026-10-19T02:59:00Z');const dispatcher=new OrderRuleDispatcher({store:f.store,mail,settings:()=>({schedule:{times:['11:00','17:00'],weekends:false}}),clock:()=>now,providersReady:()=>true,templateResolver:()=>({id:'template',version:1,subject:'ignored',text:'模板{{订单列表}}',html:'<div>{{订单列表}}</div>',to:['intruder@example.test'],attachments:[]})});
|
||||
await dispatcher.tick();now=new Date('2026-10-19T03:00:00Z');await dispatcher.tick();await dispatcher.stop();
|
||||
assert.equal(messages.length,15);assert.equal(f.store.all('batches').filter(b=>b.status==='sent').length,15);
|
||||
for(const [index,raw] of messages.entries()){const message=await simpleParser(raw);assert.deepEqual(message.to.value.map(x=>x.address),['orders@example.test']);assert.match(message.text,/模板/);assert.match(message.text,/SO-/);assert.equal(message.attachments.length,f.store.all('batches')[index].ruleSnapshot.attachPdf?1:0);}
|
||||
for(const [index,raw] of messages.entries()){const message=await simpleParser(raw);assert.deepEqual(message.to.value.map(x=>x.address),['orders@example.test']);assert.match(message.text,/模板/);assert.match(message.text,/SO-/);assert.equal(message.attachments.length,f.store.all('batches').find(b=>b.subject===message.subject).ruleSnapshot.attachPdf?1:0);}
|
||||
assert.equal(f.counts().exports,15);
|
||||
});
|
||||
for(const partial of [false,true])test(`real loopback SMTP ${partial?'partial refusal stays unknown':'complete envelope refusal is explicitly failed'}`,async t=>{
|
||||
@@ -176,7 +176,7 @@ for(const partial of [false,true])test(`real loopback SMTP ${partial?'partial re
|
||||
});
|
||||
|
||||
function deferred(){let resolve;const promise=new Promise(r=>resolve=r);return {promise,resolve};}
|
||||
test('discovery barrier covers queued scan, complete persisted set, late failure and rebuild of prepared category',async t=>{
|
||||
test('discovery barrier preserves frozen collection and explicitly blocks late same-window arrivals',async t=>{
|
||||
const f=fixture(t);f.execution.clock=f.store.clock=()=>new Date('2026-10-19T03:00:00Z');await configure(f);await f.execution.scan({connectionId:'c1',idempotencyKey:'ready'},principal);
|
||||
const cutoff='2026-10-19T03:00:00Z',batch=f.store.prepare(cutoff,'admin')[0];assert.ok(batch);
|
||||
const discovery=deferred(),capture=deferred(),entered=deferred(),original={...f.row};let fail=true;
|
||||
@@ -188,10 +188,9 @@ test('discovery barrier covers queued scan, complete persisted set, late failure
|
||||
discovery.resolve([original,{...original,taskId:'late1',instanceId:'late1'},{...original,taskId:'late2',instanceId:'late2'}]);await entered.promise;
|
||||
assert.equal(f.store.all('execution-tasks').length,3,'all relevant identities persisted before first awaited capture');
|
||||
assert.equal(f.store.prepare(cutoff,'admin').length,0);capture.resolve();await scanning;
|
||||
assert.throws(()=>f.store.beginSending(batch.id),/扫描|完整/);assert.equal(f.store.prepare(cutoff,'admin').length,0);
|
||||
assert.equal(f.store.prepare(cutoff,'admin').length,0);
|
||||
fail=false;await f.execution.scan({connectionId:'c1',idempotencyKey:'recovered'},principal);
|
||||
assert.throws(()=>f.store.beginSending(batch.id),/完整/,'new same-category orders cannot be omitted by old frozen batch');
|
||||
const replacement=f.store.prepare(cutoff,'admin')[0];assert.ok(replacement);assert.equal(replacement.orderIds.length,3);assert.equal(f.store.get('batches',batch.id).status,'cancelled');assert.equal(f.store.beginSending(replacement.id).status,'sending');
|
||||
const replacement=f.store.prepare(cutoff,'admin');assert.equal(replacement.length,0);assert.equal(f.store.get('batches',batch.id).status,'prepared');assert.equal(f.store.get('batches',batch.id).orderIds.length,1);assert.equal(f.store.all('orders').filter(o=>o.blockedByBatchId===batch.id).length,2);assert.equal(f.store.all('business-issues').filter(i=>i.id.startsWith('late:')).length,2);assert.equal(f.store.beginSending(batch.id).status,'sending');
|
||||
});
|
||||
test('cutoff requires a successful post-cutoff discovery for every source and failed zero-row scans stay blocked',async t=>{
|
||||
const f=fixture(t);f.execution.clock=f.store.clock=()=>new Date('2026-10-19T02:00:00Z');await configure(f);await f.execution.scan({connectionId:'c1',idempotencyKey:'ready'},principal);
|
||||
@@ -217,3 +216,9 @@ test('all configured sources require independent complete cutoff discovery and t
|
||||
await assert.rejects(f.execution.retry(task.id,{version:task.version,note:'已经确认恢复条件',idempotencyKey:'denied'}, {user:{username:'operator',role:'operator'},sessionId:'other'}),{status:403});
|
||||
task.conflict=true;f.store.put('execution-tasks',task);assert.equal(f.execution.snapshot(owner).tasks[0].canRetry,false);task.conflict=false;task.status='unknown';f.store.put('execution-tasks',task);assert.equal(f.execution.snapshot(owner).tasks[0].canRetry,false);
|
||||
});
|
||||
test('trusted discovery persists while paused and is consumed without a second list read',async t=>{const f=fixture(t);await configure(f);let scans=0;f.provider.scan=async()=>{scans++;return [f.row];};f.execution.systemPrincipal=principal;await f.execution.notifyDiscovery({connectionId:'c1',runId:'watch1',rows:[f.row],startedAt:'2026-10-19T03:00:00Z',finishedAt:'2026-10-19T03:00:00Z'});await f.execution.background();assert.equal(scans,0);assert.equal(f.store.all('execution-discoveries')[0].status,'pending');assert.ok(f.store.discoveryBlockers('2026-10-19T03:00:00Z').length);f.store.put('settings',{...f.store.get('settings','main'),processingEnabled:true,processingSince:'2026-10-19T00:00:00Z'});await f.execution.background();assert.equal(scans,0);assert.equal(f.counts().exports,1);assert.equal(f.store.all('execution-discoveries')[0].status,'complete');await f.execution.background();assert.equal(scans,0);});
|
||||
test('archived todo disappearance uses receipt readback and never calls capture',async t=>{const f=fixture(t);await configure(f);await f.execution.scan({connectionId:'c1',idempotencyKey:'archive'},principal);f.archive.read=async file=>fs.promises.readFile(file.path);f.provider.scan=async()=>[];f.provider.capture=async()=>{throw Error('must not capture completed source');};await f.execution.scan({connectionId:'c1',idempotencyKey:'gone'},principal);assert.equal(f.execution.snapshot().tasks[0].runtimeCheck.status,'ready');assert.equal(f.counts().exports,1);});
|
||||
test('published migration is atomic versioned idempotent and preserves distribution-only archive',async t=>{const f=fixture(t);await configure(f);await f.execution.scan({connectionId:'c1',idempotencyKey:'archive'},principal);const before=f.store.all('orders')[0],record=f.store.get('rules','bs-change');record.published={...record.published,version:record.published.version+1,to:['new@example.test']};f.store.put('rules',record);const input={version:record.published.version,idempotencyKey:'migration1',note:'更新分发范围依据'};const preview=f.store.previewMigration(record.id,input,'admin');assert.equal(preview.items[0].archiveChanged,false);f.store.applyMigration(record.id,input,'admin');assert.deepEqual(f.store.get('orders',before.id).archive,before.archive);assert.deepEqual(f.store.get('orders',before.id).ruleSnapshot.to,['new@example.test']);f.store.applyMigration(record.id,input,'admin');assert.throws(()=>f.store.applyMigration(record.id,{...input,note:'另一不同处理依据'},'admin'),{status:409});const changed=f.store.get('orders',before.id);changed.status='unknown';f.store.put('orders',changed);assert.equal(f.store.previewMigration(record.id,{...input,idempotencyKey:'m2'},'admin').excluded.length,1);});
|
||||
test('revision resolution preserves identity, suppresses ignored repeat, blocks frozen orders',async t=>{const f=fixture(t);await configure(f);await f.execution.scan({connectionId:'c1',idempotencyKey:'archive'},principal);f.row.title='changed revision content';await f.execution.scan({connectionId:'c1',idempotencyKey:'conflict'},principal);let task=f.store.all('execution-tasks')[0];assert.equal(task.conflict,true);await f.execution.resolve(task.id,{version:task.version,idempotencyKey:'ignore1',resolution:'ignore',note:'人工比对确认忽略变化'},principal);await f.execution.scan({connectionId:'c1',idempotencyKey:'repeat'},principal);task=f.store.get('execution-tasks',task.id);assert.equal(task.conflict,false);const o=f.store.get('orders',task.orderId);o.status='unknown';f.store.put('orders',o);task.conflict=true;task.conflictRow={...task.row,title:'another'};f.store.put('execution-tasks',task);await assert.rejects(f.execution.resolve(task.id,{version:task.version,idempotencyKey:'adopt1',resolution:'adopt',note:'人工确认采用新修订'},principal),{status:409});});
|
||||
test('a new BPM revision is held against the prior identity and cannot bypass a frozen batch',async t=>{const f=fixture(t);await configure(f);await f.execution.scan({connectionId:'c1',idempotencyKey:'archive-old'},principal);const batch=f.store.prepare('2026-10-19T03:00:00Z','admin')[0];f.row.revision='2';await f.execution.scan({connectionId:'c1',idempotencyKey:'revision2'},principal);const task=f.store.all('execution-tasks').find(t=>t.row.revision==='2');assert.equal(task.conflict,true);assert.equal(f.counts().exports,1);await assert.rejects(f.execution.resolve(task.id,{version:task.version,idempotencyKey:'adopt',resolution:'adopt',note:'核对新修订仍不能重发'},principal),{status:409});assert.equal(f.store.get('batches',batch.id).status,'prepared');});
|
||||
test('adopting a new unfrozen revision preserves original evidence and requires fresh archive',async t=>{const f=fixture(t);await configure(f);await f.execution.scan({connectionId:'c1',idempotencyKey:'original'},principal);const original=f.store.all('orders')[0];f.row.revision='2';await f.execution.scan({connectionId:'c1',idempotencyKey:'changed'},principal);const task=f.store.all('execution-tasks').find(t=>t.row.revision==='2');await f.execution.resolve(task.id,{version:task.version,idempotencyKey:'adopt2',resolution:'adopt',note:'人工确认新版业务修订'},principal);await f.execution.scan({connectionId:'c1',idempotencyKey:'process-new'},principal);const order=f.store.get('orders',original.id);assert.equal(order.sample.revision,'2');assert.equal(order.archiveHistory.length,1);assert.equal(f.counts().exports,2);assert.equal(f.store.all('execution-tasks').find(t=>t.row.revision==='1').status,'ignored');assert.equal(f.store.get('execution-tasks',task.id).conflict,false);});
|
||||
@@ -0,0 +1,10 @@
|
||||
'use strict';
|
||||
const {test}=require('node:test');const assert=require('node:assert/strict');
|
||||
const {windowForCutoff,inWindow}=require('../../src/modules/order-rules/window.cjs');
|
||||
test('F01 connection ownership and public projection',()=>{const a=require('../../src/modules/order-rules/access.cjs');const w={recordSources:()=>[{id:'c',owner:'alice',status:'archived'}]};const o={sample:{connectionId:'c',fields:{secret:'private'}},event:{orderNo:'42'}};assert.equal(a.canReadOrder(w,{username:'other',role:'operator'},o),false);assert.equal(a.canReadOrder(w,{username:'alice',role:'operator'},o),true);assert.equal(JSON.stringify(a.publicOrder(o)).includes('private'),false);assert.equal(a.canReadBatch(w,{username:'alice',role:'operator'},{orderIds:['missing']},{get:()=>null}),false);});
|
||||
test('continuous ordinary weekday window includes prior evening',()=>assert.equal(inWindow('2026-10-20T17:30:00+08:00',windowForCutoff('2026-10-21T11:00:00+08:00',{times:['11:00','17:00'],weekends:false})),true));
|
||||
test('independent processing gate and activation baseline',t=>{const fs=require('node:fs'),os=require('node:os'),path=require('node:path');const {RuleStore}=require('../../src/modules/order-rules/store.cjs');const dir=fs.mkdtempSync(path.join(os.tmpdir(),'global-core-'));const s=new RuleStore(dir,{clock:()=>new Date('2026-10-21T02:00:00Z')});t.after(()=>{s.close();fs.rmSync(dir,{recursive:true,force:true});});assert.equal(s.settings().processingEnabled,false);const next=s.saveSettings({...s.settings(),processingEnabled:true},'admin');assert.equal(next.enabled,false);assert.equal(next.processingSince,'2026-10-21T02:00:00.000Z');});
|
||||
test('F02 corrected archive generation never reuses an old destination receipt',async t=>{const fs=require('node:fs/promises'),os=require('node:os'),path=require('node:path'),crypto=require('node:crypto');const {OrderArchiveProvider}=require('../../src/modules/storage/order-archive.cjs');const dir=await fs.mkdtemp(path.join(os.tmpdir(),'archive-generation-'));t.after(()=>fs.rm(dir,{recursive:true,force:true}));const records=new Map(),bytes=Buffer.from('%PDF-test'),sha=crypto.createHash('sha256').update(bytes).digest('hex');let rendered=0;const storage={store:{servers:()=>[{id:'s',enabled:true,host:'server',share:'share',directory:'',state:{readable:true,writable:true}}]},run:async(_,fn)=>fn({},null),operation:async(_,op,args)=>op==='archive'?{filename:args[1],relativePath:args[2]+'/'+args[1],sha256:sha,bytes:bytes.length}:{bytes},readFile:async()=>({bytes})};const a=new OrderArchiveProvider({storage,outputDir:dir,journal:{get:(k,id)=>records.get(k+id),put:(k,v)=>records.set(k+v.id,v)},renderer:async(_,options)=>{await fs.mkdir(options.outputDir,{recursive:true});const file=path.join(options.outputDir,++rendered+'.pdf');await fs.writeFile(file,bytes);return {path:file};}});const order={id:'o',sourceHash:'same',event:{orderNo:'42',serialNum:'s',receivedAt:'2026-10-21T02:00:00Z'}};const rule={archiveDirectory:'\\\\server\\share\\A',filenameDate:'receivedAt'};const original=await a.archive({order,rule,snapshot:{},taskId:'t'});const corrected=await a.archive({order:{...order,archiveGeneration:2},rule:{...rule,archiveDirectory:'\\\\server\\share\\B'},snapshot:{},taskId:'t'});assert.notDeepEqual(corrected.files,original.files);assert.match(corrected.files[0].path,/\\B\\/);assert.equal(rendered,2);await a.archive({order:{...order,archiveGeneration:2},rule:{...rule,archiveDirectory:'\\\\server\\share\\B'},snapshot:{},taskId:'t'});assert.equal(rendered,2);});
|
||||
test('fifteen legally frozen categories finish through slow SMTP within 30 minute queue',async()=>{const {OrderRuleDispatcher}=require('../../src/modules/order-rules/dispatcher.cjs');let now=new Date('2026-10-21T02:59:59Z');const cutoff='2026-10-21T03:00:00.000Z',window=windowForCutoff(cutoff,{times:['11:00','17:00'],weekends:false});const batches=Array.from({length:15},(_,i)=>({id:'b'+i,status:'prepared',cutoff,window,createdAt:cutoff,to:['x@example.test'],cc:[],attachments:[],orderIds:[]}));let sends=0;const store={settings:()=>({enabled:true,channelId:'c'}),snapshot:()=>({capabilities:{liveTodo:true,pdfExport:true,automaticArchive:true},batches}),discoveryBlockers:()=>[],batchIncomplete:()=>false,prepare:()=>[],beginSending:id=>{batches.find(b=>b.id===id).status='sending';},finishSending:(id,status)=>{batches.find(b=>b.id===id).status=status;}};const mail={exclusive:async(_,f)=>f(),store:{channelSecret:()=>({id:'c',version:1,email:'s@example.test',smtp:{}}),guard:()=>{}},smtpFactory:()=>({verify:async()=>{},sendMail:async()=>{sends++;now=new Date(+now+6000);return {accepted:['x@example.test']};},close:()=>{}})};const d=new OrderRuleDispatcher({store,mail,clock:()=>now,settings:()=>({schedule:{times:['11:00','17:00'],weekends:false}}),providersReady:()=>true});await d.tick(now);now=new Date(cutoff);await d.tick(now);assert.equal(sends,15);assert.equal(batches.every(b=>b.status==='sent'),true);});
|
||||
test('blocked collection retries within 60 seconds but never creates a late batch',async()=>{const {OrderRuleDispatcher}=require('../../src/modules/order-rules/dispatcher.cjs');let now=new Date('2026-10-21T03:00:00Z'),prepares=0;const store={settings:()=>({enabled:true,channelId:'c'}),snapshot:()=>({capabilities:{liveTodo:true,pdfExport:true,automaticArchive:true},batches:[]}),discoveryBlockers:()=>[],prepare:()=>{prepares++;return [];}};const d=new OrderRuleDispatcher({store,mail:{exclusive:async(_,fn)=>fn()},clock:()=>now,settings:()=>({schedule:{times:['11:00','17:00'],weekends:false}}),providersReady:()=>true});await d.tick();now=new Date(+now+30000);await d.tick();assert.equal(prepares,2);now=new Date(+now+31000);await d.tick();assert.equal(prepares,2);});
|
||||
test('external rules snapshot filters foreign orders mixed batches audit and raw form evidence',async()=>{const {orderRuleApi}=require('../../src/modules/order-rules/api.cjs');const owned={id:'own',sample:{connectionId:'a',fields:{private:'secret-owned'}},event:{orderNo:'OWN'}},foreign={id:'foreign',sample:{connectionId:'b',fields:{private:'secret-other'}},event:{orderNo:'FOREIGN'}};const orders=[owned,foreign],batches=[{id:'mixed',orderIds:['own','foreign'],text:'private frozen body'},{id:'owned',orderIds:['own']}];let output;await orderRuleApi({orderRules:{snapshot:()=>({orders,batches,audit:[{detail:'foreign evidence'}]}),get:(_,id)=>orders.find(o=>o.id===id)},workspace:{recordSources:()=>[{id:'a',owner:'alice'},{id:'b',owner:'bob'}]},user:{username:'alice',role:'operator'},route:'/api/order-rules',method:'GET',reply:(_,value)=>{output=value;}});assert.deepEqual(output.orders.map(o=>o.id),['own']);assert.deepEqual(output.batches.map(b=>b.id),['owned']);assert.deepEqual(output.audit,[]);assert.doesNotMatch(JSON.stringify(output),/secret-|FOREIGN|private frozen/);});
|
||||
@@ -87,16 +87,15 @@ test('pausing a rule prevents a prepared batch from entering SMTP sending',t=>{
|
||||
store.pause(rule.id,{version:rule.version},'admin');assert.throws(()=>store.beginSending(batch.id),e=>e.status===409);
|
||||
assert.equal(store.snapshot().batches[0].status,'prepared');
|
||||
});
|
||||
test('late discovery rebuilds an unsent reservation as one complete batch and never carries it into a later slot',t=>{
|
||||
test('late discovery cannot alter a frozen reservation and leaves explicit operator work',t=>{
|
||||
const {store}=fixture(t,{capabilities:{liveTodo:true,pdfExport:true,automaticArchive:true}}),sample=configure(store);
|
||||
const archive=(sample)=>{const order=store.ingest(sample,'system');store.recordArchive(order.id,{files:[{name:order.id+'.pdf',path:'C:\\archive\\'+order.id+'.pdf',sha256:'a'.repeat(64),size:42,kind:'pdf'}],archivedAt:'2026-10-19T01:05:00Z'},'archive-executor');return order;};
|
||||
archive(sample);assert.equal(store.prepare('2026-10-19T03:00:00Z','admin').length,1);
|
||||
archive({...sample,instanceId:'late',taskId:'late'});
|
||||
const replacement=store.prepare('2026-10-19T03:00:00Z','admin');assert.equal(replacement.length,1);assert.equal(replacement[0].orderIds.length,2);assert.equal(store.snapshot().batches.filter(b=>b.status==='prepared').length,1);
|
||||
assert.equal(store.prepare('2026-10-19T03:00:00Z','admin').length,0);
|
||||
assert.equal(store.prepare('2026-10-19T09:00:00Z','admin').length,0);
|
||||
assert.equal(store.snapshot().orders.filter(o=>o.status==='ignored').length,2);
|
||||
const order=store.ingest(sample,'system');store.recordArchive(order.id,{files:[{name:'o.pdf',path:'C:\\archive\\o.pdf',sha256:'a'.repeat(64),size:42,kind:'pdf'}],archivedAt:'2026-10-19T01:05:00Z'},'archive-executor');
|
||||
const frozen=store.prepare('2026-10-19T03:00:00Z','admin')[0];
|
||||
const late=store.ingest({...sample,instanceId:'late',taskId:'late'},'system');assert.equal(late.status,'blocked');assert.equal(late.blockedByBatchId,frozen.id);
|
||||
assert.equal(store.prepare('2026-10-19T03:00:00Z','admin').length,0);assert.equal(store.get('batches',frozen.id).status,'prepared');assert.deepEqual(store.get('batches',frozen.id).orderIds,[order.id]);assert.ok(store.get('business-issues','late:'+late.id));
|
||||
assert.throws(()=>store.recheck(late.id,{note:'尝试更改已冻结集合'},'admin'),{status:409});
|
||||
});
|
||||
|
||||
test('old history cannot enter this morning mail while current orders remain eligible',t=>{
|
||||
const {store}=fixture(t,{clock:()=>new Date('2026-10-20T02:00:00Z'),capabilities:{liveTodo:true,pdfExport:true,automaticArchive:true}}),sample=configure(store);
|
||||
const old=store.ingest({...sample,instanceId:'old',taskId:'old',receivedAt:'2026-10-19T01:00:00Z'},'system');
|
||||
@@ -105,7 +104,7 @@ test('old history cannot enter this morning mail while current orders remain eli
|
||||
const current=store.ingest({...sample,instanceId:'current',taskId:'current',receivedAt:'2026-10-20T01:00:00Z'},'system');
|
||||
store.recordArchive(current.id,{files:[{name:'current.pdf',path:'C:\\archive\\current.pdf',sha256:'a'.repeat(64),size:42,kind:'pdf'}],archivedAt:'2026-10-20T01:05:00Z'},'archive-executor');
|
||||
const batches=store.prepare('2026-10-20T03:00:00Z','admin');assert.equal(batches.length,1);assert.deepEqual(batches[0].orderIds,[current.id]);
|
||||
assert.equal(batches[0].window.start,'2026-10-19T16:00:00.000Z');
|
||||
assert.equal(batches[0].window.start,'2026-10-19T09:00:00.000Z');
|
||||
});
|
||||
test('paused old publication cannot shadow an enabled replacement for the same process and node',t=>{
|
||||
const {store}=fixture(t),sample=configure(store);
|
||||
|
||||
@@ -2,9 +2,9 @@
|
||||
const {test}=require('node:test');const assert=require('node:assert/strict');
|
||||
const {windowForCutoff,upcomingWindow,inWindow}=require('../../src/modules/order-rules/window.cjs');
|
||||
const schedule={times:['11:00','17:00'],timezone:'Asia/Shanghai',weekends:false};
|
||||
test('normal weekday only includes same-day first interval or interval between send times',()=>{
|
||||
test('normal weekday first interval continuously covers prior evening',()=>{
|
||||
const morning=windowForCutoff('2026-10-20T03:00:00Z',schedule),afternoon=windowForCutoff('2026-10-20T09:00:00Z',schedule);
|
||||
assert.equal(morning.start,'2026-10-19T16:00:00.000Z');assert.equal(morning.end,'2026-10-20T03:00:00.000Z');
|
||||
assert.equal(morning.start,'2026-10-19T09:00:00.000Z');assert.equal(morning.end,'2026-10-20T03:00:00.000Z');
|
||||
assert.equal(afternoon.start,'2026-10-20T03:00:00.000Z');assert.equal(afternoon.end,'2026-10-20T09:00:00.000Z');
|
||||
assert.equal(inWindow('2026-10-19T08:00:00Z',morning),false);
|
||||
assert.equal(inWindow('2026-10-20T03:00:00Z',morning),false);assert.equal(inWindow('2026-10-20T03:00:00Z',afternoon),true);
|
||||
|
||||
Reference in new issue
Block a user