201 lines
15 KiB
JavaScript
201 lines
15 KiB
JavaScript
'use strict';
|
|
const test=require('node:test');
|
|
const assert=require('node:assert/strict');
|
|
const fs=require('node:fs');const os=require('node:os');const path=require('node:path');const crypto=require('node:crypto');
|
|
const {transition}=require('../../src/modules/order-rules/state.cjs');
|
|
const {buildBatch}=require('../../src/modules/order-rules/batch.cjs');
|
|
|
|
const cutoff='2026-10-19T01:00:00.000Z';
|
|
function rule(patch={}){return {id:'r1',version:1,categoryId:'notice',name:'订单通知',subjectPrefix:'订单通知',intro:'请处理以下订单。',signature:'业务部',to:['USER@example.com','user@example.com'],cc:['copy@example.com','USER@example.com'],attachPdf:true,archiveDirectory:'\\\\nas\\orders',...patch};}
|
|
function order(id='1',patch={}){return {id,event:{orderNo:`SO-${id}`,brief:'型号 <script>alert(1)</script>',receivedAt:'2026-10-19T00:00:00.000Z'},ruleSnapshot:rule(),archive:{archivedAt:'2026-10-19T00:30:00.000Z',files:[{name:`SO-${id}.pdf`,path:`\\\\nas\\orders\\SO-${id}.pdf`,sha256:'a'.repeat(64),size:100,kind:'pdf'}]},...patch};}
|
|
|
|
test('state actions enforce archive, pending and batch progression without skipping evidence stages',()=>{
|
|
assert.equal(transition('order','identified','prepare'),'preparing');
|
|
assert.equal(transition('order','preparing','archive'),'archived');
|
|
assert.equal(transition('order','archived','queue'),'pending');
|
|
assert.equal(transition('order','pending','batch'),'batched');
|
|
assert.equal(transition('order','batched','sent'),'sent');
|
|
assert.throws(()=>transition('order','identified','sent'),{status:409});
|
|
assert.throws(()=>transition('order','blocked','sent'),{status:409});
|
|
assert.throws(()=>transition('batch','failed','send'),{status:409});
|
|
assert.throws(()=>transition('batch','unknown','send'),{status:409});
|
|
assert.equal(transition('batch','prepared','send'),'sending');
|
|
assert.equal(transition('batch','sending','unknown'),'unknown');
|
|
assert.equal(transition('batch','unknown','resolve_sent'),'sent');
|
|
assert.equal(transition('batch','unknown','retry'),'cancelled');
|
|
});
|
|
|
|
test('batch includes every order above 200 with subject numbers and normalized independent recipients',()=>{
|
|
const orders=Array.from({length:205},(_,i)=>order(String(i+1)));
|
|
const batch=buildBatch(rule(),orders,cutoff);
|
|
assert.equal(batch.orderIds.length,205);
|
|
assert.equal(batch.attachments.length,205);
|
|
assert.match(batch.subject,/SO-1/);assert.match(batch.subject,/SO-205/);
|
|
assert.deepEqual(batch.to,['user@example.com']);assert.deepEqual(batch.cc,['copy@example.com']);
|
|
assert.equal(batch.cutoff,cutoff);
|
|
orders[0].archive.files[0].name='mutated';orders[0].event.orderNo='mutated';
|
|
assert.equal(batch.attachments[0].name,'SO-1.pdf');assert.equal(batch.orderNos[0],'SO-1');
|
|
});
|
|
|
|
test('mail keeps intro signature and escaped summaries with blue clickable UNC evidence',()=>{
|
|
const batch=buildBatch(rule({intro:'<团队>',signature:'研发 & 业务'}),[order()],cutoff);
|
|
assert.match(batch.text,/<团队>/);assert.match(batch.text,/研发 & 业务/);
|
|
assert.match(batch.html,/<script>/);assert.doesNotMatch(batch.html,/<script>/);
|
|
assert.match(batch.html,/href="file:\/\/nas\/orders\/SO-1.pdf"/);
|
|
assert.match(batch.html,/color:\s*#(?:00f|0000ff)/i);
|
|
assert.match(batch.html,/<团队>/);
|
|
});
|
|
|
|
test('missing required PDF or archive evidence blocks the entire category',()=>{
|
|
assert.throws(()=>buildBatch(rule(),[order(),order('2',{archive:null})],cutoff),/归档/);
|
|
const onlyNotice=order('2');onlyNotice.archive.files[0].kind='notice';
|
|
assert.throws(()=>buildBatch(rule(),[order(),onlyNotice],cutoff),/PDF/);
|
|
const badEvidence=order('2');delete badEvidence.archive.files[0].sha256;
|
|
assert.throws(()=>buildBatch(rule(),[badEvidence],cutoff),/证据/);
|
|
});
|
|
|
|
test('mixed categories, rule versions, duplicate IDs and after-cutoff items are rejected instead of omitted',()=>{
|
|
const other=order('2');other.ruleSnapshot.categoryId='change';
|
|
assert.throws(()=>buildBatch(rule(),[order(),other],cutoff),/类别/);
|
|
const revised=order('2');revised.ruleSnapshot.version=2;
|
|
assert.throws(()=>buildBatch(rule(),[order(),revised],cutoff),/版本/);
|
|
assert.throws(()=>buildBatch(rule(),[order(),order()],cutoff),/重复/);
|
|
const later=order('2');later.event.receivedAt='2026-10-19T02:00:00.000Z';
|
|
assert.throws(()=>buildBatch(rule(),[later],cutoff),/截止/);
|
|
});
|
|
|
|
test('strict recipient parsing rejects header injections and malformed lists',()=>{
|
|
for(const address of ['a@example.com\r\nBcc: intruder@example.com','Name <a@example.com>','a@@example.com','a@example.com,other@example.com','a@localhost','a..b@example.com']){
|
|
assert.throws(()=>buildBatch(rule({to:[address]}),[order()],cutoff),/邮箱|收件/);
|
|
}
|
|
assert.throws(()=>buildBatch(rule({to:[]}),[order()],cutoff),/收件/);
|
|
});
|
|
|
|
test('message size estimate includes base64 overhead and rejects oversize rather than truncating',()=>{
|
|
const large=order();large.archive.files[0].size=15000;
|
|
assert.throws(()=>buildBatch(rule(),[large],cutoff,{maxMessageBytes:20000}),/大小|容量/);
|
|
});
|
|
|
|
test('an explicit batch window rejects historical orders and excludes its upper boundary',()=>{
|
|
const window={start:'2026-10-19T00:00:00.000Z',end:cutoff,startInclusive:true,endInclusive:false};
|
|
const old=order('old');old.event.receivedAt='2026-10-18T23:59:59.999Z';
|
|
assert.throws(()=>buildBatch(rule(),[old,order()],cutoff,{window}),/时段|窗口/);
|
|
const boundary=order('boundary');boundary.event.receivedAt=cutoff;
|
|
assert.throws(()=>buildBatch(rule(),[boundary],cutoff,{window}),/时段|窗口/);
|
|
const batch=buildBatch(rule(),[order(),order('2')],cutoff,{window});
|
|
assert.deepEqual(batch.orderIds,['1','2']);assert.equal(batch.window.start,'2026-10-19T00:00:00.000Z');assert.equal(batch.window.end,cutoff);
|
|
});
|
|
|
|
test('batch refuses inverted windows and windows that do not end at its cutoff',()=>{
|
|
for(const window of [{start:cutoff,end:'2026-10-19T00:00:00.000Z'},{start:'2026-10-18T00:00:00.000Z',end:'2026-10-19T02:00:00.000Z'}]){
|
|
assert.throws(()=>buildBatch(rule(),[order()],cutoff,{window}),/时段|窗口/);
|
|
}
|
|
});
|
|
|
|
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};
|
|
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);
|
|
const batch={id:'batch1',status:'prepared',categoryId:'notice',subject:'已冻结 SO-1',text:'原正文',html:'<p>原正文</p>',to:['user@example.com'],cc:['copy@example.com'],attachments:[{name:'order.pdf',path:file,size:content.length,sha256:crypto.createHash('sha256').update(content).digest('hex'),kind:'pdf'}],cutoff:dispatchCutoff,window:structuredClone(dispatchWindow)};
|
|
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={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 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');
|
|
const dispatcher=new OrderRuleDispatcher({store,mail,settings:()=>({schedule}),calendar:()=>[],clock:()=>now,providersReady:()=>ready});
|
|
return {dispatcher,store,mail,record,batch,config,caps,file,setNow:value=>{now=new Date(value);}};
|
|
}
|
|
async function due(f){await f.dispatcher.tick();f.setNow(dispatchCutoff);await f.dispatcher.tick();}
|
|
|
|
test('dispatcher never prepares or touches SMTP while disabled or any provider is unverified',async t=>{
|
|
for(const input of [{enabled:false},{ready:false},{capabilities:false}]){
|
|
const f=dispatchFixture(t,input);await due(f);assert.equal(f.record.prepared,0);assert.equal(f.record.smtp,0);assert.equal(f.record.sent.length,0);await f.dispatcher.stop();
|
|
}
|
|
});
|
|
|
|
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);
|
|
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();
|
|
});
|
|
|
|
test('dispatcher attachment tampering fails before SMTP or sending transition',async t=>{
|
|
const f=dispatchFixture(t);fs.writeFileSync(f.file,'changed bytes');await due(f);
|
|
assert.equal(f.record.status,'failed');assert.equal(f.record.begun,0);assert.equal(f.record.smtp,0);assert.equal(f.record.sent.length,0);await f.dispatcher.stop();
|
|
});
|
|
|
|
test('dispatcher maps pre-send verify failure to failed and post-begin errors or partial acceptance to unknown',async t=>{
|
|
for(const [input,wanted,begun] of [[{verify:()=>{throw Error('verify failure');}},'failed',0],[{send:()=>{throw Error('socket dropped');}},'unknown',1],[{result:{accepted:['user@example.com'],rejected:['copy@example.com']}},'unknown',1]]){
|
|
const f=dispatchFixture(t,input);await due(f);assert.equal(f.record.status,wanted);assert.equal(f.record.begun,begun);await f.dispatcher.stop();
|
|
}
|
|
});
|
|
|
|
test('dispatcher rechecks pause and provider gates after SMTP verification',async t=>{
|
|
for(const change of [({config})=>{config.enabled=false;},({caps})=>{caps.pdfExport=false;}]){
|
|
const f=dispatchFixture(t,{verify:change});await due(f);assert.equal(f.record.begun,0);assert.equal(f.record.sent.length,0);await f.dispatcher.stop();
|
|
}
|
|
});
|
|
|
|
test('dispatcher uses business calendar to skip paused days and stop prevents further sends',async t=>{
|
|
const f=dispatchFixture(t);f.dispatcher.calendar=()=>[{date:'2026-10-20',kind:'pause'}];await due(f);assert.equal(f.record.prepared,0);
|
|
await f.dispatcher.stop();f.dispatcher.calendar=()=>[];await f.dispatcher.tick();assert.equal(f.record.sent.length,0);
|
|
});
|
|
|
|
test('dispatcher acquires mailbox before preparing and retries the same slot when busy',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);assert.equal(f.record.prepared,0);assert.equal(f.record.sent.length,0);
|
|
busy=false;await f.dispatcher.tick();assert.equal(f.record.prepared,1);assert.equal(f.record.status,'sent');await f.dispatcher.stop();
|
|
});
|
|
|
|
test('dispatcher recovers a manually prepared batch even when no new orders can be prepared',async t=>{
|
|
const f=dispatchFixture(t);f.store.prepare=()=>[];
|
|
await due(f);assert.equal(f.record.sent.length,1);assert.equal(f.record.status,'sent');await f.dispatcher.stop();
|
|
});
|
|
|
|
test('dispatcher refuses a prepared snapshot frozen to a different mailbox before SMTP',async t=>{
|
|
const f=dispatchFixture(t);f.batch.channelId='old-channel';
|
|
await due(f);assert.equal(f.record.status,'failed');assert.equal(f.record.smtp,0);assert.equal(f.record.begun,0);assert.equal(f.record.sent.length,0);assert.match(f.record.messages[0],/邮箱|渠道/);await f.dispatcher.stop();
|
|
});
|
|
|
|
test('dispatcher never carries a prepared morning batch into the afternoon slot after a pause',async t=>{
|
|
const f=dispatchFixture(t);let prepareCount=0;
|
|
f.store.prepare=()=>{prepareCount++;if(prepareCount===1){f.config.enabled=false;return [f.batch];}return [];};
|
|
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();
|
|
});
|
|
|
|
test('dispatcher ignores old, future and mismatched-window prepared batches at the current slot',async t=>{
|
|
for(const mutate of [b=>{b.cutoff='2026-10-19T09:00:00.000Z';},b=>{b.cutoff='2026-10-20T09:00:00.000Z';},b=>{b.window.start='2026-10-18T16:00:00.000Z';},b=>{delete b.window;}]){
|
|
const f=dispatchFixture(t);mutate(f.batch);f.store.prepare=()=>[];await due(f);assert.equal(f.record.sent.length,0);assert.equal(f.record.smtp,0);await f.dispatcher.stop();
|
|
}
|
|
});
|
|
|
|
test('dispatcher resumes a paused prepared batch only within the same slot grace',async t=>{
|
|
const f=dispatchFixture(t);let preparation=0;
|
|
f.store.prepare=()=>{preparation++;if(preparation===1){f.config.enabled=false;return [f.batch];}return [];};
|
|
await due(f);assert.equal(f.record.sent.length,0);f.setNow('2026-10-20T01:00:15.000Z');await f.dispatcher.tick();
|
|
f.config.enabled=true;f.setNow('2026-10-20T01:00:30.000Z');await f.dispatcher.tick();
|
|
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=>{
|
|
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();
|
|
});
|
|
|
|
test('dispatcher rechecks slot expiration after asynchronous SMTP verification',async t=>{
|
|
const f=dispatchFixture(t,{verify:()=>f.setNow('2026-10-20T01:01: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();
|
|
});
|