Files
order-notification-automation/tests/order-rules/restricted-test.test.cjs
T

118 lines
15 KiB
JavaScript

'use strict';
const test=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs'),os=require('node:os'),path=require('node:path'),crypto=require('node:crypto');
const {RuleStore}=require('../../src/modules/order-rules/store.cjs');
const {activateFieldMapping}=require('../fixtures/activate-field-mapping.cjs');
const admin={username:'admin',role:'admin'};
function fixture(t,{all=false}={}){
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'restricted-test-')),desktop=path.join(dir,'Desktop'),local=path.join(desktop,'run');fs.mkdirSync(local,{recursive:true});
const root='\\\\localhost\\'+local[0]+'$'+local.slice(2),options={clock:()=>new Date('2026-10-22T01:00:00Z'),capabilities:{liveTodo:true,pdfExport:true,automaticArchive:true},desktopRoot:desktop};
let store=new RuleStore(path.join(dir,'state'),options);t.after(()=>{store.close();fs.rmSync(dir,{recursive:true,force:true});});
const ids=all?store.all('rules').map(r=>r.id):['bs-change'];let sample;
for(const id of ids){const rule=store.get('rules',id).draft;
// Isolated BPM catalog evidence is distinct from historical field samples.
require('../../src/modules/order-rules/scope-catalog.cjs').observe(store,require('../../src/modules/order-rules/scopes.cjs').scopesFor(rule).map(scope=>({...scope,source:'todo'})));
sample={connectionId:'c1',source:'history',configurationOnly:true,timestampType:'process-start',instanceId:'history-'+id,taskId:'h-'+id,revision:'1',processName:rule.processNames[0],processVersion:'test-1',nodeName:'历史节点',receivedAt:'2026-10-21T01:00:00Z',serialNum:'S-'+id,title:'订单号:123456 客户简称:测试客户',fields:{order:'123456'}};
const captured=store.recordCapture({sample,snapshot:{processVersion:'test-1',fields:[{path:'order',label:'订单号',value:'123456'}]},taskId:sample.taskId});
const active=activateFieldMapping(store,{sampleId:captured.id,processName:sample.processName,processVersion:sample.processVersion,fields:{orderNo:'order'}},admin);
const current=store.get('rules',id).draft;
store.saveRule({...current,adapterIds:[active.id],to:['2639266652@qq.com'],cc:[],attachPdf:false,archiveDirectory:root+'\\'+id,filenameDate:'receivedAt'},'admin');
}
const input=()=>({version:store.restrictedTest()?.version||0,enabled:true,recipient:'2639266652@qq.com',archiveRoot:root,channelId:'test-channel',ruleIds:ids});
return {get store(){return store;},root,local,desktop,sample,ids,input,reopen(){store.close();store=new RuleStore(path.join(dir,'state'),options);},future(patch={}){const r=store.get('rules','bs-change').draft;return {...sample,processName:r.processNames[0],nodeName:r.nodeNames[0],source:'todo',configurationOnly:false,timestampType:'received',instanceId:'live-1',taskId:'live-1',receivedAt:'2026-10-22T01:00:01Z',...patch};}};
}
test('history prepares 15 independent test snapshots without granting formal publication',t=>{
const f=fixture(t,{all:true}),before=f.store.all('rules').map(r=>[r.id,r.published,r.trialSampleId]);
const run=f.store.saveRestrictedTest(f.input(),admin);
assert.equal(run.enabled,true);assert.equal(run.ruleCount,15);assert.equal(run.since,'2026-10-22T01:00:00.000Z');
assert.deepEqual(f.store.all('rules').map(r=>[r.id,r.published,r.trialSampleId]),before);
for(const record of f.store.all('rules')){const rule=f.store.executionRule(record);assert.equal(rule.testRunId,run.id);assert.deepEqual(rule.to,['2639266652@qq.com']);assert.deepEqual(rule.cc,[]);}
const record=f.store.get('rules','bs-change');assert.throws(()=>f.store.publish(record.id,{version:record.draft.version},'admin'),{status:409});
});
test('restricted ingest refuses history, configuration-only, future dates and pre-baseline arrivals',t=>{
const f=fixture(t);f.store.saveRestrictedTest(f.input(),admin);
for(const patch of [{source:'history'},{configurationOnly:true},{receivedAt:'2026-10-22T00:59:59Z'},{receivedAt:'2026-10-23T01:00:00Z'}])assert.throws(()=>f.store.ingest(f.future(patch),'admin'),{status:409});
const order=f.store.ingest(f.future({receivedAt:'2026-10-22T01:00:00Z'}),'admin');assert.equal(order.status,'identified',order.error);assert.ok(order.ruleSnapshot.testRunId);assert.equal(f.store.all('orders').length,1);
});
test('test state survives restart, pauses without falling back to publication and locks destinations',t=>{
const f=fixture(t),sample=f.future({receivedAt:'2026-10-22T01:00:00Z'}),captured=f.store.recordCapture({sample,taskId:'formal-fixture',snapshot:{processVersion:sample.processVersion,fields:[{path:'order',value:'123456'}]}});
assert.equal(f.store.capturedPreview(captured.id).valid,true);f.store.publish('bs-change',{version:f.store.get('rules','bs-change').draft.version},'admin');
const published=f.store.get('rules','bs-change').published,run=f.store.saveRestrictedTest(f.input(),admin);f.reopen();assert.equal(f.store.restrictedTest().id,run.id);
for(const patch of [{recipient:'other@qq.com'},{archiveRoot:f.root+'\\other'},{channelId:'other'}])assert.throws(()=>f.store.saveRestrictedTest({...f.input(),...patch},admin),{status:409});
const paused=f.store.saveRestrictedTest({version:run.version,enabled:false},admin);assert.equal(paused.enabled,false);assert.equal(f.store.executionRule(f.store.get('rules','bs-change')),null);
assert.throws(()=>f.store.ingest(f.future(),'admin'),{status:409});
const resumed=f.store.saveRestrictedTest({version:paused.version,enabled:true},admin);assert.equal(resumed.since,run.since);assert.equal(resumed.id,run.id);
assert.throws(()=>f.store.saveRestrictedTest({version:run.version,enabled:false},admin),{status:409});
assert.deepEqual(f.store.get('rules','bs-change').published,published);
assert.throws(()=>f.store.previewMigration('bs-change',{version:published.version,idempotencyKey:'restricted-migration',note:'验证测试隔离迁移'}),{status:409});
});
test('all 15 classes ingest future real events through their original exact node pairs',t=>{
const f=fixture(t,{all:true});f.store.saveRestrictedTest(f.input(),admin);
for(const record of f.store.all('rules')){const r=f.store.executionRule(record),scope=r.scopes[0],sample={...f.sample,...scope,source:'todo',configurationOnly:false,timestampType:'received',receivedAt:'2026-10-22T01:00:00Z',instanceId:'live-'+r.id,taskId:'live-'+r.id};const order=f.store.ingest(sample,'admin');assert.equal(order.status,'identified',r.id+': '+order.error);assert.equal(order.categoryId,r.id);}
assert.equal(f.store.all('orders').length,15);
});
test('test configuration checks admin role, QQ, Desktop path and active mapping evidence',t=>{
const f=fixture(t);
assert.throws(()=>f.store.saveRestrictedTest(f.input(),{username:'op',role:'operator'}),{status:403});
for(const patch of [{recipient:'test@example.test'},{archiveRoot:'\\\\nas\\orders'},{archiveRoot:f.root+'\\..\\..\\elsewhere'}])assert.throws(()=>f.store.saveRestrictedTest({...f.input(),...patch},admin));
const adapter=f.store.adapters().find(a=>a.verified&&!a.reference);f.store.put('field-adapters',{...adapter,evidenceHash:'changed'});
assert.throws(()=>f.store.saveRestrictedTest(f.input(),admin),{status:409});
});
test('frozen test rule ignores draft edits but stops when its mapping evidence changes',t=>{
const f=fixture(t);f.store.saveRestrictedTest(f.input(),admin);const record=f.store.get('rules','bs-change');
f.store.saveRule({...record.draft,to:['elsewhere@example.test'],archiveDirectory:'\\\\nas\\orders'},'admin');
assert.deepEqual(f.store.executionRule(f.store.get('rules','bs-change')).to,['2639266652@qq.com']);
const adapter=f.store.adapters().find(a=>a.verified&&!a.reference);f.store.put('field-adapters',{...adapter,version:adapter.version+1});
assert.equal(f.store.executionRule(f.store.get('rules','bs-change')),null);
});
test('archive provider blocks outside and symlink targets before rendering or writing',async t=>{
const f=fixture(t);f.store.saveRestrictedTest(f.input(),admin);const rule=f.store.executionRule(f.store.get('rules','bs-change'));
const {OrderArchiveProvider}=require('../../src/modules/storage/order-archive.cjs');let rendered=0;
const archive=new OrderArchiveProvider({journal:f.store,storage:{},outputDir:f.local,renderer:async()=>{rendered++;throw Error('renderer should never run');}});
await assert.rejects(archive.archive({order:{id:'o',event:{}},rule:{...rule,archiveDirectory:'\\\\nas\\orders'},snapshot:{}}),{status:409});assert.equal(rendered,0);
const outside=fs.mkdtempSync(path.join(os.tmpdir(),'restricted-outside-'));t.after(()=>fs.rmSync(outside,{recursive:true,force:true}));
fs.symlinkSync(outside,path.join(f.local,'escape'),'junction');
await assert.rejects(archive.probe({...rule,archiveDirectory:f.root+'\\escape'}),{status:409});assert.equal(rendered,0);
});
test('dispatcher prevents changed recipients and paused tests at the actual SMTP boundary',async t=>{
const f=fixture(t);const run=f.store.saveRestrictedTest(f.input(),admin),order=f.store.ingest(f.future(),'admin');
const content=Buffer.from('%PDF-1.7 test'),file={name:'order.pdf',path:f.root+'\\bs-change\\order.pdf',size:content.length,sha256:crypto.createHash('sha256').update(content).digest('hex'),kind:'pdf'};
f.store.recordArchive(order.id,{archivedAt:f.store.now(),files:[file]},'admin');
const settings=f.store.get('settings','main');f.store.put('settings',{...settings,channelId:'test-channel',enabled:true,processingEnabled:true});
f.store.clock=()=>new Date('2026-10-22T03:00:00Z');const [batch]=f.store.prepare('2026-10-22T03:00:00Z','admin');assert.ok(batch);
const {OrderRuleDispatcher}=require('../../src/modules/order-rules/dispatcher.cjs');let sends=0,checks=0;
const mail={clients:new Set(),store:{channelSecret:()=>({id:'test-channel',version:1,email:'sender@example.test',smtp:{}}),guard:()=>{}},smtpFactory:()=>({verify:async()=>{checks++;f.store.saveRestrictedTest({version:run.version,enabled:false},admin);},sendMail:async()=>{sends++;return {accepted:['2639266652@qq.com']};}})};
const dispatcher=new OrderRuleDispatcher({store:f.store,mail,settings:()=>({}),clock:f.store.clock,providersReady:()=>true,attachmentReader:async()=>content});
await dispatcher.dispatch({...batch,to:['outside@example.test']},f.store.settings());assert.equal(checks,0);assert.equal(sends,0);
// Use a new reservation for the asynchronous pause case, preserving normal transitions.
f.store.put('batches',batch);const reserved=f.store.get('orders',order.id);reserved.status='batched';reserved.batchId=batch.id;f.store.put('orders',reserved);
await dispatcher.dispatch(batch,f.store.settings());assert.equal(checks,1);assert.equal(sends,0);assert.equal(f.store.get('batches',batch.id).status,'failed');
});
test('execution scans only post-baseline matching todo nodes and archives using test snapshots',async t=>{
const f=fixture(t);f.store.saveRestrictedTest(f.input(),admin);let captures=0,exports=0;
const connection={id:'c1',owner:'admin',status:'connected'},row=f.future(),principal={user:admin,sessionId:'s'};
const provider={scan:async()=>[{...row,taskId:'old',receivedAt:'2026-10-22T00:59:59Z'},{...row,taskId:'history',source:'history'},{...row,taskId:'wrong',nodeName:'人工审批'},row],capabilities:()=>({liveTodo:true,pdfExport:true}),capture:async()=>{captures++;return {sample:row,snapshot:{processVersion:row.processVersion,fields:[{path:'order',value:'123456'}]}};}};
const archive={probe:async rule=>{assert.ok(rule.testRunId);return {pdfExport:true,automaticArchive:true};},archive:async({rule})=>{exports++;assert.deepEqual(rule.to,['2639266652@qq.com']);return {archivedAt:f.store.now(),files:[{path:rule.archiveDirectory+'\\one.pdf',name:'one.pdf',kind:'pdf',size:1,sha256:'a'.repeat(64)}]};}};
const {OrderExecutionCoordinator}=require('../../src/modules/order-execution/coordinator.cjs');
const execution=new OrderExecutionCoordinator({store:f.store,workspace:{getConnection:()=>connection,snapshot:()=>({connections:[connection]})},provider,archive,clock:f.store.clock});t.after(()=>execution.stop());
await execution.scan({connectionId:'c1',idempotencyKey:'test-future'},principal);
assert.equal(captures,1);assert.equal(exports,1);assert.equal(f.store.all('orders')[0]?.status,'pending');assert.equal(f.store.all('execution-tasks').length,1);
});
test('restricted API permits only administrators and retains fixed destinations on versioned pause',async t=>{
const f=fixture(t),{orderRuleApi}=require('../../src/modules/order-rules/api.cjs');let result;
const call=(user,body)=>orderRuleApi({orderRules:f.store,workspace:{record:()=>{}},mail:{store:{publicChannel:()=>({state:{smtp:true}}),categoryTemplate:()=>null}},user,route:'/api/order-rules/restricted-test',method:'POST',body,reply:(status,value)=>{assert.equal(status,200);result=value;}});
for(const role of ['viewer','operator'])await assert.rejects(call({username:role,role},f.input()),{status:403});
await call(admin,f.input());assert.equal(result.ruleCount,1);
await call(admin,{version:result.version,enabled:false});assert.equal(result.enabled,false);assert.equal(result.recipient,'2639266652@qq.com');
});
test('uncertain SMTP outcome stays unknown across test restart and cannot be resent automatically',async t=>{
const f=fixture(t);f.store.saveRestrictedTest(f.input(),admin);const order=f.store.ingest(f.future(),'admin'),content=Buffer.from('%PDF-1.7 test');
f.store.recordArchive(order.id,{archivedAt:f.store.now(),files:[{name:'one.pdf',path:f.root+'\\bs-change\\one.pdf',size:content.length,sha256:crypto.createHash('sha256').update(content).digest('hex'),kind:'pdf'}]},'admin');
const settings=f.store.get('settings','main');f.store.put('settings',{...settings,enabled:true,channelId:'test-channel'});f.store.clock=()=>new Date('2026-10-22T03:00:00Z');const [batch]=f.store.prepare('2026-10-22T03:00:00Z','admin');
const {OrderRuleDispatcher}=require('../../src/modules/order-rules/dispatcher.cjs');let sent=0;
const mail={clients:new Set(),exclusive:async(_,fn)=>fn(),store:{channelSecret:()=>({id:'test-channel',version:1,email:'sender@example.test',smtp:{}}),guard:()=>{}},smtpFactory:()=>({verify:async()=>{},sendMail:async message=>{assert.deepEqual(message.to,['2639266652@qq.com']);assert.deepEqual(message.cc,[]);sent++;throw Error('connection lost after DATA');}})};
const sender=()=>new OrderRuleDispatcher({store:f.store,mail,settings:()=>({schedule:{times:['11:00','17:00'],weekends:false}}),clock:f.store.clock,providersReady:()=>true,attachmentReader:async()=>content});
await sender().dispatch(batch,f.store.settings());assert.equal(f.store.get('batches',batch.id).status,'unknown');
f.reopen();assert.equal(f.store.get('batches',batch.id).status,'unknown');await sender().tick();assert.equal(sent,1);
await assert.rejects(sender().resend(batch.id,{version:f.store.get('batches',batch.id).version,idempotencyKey:'unknown-retry',note:'不得重发待核实邮件'},admin),{status:409});assert.equal(sent,1);
});