141 lines
18 KiB
JavaScript
141 lines
18 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 {extractTitle}=require('../../src/modules/order-rules/title.cjs');
|
|
const {OrderRuleDispatcher}=require('../../src/modules/order-rules/dispatcher.cjs');
|
|
const {activateReferenceMapping}=require('../fixtures/activate-field-mapping.cjs');
|
|
const {orderDetail,batchDetail,summary}=require('../../src/modules/order-rules/query.cjs');
|
|
const {previewEffects}=require('../../src/modules/order-rules/effects-preview.cjs');
|
|
const cutoff='2026-10-19T03:00:00.000Z',admin={username:'admin',role:'admin'};
|
|
const mixed='订单号:O-100机芯号:CORE-O客户简称:普通客户总数量:10订单类别:参考订单订单类型:C业务模式:惠州数字毛利:绿标订单号:H-200机芯号:CORE-H客户简称:惠州创维数字技术有限公司总数量:20';
|
|
function fixture(t,{enabled=true,title=mixed,template={}}={}){
|
|
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'huizhou-delivery-')),clock=()=>new Date('2026-10-19T02:00:00Z');
|
|
const options={clock,capabilities:{liveTodo:true,pdfExport:true,automaticArchive:true}};let store=new RuleStore(dir,options);
|
|
const huiTemplate={id:'hui-template',version:1,status:'active',notificationMode:'huizhou',subject:'惠州 {{订单号}}',text:'业务访问 https://example.test/business\n{{订单明细}}',html:'<p>业务访问 https://example.test/business</p><div>{{订单明细}}</div>',...template};
|
|
const resolver=(category,rule,mode='normal')=>mode==='huizhou'?huiTemplate:null;store.templateResolver=resolver;
|
|
t.after(()=>{store.close();fs.rmSync(dir,{recursive:true,force:true});});
|
|
const reference=require('../../src/modules/order-rules/catalog.cjs').adapters.find(a=>a.id==='bs-change');
|
|
const {sample}=activateReferenceMapping(store,'bs-change',{connectionId:'c1',instanceId:'i1',taskId:'t1',revision:'1',receivedAt:'2026-10-19T01:00:00Z',title,fields:{[reference.fields.orderNo]:extractTitle(title).orders[0].orderNo}});
|
|
const rule=store.saveRule({...store.get('rules','bs-change').draft,to:['USER@example.test'],cc:['copy@example.test'],archiveDirectory:'\\\\server\\orders',filenameDate:'receivedAt',huizhouEnabled:enabled,huizhouTemplateId:enabled?'hui-template':''},'admin');
|
|
// Capture the final real-shaped sample through the normal mapping/trial contract.
|
|
const capture=store.recordCapture({sample,taskId:'final',snapshot:{processVersion:sample.processVersion,fields:Object.entries(sample.fields).map(([path,value])=>({path,value}))}});
|
|
assert.equal(store.capturedPreview(capture.id).valid,true);store.publish(rule.id,{version:rule.version},'admin');
|
|
store.saveSettings({...store.settings(),enabled:true,channelId:'channel'},'admin');
|
|
const bytes=Buffer.from('%PDF-1.7\nisolated Hui fixture'),sha256=crypto.createHash('sha256').update(bytes).digest('hex');
|
|
function ingest(extra={}){const order=store.ingest({...sample,...extra},'system');store.recordArchive(order.id,{archivedAt:'2026-10-19T01:10:00Z',files:[{name:'O-100.pdf',path:'C:\\archive\\O-100.pdf',kind:'pdf',size:bytes.length,sha256}]},'executor');return store.get('orders',order.id);}
|
|
const order=ingest(),sent=[];let verifyFailure=false,sendFailure=false;
|
|
const mail={exclusive:async(id,work)=>work(),store:{channelSecret:()=>({id:'channel',version:1,email:'sender@example.test',name:'test',smtp:{host:'unused.invalid'}}),guard:()=>{}},smtpFactory:()=>({verify:async()=>{if(verifyFailure)throw Error('verify unavailable');},sendMail:async message=>{sent.push(message);if(sendFailure)throw Error('lost SMTP result');return {accepted:[...message.to,...message.cc],rejected:[]};},close:()=>{}})};
|
|
return {get store(){return store;},order,sample,rule,bytes,sent,ingest,huiTemplate,mail,clock,failVerify(v){verifyFailure=v;},failSend(v){sendFailure=v;},dispatcher(){return new OrderRuleDispatcher({store,mail,settings:()=>({schedule:{times:['11:00','17:00'],weekends:false}}),clock:()=>new Date(cutoff),providersReady:()=>true,attachmentReader:async()=>bytes});},reopen(){store.close();store=new RuleStore(dir,options);store.templateResolver=resolver;return store;},context(){return {orderRules:store,workspace:{recordSources:()=>[{id:'c1',owner:'admin'}]}};}};
|
|
}
|
|
function pair(f){const batches=f.store.prepare(cutoff,'admin');assert.equal(batches.length,2);return {normal:batches.find(b=>b.notificationMode==='normal'),hui:batches.find(b=>b.notificationMode==='huizhou')};}
|
|
|
|
test('mixed event freezes only Hui title details with identical recipients and one shared archive',t=>{
|
|
const f=fixture(t),{normal,hui}=pair(f);
|
|
assert.match(normal.text,/O-100/);assert.match(normal.text,/H-200/);
|
|
assert.deepEqual(hui.orderNos,['H-200']);assert.match(hui.subject,/H-200/);assert.doesNotMatch(hui.subject+hui.text+hui.html,/O-100|CORE-O/);
|
|
assert.match(hui.text,/CORE-H/);assert.match(hui.text,/https:\/\/example.test\/business/);assert.doesNotMatch(hui.text,/C:\\archive|存放地址/);
|
|
assert.deepEqual(hui.to,normal.to);assert.deepEqual(hui.cc,normal.cc);assert.deepEqual(hui.attachments,normal.attachments);
|
|
assert.deepEqual(f.store.prepare(cutoff,'admin'),[]);assert.equal(f.store.all('orders').length,1);assert.equal(f.store.all('batches').length,2);
|
|
});
|
|
test('business mode before a new segment binds forward, and explicit inline mode binds to its own order',()=>{
|
|
const rows=extractTitle(mixed).orders;assert.equal(rows[0].businessMode,undefined);assert.equal(rows[1].businessMode,'惠州数字');
|
|
assert.equal(extractTitle('业务模式:惠州订单号:H-1客户简称:惠州创维数字技术有限公司').orders[0].businessMode,'惠州');
|
|
assert.equal(extractTitle('订单号:H-1业务模式:惠州模式客户简称:惠州创维数字技术有限公司').orders[0].businessMode,'惠州模式');
|
|
});
|
|
test('a separated next-paragraph business mode cannot leak into the preceding ordinary order',()=>{
|
|
const rows=extractTitle('订单号:O-100客户简称:普通客户\n业务模式:惠州数字订单号:H-200客户简称:终端客户').orders;
|
|
assert.equal(rows[0].businessMode,undefined);assert.equal(rows[1].businessMode,'惠州数字');
|
|
});
|
|
test('conflicting business headers for the same segment remain visible Hui uncertainty',()=>{
|
|
const {selectHuizhou}=require('../../src/modules/order-rules/huizhou.cjs');
|
|
const selection=selectHuizhou({titleOrders:extractTitle('业务模式:普通业务模式:惠州订单号:H-200客户简称:惠州创维数字技术有限公司').orders});assert.equal(selection.orders.length,0);assert.equal(selection.issues.length,1);
|
|
});
|
|
for(const title of ['订单号:HA200客户简称:未知客户','订单号:H-200业务模式:普通客户简称:惠州创维数字技术有限公司'])test('uncertain evidence remains Hui-only and normal still freezes: '+title,t=>{
|
|
const f=fixture(t,{title}),batches=f.store.prepare(cutoff,'admin');assert.equal(batches.length,1);assert.equal(batches[0].notificationMode,'normal');
|
|
const detail=orderDetail(f.context(),f.order.id,admin);assert.equal(detail.notifications.huizhou.status,'blocked');assert.ok(detail.notifications.huizhou.issues.length);
|
|
});
|
|
test('trusted Hui business mode is sufficient with a general end-customer name',t=>{
|
|
const f=fixture(t,{title:'订单号:H-200业务模式:惠州模式客户简称:普通客户名称'}),{hui}=pair(f);assert.deepEqual(hui.orderNos,['H-200']);assert.match(hui.text,/普通客户名称/);
|
|
});
|
|
test('old ordinary frozen batch cannot acquire a companion from a later Hui-enabled snapshot',t=>{
|
|
const f=fixture(t),{normal,hui}=pair(f);f.store.db.prepare('DELETE FROM records WHERE kind=? AND id=?').run('batches',hui.id);
|
|
const legacy=f.store.get('batches',normal.id);delete legacy.notificationMode;delete legacy.huizhouPlanned;f.store.put('batches',legacy);
|
|
const order=f.store.get('orders',f.order.id);order.notifications.huizhou={status:'pending',batchId:null,error:null,orderNos:['H-200'],issues:[]};f.store.put('orders',order);
|
|
assert.deepEqual(f.store.prepare(cutoff,'admin'),[]);assert.equal(f.store.all('batches').length,1);
|
|
});
|
|
for(const opts of [{enabled:false},{title:'订单号:O-100客户简称:普通客户'},{title:'订单号:O-100客户简称:惠州某其他公司'}])test('disabled or empty recognized Hui set never creates an extra batch '+JSON.stringify(opts),t=>{
|
|
const f=fixture(t,opts),batches=f.store.prepare(cutoff,'admin');assert.equal(batches.length,1);assert.equal(batches[0].notificationMode,'normal');assert.equal(f.store.prepare(cutoff,'admin').length,0);
|
|
});
|
|
test('legacy order without delivery eligibility never gains a companion even after enabling rule',t=>{
|
|
const f=fixture(t),old=f.store.get('orders',f.order.id);delete old.notifications;delete old.ruleSnapshot.huizhouEnabled;delete old.ruleSnapshot.huizhouTemplateId;f.store.put('orders',old);
|
|
const batches=f.store.prepare(cutoff,'admin');assert.equal(batches.length,1);assert.equal(batches[0].notificationMode,'normal');
|
|
const frozen=f.store.get('batches',batches[0].id);delete frozen.notificationMode;f.store.put('batches',frozen);assert.equal(f.store.prepare(cutoff,'admin').length,0);
|
|
});
|
|
test('normal sent and Hui failed permit exactly one Hui resend without replaying normal',async t=>{
|
|
const f=fixture(t),{normal,hui}=pair(f),d=f.dispatcher();t.after(()=>d.stop());await d.dispatch(normal,f.store.settings());f.failVerify(true);await d.dispatch(hui,f.store.settings());
|
|
assert.equal(f.store.get('orders',f.order.id).status,'sent');assert.equal(f.store.get('batches',hui.id).status,'failed');f.failVerify(false);
|
|
const input={version:f.store.get('batches',hui.id).version,idempotencyKey:'hui-resend',note:'已确认失败并修复邮件连接'};
|
|
const retry=await d.resend(hui.id,input,admin);assert.equal(retry.status,'sent');assert.equal((await d.resend(hui.id,input,admin)).id,retry.id);assert.equal(f.sent.length,2);
|
|
assert.deepEqual(f.sent.map(m=>m.subject),[normal.subject,hui.subject]);assert.equal(orderDetail(f.context(),f.order.id,admin).notifications.huizhou.status,'sent');
|
|
});
|
|
test('normal unknown does not prevent Hui delivery or let Hui recovery alter normal',async t=>{
|
|
const f=fixture(t),{normal,hui}=pair(f),d=f.dispatcher();t.after(()=>d.stop());f.failSend(true);await d.dispatch(normal,f.store.settings());f.failSend(false);await d.dispatch(hui,f.store.settings());
|
|
assert.equal(f.store.get('batches',normal.id).status,'unknown');assert.equal(f.store.get('batches',hui.id).status,'sent');assert.equal(f.store.get('orders',f.order.id).status,'unknown');
|
|
await assert.rejects(()=>d.resend(normal.id,{version:f.store.get('batches',normal.id).version,idempotencyKey:'no-unknown',note:'不能未核验直接补发'},admin));
|
|
f.store.resolve(normal.id,{resolution:'sent',note:'服务器已确认全部接收'},'admin');assert.equal(orderDetail(f.context(),f.order.id,admin).notifications.huizhou.status,'sent');
|
|
});
|
|
test('restart marks only sending Hui unknown and manual resolution reserves only Hui',t=>{
|
|
const f=fixture(t),{normal,hui}=pair(f);f.store.beginSending(normal.id);f.store.finishSending(normal.id,'sent');f.store.beginSending(hui.id);f.reopen();
|
|
assert.equal(f.store.get('orders',f.order.id).status,'sent');assert.equal(f.store.get('batches',hui.id).status,'unknown');assert.equal(orderDetail(f.context(),f.order.id,admin).notifications.huizhou.status,'unknown');
|
|
f.store.resolve(hui.id,{resolution:'retry',note:'已核验服务器未接收惠州通知'},'admin');assert.equal(f.store.get('orders',f.order.id).status,'sent');assert.equal(orderDetail(f.context(),f.order.id,admin).notifications.huizhou.status,'pending');
|
|
});
|
|
test('missing or wrong-mode Hui template blocks Hui without discarding ordinary batch',t=>{
|
|
for(const template of [{notificationMode:'normal'},null]){
|
|
const f=fixture(t,{template:template||{}});if(template===null)f.store.templateResolver=()=>null;
|
|
const batches=f.store.prepare(cutoff,'admin');assert.equal(batches.length,1);assert.equal(batches[0].notificationMode,'normal');assert.match(orderDetail(f.context(),f.order.id,admin).notifications.huizhou.error,/模板/);
|
|
}
|
|
});
|
|
test('authorized previews expose both modes and preserve mandatory Hui details when template omits variables',t=>{
|
|
const f=fixture(t,{template:{text:'访问 https://example.test/business',html:'<p>访问 https://example.test/business</p>'}}),preview=previewEffects(f.store.get('orders',f.order.id).ruleSnapshot,f.order.event,f.store);
|
|
assert.match(preview.mail.text,/O-100/);assert.deepEqual(preview.notifications.huizhou.orderNos,['H-200']);assert.match(preview.notifications.huizhou.mail.text,/CORE-H/);assert.doesNotMatch(preview.notifications.huizhou.mail.text,/O-100|存放地址/);
|
|
const {hui}=pair(f);assert.equal(batchDetail(f.context(),hui.id,admin).notificationMode,'huizhou');assert.throws(()=>orderDetail(f.context(),f.order.id,{role:'operator',username:'outsider'}),/无权|不存在/);
|
|
assert.equal(JSON.stringify(orderDetail(f.context(),f.order.id,admin)).includes('rawTitle'),false);
|
|
});
|
|
test('summary counts Hui-only blockers once after the ordinary notification has been sent',t=>{
|
|
const f=fixture(t);f.store.templateResolver=()=>null;const normal=f.store.prepare(cutoff,'admin')[0];f.store.beginSending(normal.id);f.store.finishSending(normal.id,'sent');
|
|
const result=summary(f.context(),admin);assert.equal(result.counts.blocked,1);assert.equal(result.issues.some(i=>i.notificationMode==='huizhou'),true);
|
|
});
|
|
for(const ordinaryStatus of ['sent','unknown'])for(const observed of [true,false])test(`archived runtime checks continue with ordinary ${ordinaryStatus} and Hui reserved; todo observed=${observed}`,async t=>{
|
|
const f=fixture(t),{normal,hui}=pair(f);f.store.beginSending(normal.id);f.store.finishSending(normal.id,ordinaryStatus);
|
|
const {OrderExecutionCoordinator}=require('../../src/modules/order-execution/coordinator.cjs');
|
|
const connection={id:'c1',owner:'admin',status:'connected'},row={...f.sample};delete row.fields;delete row.brief;
|
|
const taskId=crypto.createHash('sha256').update(JSON.stringify(['c1','todo',String(row.instanceId),String(row.taskId),String(row.revision)])).digest('hex');
|
|
f.store.put('execution-tasks',{id:taskId,version:1,connectionId:'c1',owner:'admin',orderId:f.order.id,row,categoryIds:['bs-change'],status:ordinaryStatus,step:'complete'});
|
|
let corrupt=false,reads=0;
|
|
const provider={scan:async()=>observed?[row]:[],capabilities:()=>({liveTodo:true,pdfExport:true}),capture:async()=>{throw Error('must not capture archived event again');}};
|
|
const archive={capabilities:()=>({automaticArchive:true,pdfExport:true}),probe:async()=>({automaticArchive:true,pdfExport:true}),read:async()=>{reads++;return corrupt?Buffer.from('bad'):f.bytes;},archive:async()=>{throw Error('must not export archived event again');}};
|
|
const execution=new OrderExecutionCoordinator({store:f.store,workspace:{getConnection:()=>connection,snapshot:()=>({connections:[connection]})},provider,archive,clock:()=>new Date(cutoff)});t.after(()=>execution.stop());
|
|
await execution.scan({connectionId:'c1',idempotencyKey:'healthy'}, {user:admin,sessionId:'fixture-session'});assert.equal(reads,1);assert.equal(f.store.get('execution-tasks',taskId).runtimeCheck.status,'ready');assert.equal(f.store.beginSending(hui.id).status,'sending');
|
|
corrupt=true;await execution.scan({connectionId:'c1',idempotencyKey:'tampered'}, {user:admin,sessionId:'fixture-session'});assert.equal(reads,2);assert.equal(f.store.get('execution-tasks',taskId).runtimeCheck.status,'blocked');
|
|
assert.throws(()=>f.store.beginSending(hui.id),/完整|复核/);assert.equal(f.store.get('orders',f.order.id).status,ordinaryStatus);
|
|
});
|
|
test('normal failure cannot auto-refreeze while Hui remains independent and cutoff groups stay separate',t=>{
|
|
const f=fixture(t),{normal,hui}=pair(f);f.store.finishSending(normal.id,'failed','normal verify failed');f.store.beginSending(hui.id);f.store.finishSending(hui.id,'sent');assert.deepEqual(f.store.prepare(cutoff,'admin'),[]);
|
|
const later=f.ingest({taskId:'later',instanceId:'later',receivedAt:'2026-10-19T04:00:00Z'}),batches=f.store.prepare('2026-10-19T09:00:00.000Z','admin');assert.equal(batches.length,2);assert.ok(batches.every(b=>b.orderIds.length===1&&b.orderIds[0]===later.id));
|
|
assert.equal(f.store.get('batches',normal.id).status,'failed');assert.equal(f.store.get('batches',hui.id).status,'sent');
|
|
});
|
|
test('repaired Hui preparation ignores normal SMTP unknown on a completed task but preserves source uncertainty gates',t=>{
|
|
const f=fixture(t);f.store.templateResolver=()=>null;const normal=f.store.prepare(cutoff,'admin')[0];f.store.beginSending(normal.id);f.store.finishSending(normal.id,'unknown');
|
|
const task={id:'complete-task',orderId:f.order.id,categoryIds:['bs-change'],row:{receivedAt:f.order.event.receivedAt},step:'archive',status:'unknown',runtimeCheck:{status:'ready'}};f.store.put('execution-tasks',task);
|
|
f.store.templateResolver=(category,rule,mode)=>mode==='huizhou'?f.huiTemplate:null;
|
|
assert.deepEqual(f.store.prepare(cutoff,'admin'),[]);
|
|
task.step='complete';task.conflict=true;f.store.put('execution-tasks',task);assert.deepEqual(f.store.prepare(cutoff,'admin'),[]);
|
|
task.conflict=false;f.store.put('execution-tasks',task);const batches=f.store.prepare(cutoff,'admin');assert.equal(batches.length,1);assert.equal(batches[0].notificationMode,'huizhou');assert.equal(f.store.beginSending(batches[0].id).status,'sending');assert.equal(f.store.get('orders',f.order.id).status,'unknown');
|
|
});
|
|
test('manual Hui resend cannot bypass a new source conflict on the shared archive task',async t=>{
|
|
const f=fixture(t),{normal,hui}=pair(f),d=f.dispatcher();t.after(()=>d.stop());f.store.beginSending(normal.id);f.store.finishSending(normal.id,'sent');f.store.finishSending(hui.id,'failed');
|
|
f.store.put('execution-tasks',{id:'conflict-task',orderId:f.order.id,categoryIds:['bs-change'],row:{receivedAt:f.order.event.receivedAt},step:'complete',status:'sent',conflict:true,runtimeCheck:{status:'ready'}});
|
|
const result=await d.resend(hui.id,{version:f.store.get('batches',hui.id).version,idempotencyKey:'conflict-resend',note:'核验发送失败但来源仍存在冲突'},admin);
|
|
assert.equal(result.status,'failed');assert.equal(f.sent.length,0);assert.equal(f.store.get('orders',f.order.id).status,'sent');
|
|
});
|