feat: integrate native BPM task processing and strict Excel test rules
This commit is contained in:
commit
8cb6a32876
444 files changed
+17045
-3182
No files matched your search
@@ -0,0 +1,20 @@
|
||||
'use strict';
|
||||
const test=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs'),path=require('node:path'),os=require('node:os');
|
||||
const {RuleStore}=require('../../src/modules/order-rules/store.cjs');
|
||||
const {MailStore}=require('../../src/modules/mail/store.cjs');
|
||||
test('an outer configuration migration rolls back all nested supported updates and can commit a complete retry',t=>{
|
||||
const directory=fs.mkdtempSync(path.join(os.tmpdir(),'atomic-rule-migration-')),store=new RuleStore(directory);t.after(()=>{store.close();fs.rmSync(directory,{recursive:true,force:true});});
|
||||
const rule=store.get('rules','bs-change').draft,settings=store.settings();
|
||||
const change=()=>{store.saveRule({...store.get('rules','bs-change').draft,subjectPrefix:'隔离迁移主题',attachPdf:false},'admin');store.saveSettings({...store.settings(),maxMessageBytes:1048576},'admin');};
|
||||
assert.throws(()=>store.transaction(()=>{change();throw Error('fixture-migration-rollback');}),/fixture-migration-rollback/);
|
||||
assert.deepEqual(store.get('rules','bs-change').draft,rule);assert.deepEqual(store.settings(),settings);
|
||||
store.transaction(change);assert.equal(store.get('rules','bs-change').draft.subjectPrefix,'隔离迁移主题');assert.equal(store.settings().maxMessageBytes,1048576);
|
||||
});
|
||||
|
||||
test('nested mailbox template preparation can roll back every new object without sending',t=>{
|
||||
const directory=fs.mkdtempSync(path.join(os.tmpdir(),'atomic-mail-migration-')),store=new MailStore(directory);t.after(()=>{store.close();fs.rmSync(directory,{recursive:true,force:true});});
|
||||
const work=()=>{const c=store.saveChannel({name:'隔离邮箱',email:'sender@example.test',enabled:false,senders:['source@example.test'],smtp:{host:'smtp.example.test',port:465,security:'tls',user:'fixture',password:'fixture'},imap:{host:'imap.example.test',port:993,security:'tls',user:'fixture',password:'fixture'}});const draft=store.ingest(c.id,'fixture',1,{subject:'隔离 {{订单号}}',scope:'fixture-scope',text:'{{订单列表}}',html:'',attachments:[],notes:[],sender:'source@example.test'},Buffer.from('fixture-template'),c.version);store.confirm(draft.id,{version:draft.version,subject:draft.subject,scope:draft.scope,useText:false},'admin');};
|
||||
assert.throws(()=>store.transaction(()=>{work();throw Error('fixture-template-rollback');}),/fixture-template-rollback/);
|
||||
assert.equal(store.channels().length,0);assert.equal(store.templates().length,0);assert.equal(store.receipts().length,0);
|
||||
store.transaction(work);assert.equal(store.templates()[0].status,'active');assert.equal(store.sends().length,0);
|
||||
});
|
||||
@@ -0,0 +1,200 @@
|
||||
'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:false,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.deepEqual(batch.attachments,[]);
|
||||
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.orderNos[0],'SO-1');assert.match(batch.text,/订单号: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\/?"/);
|
||||
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 rejects oversize order content rather than truncating',()=>{
|
||||
const large=order();large.event.brief='型号'.repeat(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-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);
|
||||
const batch={id:'batch1',status:'prepared',categoryId:'notice',subject:'已冻结 SO-1',text:'原正文',html:'<p>原正文</p>',to:['2639266652@qq.com'],cc:[],attachments:[],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={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:['2639266652@qq.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 sends the frozen recipients and attachment-free 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,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,['2639266652@qq.com']);assert.deepEqual(sent.cc,[]);
|
||||
assert.deepEqual(sent.attachments,[]);assert.equal(sent.disableFileAccess,true);assert.equal(sent.disableUrlAccess,true);
|
||||
await f.dispatcher.stop();
|
||||
});
|
||||
|
||||
test('dispatcher blocks legacy frozen attachments before SMTP or sending transition',async t=>{
|
||||
const f=dispatchFixture(t);f.batch.attachments=[{name:'old.pdf',path:f.file,size:1,sha256:'a'.repeat(64),kind:'pdf'}];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:[],rejected:['2639266652@qq.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,'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=>{
|
||||
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 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,1);await f.dispatcher.stop();
|
||||
});
|
||||
|
||||
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();
|
||||
});
|
||||
@@ -0,0 +1,33 @@
|
||||
'use strict';
|
||||
const test=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs/promises'),os=require('node:os'),path=require('node:path');
|
||||
const {activateReferenceMapping}=require('../fixtures/activate-field-mapping.cjs');
|
||||
const {startTestDashboard,login}=require('../fixtures/dashboard-runtime.cjs'),{loadPlaywright,browserOptions}=require('../../src/platform/browser.cjs');
|
||||
async function setup(t){const dir=await fs.mkdtemp(path.join(os.tmpdir(),'business-config-ui-')),runtime=await startTestDashboard({stateDir:dir,mailHistory:true}),browser=await loadPlaywright().chromium.launch(browserOptions());t.after(async()=>{await browser.close();await runtime.close();await fs.rm(dir,{recursive:true,force:true});});const page=await browser.newPage({viewport:{width:1440,height:1000}});page.setDefaultTimeout(6000);return {runtime,page};}
|
||||
test('business editor selects configured template and server folder, preserves draft on browse failures and guards switching', {timeout:60000},async t=>{
|
||||
const {page,runtime}=await setup(t),mail=runtime.mail.store;
|
||||
const config={name:'测试邮箱',email:'orders@example.test',senders:['author@example.test'],enabled:false,smtp:{host:'smtp.example.test',port:465,security:'tls',user:'orders',password:'Test-only-password'},imap:{host:'imap.example.test',port:993,security:'tls',user:'orders',password:'Test-only-password'}},channel=mail.saveChannel(config);
|
||||
const raw=Buffer.from('From: author@example.test\r\nTo: orders@example.test\r\nSubject: [模板]Configured notice\r\nContent-Type: text/plain; charset=utf-8\r\n\r\nConfigured body {{订单列表}}');
|
||||
const parsed=await require('../../src/modules/mail/parser.cjs').parseTemplate(raw,config),draft=mail.ingest(channel.id,'1',1,parsed,raw,channel.version),template=mail.confirm(draft.id,{version:1,subject:parsed.subject,scope:parsed.scope,useText:false,text:parsed.text},'admin');
|
||||
activateReferenceMapping(runtime.orderRules);runtime.orderRules.templateResolver=(categoryId,rule)=>require('../../src/modules/mail/rule-template.cjs').ruleTemplate(mail,categoryId,rule);await page.route('**/api/order-rules/fields',r=>r.fulfill({json:runtime.orderRules.fields()}));
|
||||
let browseFails=true;await page.route('**/api/storage',r=>r.fulfill({json:{servers:[{id:'fixture-server',name:'测试存储',host:'fixture',share:'orders',directory:'archive',enabled:true,state:{readable:true,writable:true}}]}}));
|
||||
await page.route('**/api/storage/servers/fixture-server/files?**',route=>browseFails?route.fulfill({status:503,json:{error:'临时断线'}}):route.fulfill({json:{path:new URL(route.request().url()).searchParams.get('path')||'',entries:new URL(route.request().url()).searchParams.get('path')?[]:[{name:'分类文件夹',type:'directory'}],truncated:false}}));
|
||||
await page.goto('http://127.0.0.1:'+runtime.server.address().port+'/#order-rules');await login(page);await page.locator('[data-rule-id="bs-change"]').click();
|
||||
assert.equal(await page.locator('.rule-validation-column').count(),0);assert.equal(await page.locator('[data-adapter-choice]').count(),0);assert.equal(await page.locator('#order-rule-advanced').count(),0);
|
||||
await page.getByLabel('邮件模板',{exact:true}).selectOption(template.id);await page.getByLabel('存储服务器',{exact:true}).selectOption('fixture-server');await page.getByLabel('服务器内文件夹',{exact:true}).fill('changes');
|
||||
await page.getByRole('button',{name:'浏览',exact:true}).click();await page.getByText(/文件夹读取失败:临时断线/).waitFor();assert.equal(await page.getByLabel('邮件模板',{exact:true}).inputValue(),template.id);assert.equal(await page.getByLabel('服务器内文件夹',{exact:true}).inputValue(),'changes');
|
||||
browseFails=false;await page.getByLabel('服务器内文件夹',{exact:true}).fill('');await page.getByRole('button',{name:'浏览',exact:true}).click();await page.getByRole('button',{name:'▱ 分类文件夹',exact:true}).click();await page.getByRole('button',{name:'使用此文件夹',exact:true}).click();
|
||||
await page.getByLabel('文件名日期依据',{exact:true}).selectOption('receivedAt');await page.getByLabel('收件人',{exact:true}).fill('orders@example.test');await page.getByRole('button',{name:'保存草稿',exact:true}).click();await page.getByText('规则草稿已保存。',{exact:true}).waitFor();const saved=runtime.orderRules.get('rules','bs-change').draft;assert.equal(saved.bodyTemplateId,template.id);assert.equal(saved.archiveDirectory,'\\\\fixture\\orders\\archive\\分类文件夹');
|
||||
await page.getByRole('button',{name:'检查识别结果',exact:true}).click();await page.locator('#order-rule-preview-result').getByText('已保存规则通过真实订单检查,可以继续核对并发布。',{exact:true}).waitFor();await page.getByRole('button',{name:'检查识别结果',exact:true}).waitFor();assert.match(await page.locator('#order-rule-preview-result').textContent(),/Configured body/);
|
||||
await page.getByLabel('规则名称',{exact:true}).fill('尚未保存的分类');await page.locator('[data-rule-id="bs-notice"]').click();await page.getByRole('button',{name:'留在此页',exact:true}).click();assert.equal(await page.getByLabel('规则名称',{exact:true}).inputValue(),'尚未保存的分类');
|
||||
await page.locator('[data-rule-toggle="bs-change"]').click();await page.getByRole('button',{name:'放弃并继续',exact:true}).click();await page.getByText(/此分类尚未发布。/).waitFor();assert.equal(runtime.orderRules.get('rules','bs-change').published,null);assert.equal(runtime.orderRules.settings().enabled,false);await page.locator('[data-rule-id="bs-notice"]').click();assert.equal(await page.getByRole('dialog',{name:'未保存的修改'}).count(),0);
|
||||
await page.setViewportSize({width:390,height:844});assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true);
|
||||
});
|
||||
test('Excel import reads xls in a worker, previews rows, commits once, downloads xlsx and displays invalid rows', {timeout:60000},async t=>{
|
||||
const {page,runtime}=await setup(t),XLSX=require('xlsx'),sheet=XLSX.utils.aoa_to_sheet([['类别编号','分类名称','订单评审流程','电子流状态','服务器存档地址','邮件命名','收件人','附带PDF'],['bs-change','备损订单更改通知书','备损订单更改评审','订单专员(订单通知书)','备损订单','【备损订单更改通知书】','orders@example.test','是']]),book=XLSX.utils.book_new();XLSX.utils.book_append_sheet(book,sheet,'分类规则');
|
||||
await page.goto('http://127.0.0.1:'+runtime.server.address().port+'/#order-rules');await login(page);await page.getByRole('button',{name:'导入 Excel',exact:true}).click();
|
||||
const before=runtime.orderRules.get('rules','bs-change').draft.version;
|
||||
await page.locator('#rule-import-file').setInputFiles({name:'分类.xls',mimeType:'application/vnd.ms-excel',buffer:XLSX.write(book,{type:'buffer',bookType:'biff8'})});await page.getByRole('button',{name:'确认导入 1 类草稿',exact:true}).waitFor();assert.equal(runtime.orderRules.get('rules','bs-change').draft.version,before);
|
||||
await page.getByRole('button',{name:'确认导入 1 类草稿',exact:true}).click();await page.getByText('Excel 草稿已导入,启停状态未改变。',{exact:true}).waitFor();assert.equal(runtime.orderRules.get('rules','bs-change').draft.version,before+1);assert.equal(runtime.orderRules.get('rules','bs-change').published,null);assert.equal(runtime.orderRules.settings().enabled,false);
|
||||
const download=await Promise.all([page.waitForEvent('download',{timeout:20000}),page.getByRole('link',{name:'下载当前规则 Excel',exact:true}).click({noWaitAfter:true})]);assert.equal(download[0].suggestedFilename(),'分类规则.xlsx');assert.equal(await download[0].failure(),null);const exported=XLSX.read(await fs.readFile(await download[0].path()),{type:'buffer'});assert.equal(XLSX.utils.sheet_to_json(exported.Sheets['分类规则']).length,15);
|
||||
sheet.G2={t:'s',v:'invalid-address'};await page.locator('#rule-import-file').setInputFiles({name:'无效分类.xlsx',mimeType:'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',buffer:XLSX.write(book,{type:'buffer',bookType:'xlsx'})});await page.getByText('收件人未识别到有效邮箱',{exact:true}).waitFor();assert.equal(await page.getByRole('button',{name:'确认导入 1 类草稿',exact:true}).isDisabled(),true);assert.equal(runtime.orderRules.get('rules','bs-change').draft.version,before+1);
|
||||
});
|
||||
@@ -0,0 +1,40 @@
|
||||
'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 {activateReferenceMapping}=require('../fixtures/activate-field-mapping.cjs');
|
||||
const {RuleStore}=require('../../src/modules/order-rules/store.cjs');
|
||||
function setup(t){const dir=fs.mkdtempSync(path.join(os.tmpdir(),'rule-business-')),store=new RuleStore(dir);t.after(()=>{store.close();fs.rmSync(dir,{recursive:true,force:true});});return store;}
|
||||
const table=()=>({rows:[['类别编号','分类名称','订单评审流程','电子流状态','服务器存档地址','邮件命名','收件人','抄送人','附带PDF'],['bs-change','备损订单更改通知书','备损订单更改评审','订单专员(订单通知书)','备损订单通知书','【备损订单更改通知书】','A@example.test','','是']]});
|
||||
test('Excel preview is read-only for business state; import commits drafts atomically and is idempotent',t=>{
|
||||
const store=setup(t),{previewImport,commitImport}=require('../../src/modules/order-rules/import.cjs'),before=store.all('rules');
|
||||
const preview=previewImport(store,table(),'admin');assert.equal(preview.rows.length,1);assert.deepEqual(store.all('rules'),before);
|
||||
const saved=commitImport(store,{id:preview.id},'admin');assert.equal(saved.count,1);assert.deepEqual(store.get('rules','bs-change').draft.to,['a@example.test']);assert.equal(store.get('rules','bs-change').published,null);assert.equal(store.settings().enabled,false);
|
||||
assert.deepEqual(commitImport(store,{id:preview.id},'admin'),saved);
|
||||
});
|
||||
test('Excel reports unknown and duplicate categories, invalid addresses and stale versions without partial writes',t=>{
|
||||
const store=setup(t),{previewImport,commitImport}=require('../../src/modules/order-rules/import.cjs'),bad=table();bad.rows.push([...bad.rows[1]]);assert.equal(previewImport(store,bad,'admin').canCommit,false);
|
||||
const unknown=table();unknown.rows[1][0]='unknown';assert.equal(previewImport(store,unknown,'admin').canCommit,false);
|
||||
const invalid=table();invalid.rows[1][6]='not an address';assert.equal(previewImport(store,invalid,'admin').canCommit,false);
|
||||
const partial=table();partial.rows[1][6]='Valid <valid@example.test>, bad@invalid';assert.equal(previewImport(store,partial,'admin').canCommit,false);
|
||||
const plan=previewImport(store,table(),'admin'),old=store.get('rules','bs-change').draft;store.saveRule({...old,name:'另一个管理员已修改'},'admin');const before=store.all('rules');assert.throws(()=>commitImport(store,{id:plan.id},'admin'),e=>e.status===409);assert.deepEqual(store.all('rules'),before);
|
||||
});
|
||||
test('resume enables verified published snapshot without publishing a later draft and rejects stale switch actions',t=>{
|
||||
const store=setup(t),{captured}=activateReferenceMapping(store),old=store.get('rules','bs-change').draft;
|
||||
const saved=store.saveRule({...old,to:['a@example.test'],archiveDirectory:'\\\\server\\share',filenameDate:'receivedAt',bodyTemplateId:'template-1'},'admin');
|
||||
store.trial(saved.id,{version:saved.version,sampleId:captured.id});store.publish(saved.id,{version:saved.version},'admin');store.pause(saved.id,{version:saved.version},'admin');
|
||||
const edit=store.saveRule({...saved,intro:'尚未发布'},'admin'),snapshot=store.snapshot().rules.find(r=>r.id===saved.id);
|
||||
const input={version:edit.version,publishedVersion:saved.version,activationVersion:snapshot.activationVersion};store.resume(saved.id,input,'admin');assert.equal(store.get('rules',saved.id).published.intro,saved.intro);assert.equal(store.get('rules',saved.id).draft.intro,'尚未发布');assert.throws(()=>store.resume(saved.id,input,'admin'),e=>e.status===409);
|
||||
assert.equal(store.get('rules',saved.id).draft.bodyTemplateId,'template-1');
|
||||
const active=store.snapshot().rules.find(r=>r.id===saved.id);store.pause(saved.id,{version:edit.version},'admin');const record=store.get('rules',saved.id);record.publicationAdaptersHash='stale-mapping';store.put('rules',record);assert.throws(()=>store.resume(saved.id,{version:edit.version,publishedVersion:saved.version,activationVersion:active.activationVersion+1},'admin'),/识别配置已变化/);
|
||||
});
|
||||
test('Excel merged cells inherit only their explicit span and formulas/oversized ranges are rejected',()=>{
|
||||
const XLSX=require('xlsx'),{parse}=require('../../web/modules/order-rules/import-parser.js');
|
||||
const sheet=XLSX.utils.aoa_to_sheet([['序号','服务器存档地址','订单评审流程','邮件命名','邮件正文','电子流状态','收件人'],[1,'共享类别','流程甲','【备损订单通知书】','摘要信息','订单节点','a@example.test'],[2,'','流程乙','【备损订单更改通知书】','附件:PDF','',''],['','','说明文字']]);
|
||||
sheet['!merges']=[{s:{r:1,c:1},e:{r:2,c:1}},{s:{r:1,c:5},e:{r:2,c:5}},{s:{r:1,c:6},e:{r:2,c:6}}];const book=XLSX.utils.book_new();XLSX.utils.book_append_sheet(book,sheet,'分类规则');
|
||||
for(const bookType of ['biff8','xlsx']){const result=parse(XLSX,XLSX.write(book,{type:'buffer',bookType}));assert.equal(result.rows.length,3);assert.equal(result.rows[2][1],'共享类别');assert.equal(result.rows[2][6],'a@example.test');}
|
||||
sheet.C2={t:'s',v:'流程甲',f:'1+1'};assert.throws(()=>parse(XLSX,XLSX.write(book,{type:'buffer',bookType:'xlsx'})),/公式/);assert.throws(()=>parse(XLSX,new Uint8Array(2*1024*1024+1)),/2 MiB/);
|
||||
});
|
||||
test('chosen template is resolved from the rule snapshot and inactive templates are blocked',()=>{
|
||||
const {ruleTemplate}=require('../../src/modules/mail/rule-template.cjs');let active=true;
|
||||
const store={categoryTemplate:id=>({id:'legacy-'+id}),template:id=>({id,status:active?'active':'archived',text:'选定模板'})};
|
||||
assert.equal(ruleTemplate(store,'cat',{}).id,'legacy-cat');assert.equal(ruleTemplate(store,'cat',{bodyTemplateId:''}),null);assert.equal(ruleTemplate(store,'cat',{bodyTemplateId:'chosen'}).id,'chosen');active=false;assert.throws(()=>ruleTemplate(store,'cat',{bodyTemplateId:'chosen'}),e=>e.status===409);
|
||||
});
|
||||
@@ -0,0 +1,47 @@
|
||||
'use strict';
|
||||
const test=require('node:test'),assert=require('node:assert/strict');
|
||||
const {extractTitle}=require('../../src/modules/order-rules/title.cjs');
|
||||
const {buildBatch}=require('../../src/modules/order-rules/batch.cjs');
|
||||
const {applyBodyTemplate}=require('../../src/modules/order-rules/template.cjs');
|
||||
const rule={id:'overseas-notice',version:1,categoryId:'overseas-notice',name:'海外订单通知书',intro:'大家好:\n\n以下为海外订单通知书,请查收!',signature:'Best Regards!\n示例团队',to:['team@example.test'],cc:[],attachPdf:false};
|
||||
const title='订单号:TEST-100机芯号:CORE-A产品型号:MODEL-A客户简称:示例甲出货方式:CBU总数量:0订单号:HA100机芯号:CORE-B产品型号:MODEL-B客户简称:示例乙出货方式:SKD总数量:200';
|
||||
function order(id,brief=title,directory='\\\\example-nas\\orders\\overseas'){return {id,status:'pending',event:{orderNo:id,brief,receivedAt:'2026-10-20T01:00:00Z'},ruleSnapshot:rule,archive:{archivedAt:'2026-10-20T01:01:00Z',files:[{name:id+'.pdf',path:directory+'\\'+id+'.pdf',size:100,sha256:'a'.repeat(64),kind:'pdf'}]}};}
|
||||
test('title output separates shipping and customer for every summary row and keeps zero and missing distinct',()=>{
|
||||
const result=extractTitle(title);assert.equal(result.issues.length,0);
|
||||
assert.deepEqual(result.orders.map(({orderNo,coreNo,productModel,customerShort,shippingMethod,totalQuantity})=>({orderNo,coreNo,productModel,customerShort,shippingMethod,totalQuantity})),[
|
||||
{orderNo:'TEST-100',coreNo:'CORE-A',productModel:'MODEL-A',customerShort:'示例甲',shippingMethod:'CBU',totalQuantity:'0'},
|
||||
{orderNo:'HA100',coreNo:'CORE-B',productModel:'MODEL-B',customerShort:'示例乙',shippingMethod:'SKD',totalQuantity:'200'}]);
|
||||
assert.equal(extractTitle('订单号:TEST-2客户简称:示例丙总数量:5').orders[0].shippingMethod,undefined);assert.equal(result.brief.includes('出货方式:CBU'),true);
|
||||
});
|
||||
test('overseas mail has summary paragraphs and one actual directory after the list without per-file clutter',()=>{
|
||||
const one=order('TEST-100'),two=order('TEST-200','订单号:TEST-200机芯号:C产品型号:M客户简称:示例丙出货方式:CBU总数量:5');
|
||||
const batch=buildBatch(rule,[one,two],'2026-10-20T03:00:00Z');
|
||||
assert.equal(batch.text,[rule.intro,title.replace('订单号:HA100','\n订单号:HA100')+'\n'+two.event.brief,'存放地址:\\\\example-nas\\orders\\overseas',rule.signature].join('\n\n'));
|
||||
assert.equal((batch.text.match(/存放地址/g)||[]).length,1);assert.doesNotMatch(batch.text,/\.pdf/);assert.equal(batch.attachments.length,0);assert.deepEqual(batch.orderIds,['TEST-100','TEST-200']);
|
||||
assert.match(batch.html,/file:\/\/example-nas\/orders\/overseas/);assert.doesNotMatch(batch.html,/TEST-100\.pdf/);
|
||||
});
|
||||
test('overseas directory comes from frozen evidence and all actual directories are retained and escaped',()=>{
|
||||
const batch=buildBatch({...rule,archiveDirectory:'\\\\wrong\\configured'},[order('A','订单号:A客户简称:<script>','\\\\example-nas\\orders\\one'),order('B','订单号:B','\\\\example-nas\\orders\\two')],'2026-10-20T03:00:00Z');
|
||||
assert.match(batch.text,/orders\\one/);assert.match(batch.text,/orders\\two/);assert.doesNotMatch(batch.text,/wrong/);assert.doesNotMatch(batch.html,/<script>/);assert.match(batch.html,/<script>/);
|
||||
});
|
||||
test('business templates receive separate summary directory and category variables without duplicating content',()=>{
|
||||
const orders=[order('A','订单号:A机芯号:C出货方式:CBU总数量:5')],snapshot=buildBatch(rule,orders,'2026-10-20T03:00:00Z');
|
||||
const template={id:'t',version:1,text:'以下为{{类别名称}}\n\n{{订单明细}}\n\n存放地址:{{存放地址}}\n\n团队签名',html:'<p>{{类别名称}}</p><div>{{订单明细}}</div><p>存放地址:{{存放地址}}</p>',subject:'{{类别名称}}',attachments:[]};
|
||||
const batch=applyBodyTemplate(snapshot,template,orders,20971520);
|
||||
assert.equal(batch.text,'以下为海外订单通知书\n\n订单号:A机芯号:C出货方式:CBU总数量:5\n\n存放地址:\\\\example-nas\\orders\\overseas\n\n团队签名');
|
||||
assert.equal((batch.html.match(/订单号:A/g)||[]).length,1);assert.doesNotMatch(batch.text,/\.pdf/);assert.deepEqual(batch.to,['team@example.test']);
|
||||
});
|
||||
test('a template that omits business variables still retains the complete overseas summary and directory',()=>{
|
||||
const orders=[order('A','订单号:A客户简称:<b>')],snapshot=buildBatch(rule,orders,'2026-10-20T03:00:00Z');
|
||||
const batch=applyBodyTemplate(snapshot,{id:'t',version:1,text:'固定前言',html:'<p>固定前言</p>',attachments:[]},orders,20971520);
|
||||
assert.match(batch.text,/订单号:A/);assert.match(batch.text,/存放地址:\\\\example-nas\\orders\\overseas/);assert.match(batch.html,/<b>/);assert.doesNotMatch(batch.html,/<b>/);
|
||||
});
|
||||
test('legacy summary objects without text never discard the recorded notification brief',()=>{
|
||||
const item=order('A','订单号:A客户简称:保留旧摘要');item.event.titleOrders=[{orderNo:'A'}];
|
||||
assert.match(buildBatch(rule,[item],'2026-10-20T03:00:00Z').text,/保留旧摘要/);
|
||||
});
|
||||
test('the order-list variable keeps order lines separate from clickable archive directories',()=>{
|
||||
const orders=[order('A','订单号:A')],snapshot=buildBatch(rule,orders,'2026-10-20T03:00:00Z');
|
||||
const batch=applyBodyTemplate(snapshot,{id:'legacy',version:1,text:'旧格式\n{{订单列表}}',html:'<p>旧格式</p>{{订单列表}}',attachments:[]},orders,20971520);
|
||||
assert.equal(batch.text,'旧格式\n订单号:A\n\n存放地址:\\\\example-nas\\orders\\overseas');assert.match(batch.html,/href="file:\/\/example-nas\/orders\/overseas"/);assert.equal((batch.html.match(/订单号:A/g)||[]).length,1);
|
||||
});
|
||||
@@ -0,0 +1,12 @@
|
||||
'use strict';
|
||||
const test=require('node:test'),assert=require('node:assert/strict');
|
||||
const {seedRules,adapters}=require('../../src/modules/order-rules/catalog.cjs');
|
||||
const {previewMatch}=require('../../src/modules/order-rules/matching.cjs');
|
||||
const {validateRule}=require('../../src/modules/order-rules/validation.cjs');
|
||||
test('the category explicitly supplies product line without replacing the raw form evidence',()=>{
|
||||
const rule={...seedRules().find(r=>r.id==='bs-change'),productLine:'分类指定产品线'},sample=structuredClone(adapters.find(a=>a.id==='bs-change').sample),before=JSON.stringify(sample);
|
||||
const result=previewMatch([rule],adapters,sample);assert.equal(result.valid,true);assert.equal(result.event.productLine,'分类指定产品线');assert.equal(result.fieldTrace.find(f=>f.key==='productLine').path,'rule.productLine');assert.equal(JSON.stringify(sample),before);
|
||||
});
|
||||
test('explicit category product line survives rule editing and rejects an empty supplied value',()=>{
|
||||
const old=seedRules().find(r=>r.id==='bs-change');assert.equal(validateRule({...old,productLine:'分类产品线'},old).productLine,'分类产品线');assert.throws(()=>validateRule({...old,productLine:''},old),/产品线/);
|
||||
});
|
||||
@@ -0,0 +1,10 @@
|
||||
'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'),{BpmScanStore}=require('../../src/modules/bpm/scan-store.cjs');
|
||||
test('producer pending and corrupt deliveries block freezing despite a newer completed target scan',t=>{
|
||||
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'delivery-barrier-')),rules=new RuleStore(path.join(dir,'rules')),scans=new BpmScanStore(path.join(dir,'scans'));t.after(()=>{rules.close();scans.close();fs.rmSync(dir,{recursive:true,force:true});});
|
||||
rules.executionSources=()=>['a'];rules.deliveryBlockers=allowed=>scans.deliveries.pendingSources().filter(id=>allowed(id));rules.put('execution-scans',{id:'a',status:'complete',startedAt:'2026-10-21T03:01:00Z'});
|
||||
const cutoff='2026-10-21T03:00:00Z';assert.deepEqual(rules.discoveryBlockers(cutoff),[]);scans.deliveries.enqueue({connectionId:'a',runId:'old-run',rows:[],startedAt:'2026-10-21T03:00:00Z'});
|
||||
assert.ok(rules.discoveryBlockers(cutoff).length);assert.deepEqual(rules.discoveryBlockers(cutoff,id=>id==='other'),[]);
|
||||
scans.db.prepare("UPDATE execution_deliveries SET payload=x'00'").run();scans.deliveries.pending('a',Date.now());assert.ok(rules.discoveryBlockers(cutoff).length);scans.deliveries.acknowledge('old-run');assert.deepEqual(rules.discoveryBlockers(cutoff),[]);
|
||||
});
|
||||
@@ -0,0 +1,13 @@
|
||||
'use strict';
|
||||
const test=require('node:test'),assert=require('node:assert/strict');
|
||||
const {seedRules,adapters}=require('../../src/modules/order-rules/catalog.cjs'),{previewMatch}=require('../../src/modules/order-rules/matching.cjs'),{buildBatch}=require('../../src/modules/order-rules/batch.cjs');
|
||||
test('default modification rules keep PDF archives out of new messages',()=>{
|
||||
const rule={...seedRules().find(r=>r.id==='bs-change'),to:['2639266652@qq.com'],cc:[]};
|
||||
const order={id:'fixture',status:'pending',ruleSnapshot:rule,event:{orderNo:'000123',brief:'订单号:000123 客户:示例',receivedAt:'2026-10-23T00:00:00Z'},archive:{archivedAt:'2026-10-23T00:01:00Z',files:[{kind:'pdf',name:'000123.pdf',path:'C:\\fixture\\000123.pdf',size:10,sha256:'a'.repeat(64)}]}};
|
||||
assert.deepEqual(buildBatch(rule,[order],'2026-10-23T03:00:00Z').attachments,[]);
|
||||
});
|
||||
test('seeded overseas changes require the exact Excel notification node, with no inferred alias',()=>{
|
||||
const rule=seedRules().find(r=>r.id==='overseas-change'),sample=structuredClone(adapters.find(a=>a.id==='overseas-change').sample);
|
||||
for(const nodeName of ['订单更改通知书','订单专员(生效)'])assert.equal(previewMatch([rule],adapters,{...sample,nodeName}).valid,false);
|
||||
assert.equal(previewMatch([rule],adapters,{...sample,nodeName:'订单专员(订单通知书)'}).valid,true);
|
||||
});
|
||||
@@ -0,0 +1,65 @@
|
||||
'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 {activateReferenceMapping}=require('../fixtures/activate-field-mapping.cjs');
|
||||
const principal={user:{username:'admin',role:'admin'},sessionId:'isolated-test'};
|
||||
|
||||
function fixture(t){
|
||||
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'uncertain-conflict-'));
|
||||
const clock=()=>new Date('2026-10-23T02:00:00Z');
|
||||
const store=new RuleStore(path.join(dir,'state'),{clock});
|
||||
const {sample,captured,active}=activateReferenceMapping(store,'bs-change',{connectionId:'c1',instanceId:'i1',taskId:'t1',receivedAt:clock().toISOString()});
|
||||
const draft=store.get('rules','bs-change').draft;
|
||||
store.saveRule({...draft,adapterIds:[active.id],to:['test@qq.com'],cc:[],attachPdf:false,archiveDirectory:'\\\\synthetic-server\\orders',filenameDate:'receivedAt'},'admin');
|
||||
store.capturedPreview(captured.id);store.publish('bs-change',{version:store.get('rules','bs-change').draft.version},'admin');
|
||||
let row={...sample},archives=0,captures=0;
|
||||
const connection={id:'c1',owner:'admin',status:'connected'};
|
||||
const execution=new OrderExecutionCoordinator({store,clock,
|
||||
workspace:{getConnection:()=>connection,snapshot:()=>({connections:[connection]})},
|
||||
provider:{scan:async()=>[row],capabilities:()=>({liveTodo:true,pdfExport:true}),capture:async(_connection,_principal,source)=>{captures++;return {sample:{...source},snapshot:{processVersion:source.processVersion,fields:Object.entries(source.fields).map(([path,value])=>({path,value}))}};}},
|
||||
archive:{capabilities:()=>({automaticArchive:true,pdfExport:true}),archive:async()=>{archives++;throw Error('Synthetic connection lost after archive submission');}},
|
||||
});
|
||||
t.after(async()=>{await execution.stop();store.close();fs.rmSync(dir,{recursive:true,force:true});});
|
||||
return {store,execution,change:()=>{row={...row,title:'Changed after uncertain archive'};},counts:()=>({archives,captures})};
|
||||
}
|
||||
async function uncertainConflict(t){
|
||||
const f=fixture(t);
|
||||
await f.execution.scan({connectionId:'c1',idempotencyKey:'archive'},principal);
|
||||
const original=f.store.all('execution-tasks')[0];
|
||||
assert.equal(original.status,'unknown');assert.equal(original.step,'archive');
|
||||
const order=f.store.get('orders',original.orderId);
|
||||
assert.equal(order.status,'identified');assert.equal(order.archive,null);
|
||||
f.change();await f.execution.scan({connectionId:'c1',idempotencyKey:'changed'},principal);
|
||||
return {...f,original,order,task:f.store.get('execution-tasks',original.id)};
|
||||
}
|
||||
|
||||
test('changed source evidence preserves an uncertain archive outcome and its diagnostic',async t=>{
|
||||
const {store,execution,task,original,order,counts}=await uncertainConflict(t);
|
||||
assert.equal(task.conflict,true);assert.equal(task.conflictRow.title,'Changed after uncertain archive');
|
||||
assert.equal(task.status,'unknown');assert.equal(task.step,'archive');assert.equal(task.error,original.error);
|
||||
assert.equal(execution.snapshot(principal).tasks[0].canRetry,false);
|
||||
assert.deepEqual(store.get('orders',order.id),order);
|
||||
await execution.scan({connectionId:'c1',idempotencyKey:'repeat'},principal);
|
||||
assert.equal(store.get('execution-tasks',task.id).status,'unknown');assert.deepEqual(counts(),{archives:1,captures:1});
|
||||
});
|
||||
|
||||
for(const resolution of ['adopt','ignore'])test(`revision ${resolution} cannot erase an uncertain archive outcome`,async t=>{
|
||||
const {store,execution,task,order,counts}=await uncertainConflict(t);
|
||||
await assert.rejects(execution.resolve(task.id,{version:task.version,idempotencyKey:resolution,resolution,note:'Only changed source evidence is available'},principal),{status:409});
|
||||
await assert.rejects(execution.retry(task.id,{version:task.version,idempotencyKey:'retry',note:'No verified archive receipt is available'},principal),{status:409});
|
||||
assert.equal(store.get('execution-tasks',task.id).status,'unknown');
|
||||
assert.deepEqual(store.get('orders',order.id),order);assert.equal(store.all('execution-revisions').length,0);
|
||||
assert.deepEqual(counts(),{archives:1,captures:1});
|
||||
});
|
||||
|
||||
for(const status of ['sending','sent','ignored'])test(`scan conflict cannot downgrade protected ${status} task`,async t=>{
|
||||
const f=fixture(t);
|
||||
await f.execution.scan({connectionId:'c1',idempotencyKey:'archive'},principal);
|
||||
const task=f.store.all('execution-tasks')[0];task.status=status;task.step='complete';task.error=null;f.store.put('execution-tasks',task);
|
||||
f.change();await f.execution.scan({connectionId:'c1',idempotencyKey:'changed'},principal);
|
||||
const current=f.store.get('execution-tasks',task.id);
|
||||
assert.equal(current.conflict,true);assert.equal(current.status,status);assert.equal(current.step,'complete');
|
||||
await assert.rejects(f.execution.resolve(current.id,{version:current.version,idempotencyKey:'adopt-terminal',resolution:'adopt',note:'Changed evidence cannot restart a protected task'},principal),{status:409});
|
||||
assert.deepEqual(f.counts(),{archives:1,captures:1});
|
||||
});
|
||||
@@ -0,0 +1,264 @@
|
||||
'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 {OrderExecutionCoordinator}=require('../../src/modules/order-execution/coordinator.cjs');
|
||||
const {OrderRuleDispatcher}=require('../../src/modules/order-rules/dispatcher.cjs');
|
||||
const {activateFieldMapping}=require('../fixtures/activate-field-mapping.cjs');
|
||||
const admin={username:'admin',role:'admin'},principal={user:admin,sessionId:'test-session'};
|
||||
function fixture(t){
|
||||
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'execution-'));const now=()=>new Date('2026-10-19T03:00:00Z');
|
||||
const store=new RuleStore(dir,{clock:now});t.after(()=>{store.close();fs.rmSync(dir,{recursive:true,force:true});});
|
||||
const connection={id:'c1',owner:'admin',status:'connected'},workspace={getConnection:()=>connection,snapshot:()=>({connections:[connection]})};
|
||||
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={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})};
|
||||
}
|
||||
async function configure(f){
|
||||
await f.execution.scan({connectionId:'c1',idempotencyKey:'first'},principal);
|
||||
const captured=f.store.fields().samples[0];
|
||||
const adapter=activateFieldMapping(f.store,{sampleId:captured.id,processName:f.row.processName,processVersion:'1.4',fields:{orderNo:'order',brief:'brief'}},admin);
|
||||
const current=f.store.snapshot().rules.find(r=>r.id==='bs-change');
|
||||
const saved=f.store.saveRule({...current,adapterIds:[adapter.id],to:['2639266652@qq.com'],attachPdf:false,archiveDirectory:'\\\\server\\orders',filenameDate:'receivedAt'},'admin');
|
||||
assert.equal(f.store.capturedPreview(captured.id).valid,true);f.store.publish(saved.id,{version:saved.version},'admin');
|
||||
}
|
||||
|
||||
for(const correction of ['migration','recheck'])for(const outcome of ['receipt','failure'])test(`in-flight archive ${outcome} cannot overwrite ${correction} generation or task`,async t=>{
|
||||
const f=fixture(t);await configure(f);
|
||||
let release,started;const gate=new Promise(r=>{release=r;}),begin=new Promise(r=>{started=r;});
|
||||
const archive=f.archive.archive;let original,receipt;
|
||||
f.archive.archive=async input=>{original=structuredClone(input.order);started();await gate;if(outcome==='failure')throw Error('synthetic old archive failure');receipt=await archive(input);return receipt;};
|
||||
const scanning=f.execution.scan({connectionId:'c1',idempotencyKey:'archive-race'},principal);await begin;
|
||||
try{
|
||||
const current=f.store.get('rules','bs-change').draft,saved=f.store.saveRule({...current,archiveDirectory:'\\\\server\\corrected'},'admin');
|
||||
f.store.capturedPreview(f.store.fields().samples[0].id);f.store.publish(saved.id,{version:saved.version},'admin');
|
||||
if(correction==='migration')f.store.applyMigration(saved.id,{version:saved.version,idempotencyKey:'correct-output',note:'修正归档目录并重新处理'},'admin');
|
||||
else f.store.recheck(original.id,{note:'重新识别并应用正确目录'},'admin');
|
||||
const corrected=f.store.get('orders',original.id),correctedTask=f.store.all('execution-tasks')[0];
|
||||
release();await scanning;
|
||||
assert.equal(f.store.get('orders',original.id).archive,null);assert.equal(f.store.get('orders',original.id).archiveGeneration,corrected.archiveGeneration);assert.equal(f.store.get('orders',original.id).status,'identified');
|
||||
assert.deepEqual(f.store.get('execution-tasks',correctedTask.id),correctedTask);
|
||||
if(outcome==='receipt'){
|
||||
const history=f.store.get('orders',original.id).archiveHistory;
|
||||
assert.equal(history.some(item=>item.generation===(original.archiveGeneration||1)&&item.evidence?.files[0].sha256===receipt.files[0].sha256),true);
|
||||
}
|
||||
assert.equal(f.store.prepare('2026-10-19T03:00:00Z','admin').length,0);
|
||||
f.archive.archive=archive;await f.execution.scan({connectionId:'c1',idempotencyKey:'correct-generation'},principal);
|
||||
assert.equal(f.store.get('orders',original.id).status,'pending');
|
||||
}finally{release();await scanning;await f.execution.stop();}
|
||||
});
|
||||
|
||||
test('distribution migration during a real journaled archive remains recoverable without reusing a stale generation',async t=>{
|
||||
const f=fixture(t);await configure(f);const {OrderArchiveProvider}=require('../../src/modules/storage/order-archive.cjs');let release,started;const gate=new Promise(r=>release=r),begin=new Promise(r=>started=r),files=new Map(),bytes=Buffer.from('%PDF-1.7 synthetic journal race'),sha=crypto.createHash('sha256').update(bytes).digest('hex');let rendered=0,sharedWrites=0;
|
||||
const storage={store:{servers:()=>[{id:'s',enabled:true,host:'server',share:'orders',directory:'',state:{readable:true,writable:true}}]},check:async()=>{},run:async(_,fn)=>fn({},null),readFile:async(_,relative)=>({bytes:files.get(relative)}),operation:async(_,action,args)=>{if(action==='archive'){sharedWrites++;if(sharedWrites===1){started();await gate;}const relative=[args[2],args[1]].filter(Boolean).join('/');files.set(relative,bytes);return {filename:args[1],relativePath:relative,sha256:sha,bytes:bytes.length};}return {bytes:files.get(args[0])};}};
|
||||
const archive=new OrderArchiveProvider({storage,journal:f.store,clock:()=>new Date('2026-10-19T03:00:00Z'),outputDir:path.join(f.store.vault.stateDir||f.store.vault.dir||os.tmpdir(),'journal-race-'+crypto.randomUUID()),renderer:async(_,options)=>{await fs.promises.mkdir(options.outputDir,{recursive:true});const file=path.join(options.outputDir,++rendered+'.pdf');await fs.promises.writeFile(file,bytes);return {path:file};}});t.after(()=>fs.promises.rm(path.dirname(archive.outputDir),{recursive:true,force:true}));f.execution.archive=archive;
|
||||
const scanning=f.execution.scan({connectionId:'c1',idempotencyKey:'journal-start'},principal);await begin;try{const original=f.store.all('orders')[0],rule=f.store.get('rules','bs-change').draft,saved=f.store.saveRule({...rule,to:['new-owner@example.test']},'admin');f.store.capturedPreview(f.store.fields().samples[0].id);f.store.publish(saved.id,{version:saved.version},'admin');const result=f.store.applyMigration(saved.id,{version:saved.version,idempotencyKey:'distribution-race',note:'只更换通知收件人规则'},'admin');assert.equal(result.items[0].archiveChanged,false);release();await scanning;await f.execution.scan({connectionId:'c1',idempotencyKey:'journal-retry'},principal);const final=f.store.get('orders',original.id);assert.equal(final.status,'pending',final.error);assert.ok(final.archive);assert.deepEqual(final.ruleSnapshot.to,['new-owner@example.test']);assert.ok(final.archiveGeneration>(original.archiveGeneration||1));assert.equal(f.store.all('archive-intents').length,2);assert.ok(final.archiveHistory.some(item=>item.stale));}finally{release();await scanning;await f.execution.stop();}
|
||||
});
|
||||
|
||||
test('scan prefilter uses complete process-node pairs without crossing their columns',async t=>{
|
||||
const f=fixture(t),rule=f.store.get('rules','bs-change').draft;
|
||||
f.store.saveRule({...rule,scopes:[{processName:f.row.processName,nodeName:'另一个节点'},{processName:'另一个流程',nodeName:f.row.nodeName}]},'admin');
|
||||
await f.execution.scan({connectionId:'c1',idempotencyKey:'paired-scope-scan'},principal);
|
||||
assert.equal(f.store.all('capture-samples').length,0);assert.equal(f.execution.snapshot().tasks.length,0);assert.deepEqual(f.counts(),{captures:0,exports:0});await f.execution.stop();
|
||||
});
|
||||
test('capture-backed dynamic binding recovers blocked task with stable identity and exports only once',async t=>{
|
||||
const f=fixture(t);await configure(f);await f.execution.scan({connectionId:'c1',idempotencyKey:'second'},principal);
|
||||
assert.equal(f.store.all('orders')[0].status,'pending');assert.equal(f.execution.snapshot().tasks.length,1);assert.equal(f.counts().exports,1);
|
||||
await f.execution.scan({connectionId:'c1',idempotencyKey:'third'},principal);assert.equal(f.counts().exports,1);assert.equal(f.execution.snapshot().capabilities.automaticArchive,true);
|
||||
assert.throws(()=>f.store.saveAdapter({sampleId:f.store.fields().samples[0].id,processName:f.row.processName,processVersion:'1.4',fields:{orderNo:'invented',brief:'brief'},version:1},admin),/字段/);
|
||||
});
|
||||
test('capture failures block the entire category rather than silently omitting an order',async t=>{
|
||||
const f=fixture(t);await configure(f);await f.execution.scan({connectionId:'c1',idempotencyKey:'second'},principal);
|
||||
f.row.taskId='t2';f.row.instanceId='i2';f.setFail(true);await f.execution.scan({connectionId:'c1',idempotencyKey:'third'},principal);
|
||||
assert.equal(f.execution.snapshot().tasks.filter(t=>t.status==='failed').length,1);
|
||||
assert.equal(f.store.prepare('2026-10-19T03:00:00Z','admin').length,0);
|
||||
});
|
||||
test('cold restart probes archived pending work and restores dispatch gates without exporting again',async t=>{
|
||||
const f=fixture(t);await configure(f);await f.execution.scan({connectionId:'c1',idempotencyKey:'archive-before-restart'},principal);
|
||||
const before=f.counts();let captured=false,probed=false;
|
||||
const provider={scan:f.provider.scan,capabilities:()=>({liveTodo:true,pdfExport:captured}),capture:async(...args)=>{captured=true;return f.provider.capture(...args);}};
|
||||
const archive={...f.archive,capabilities:()=>({automaticArchive:probed,pdfExport:probed}),probe:async rule=>{assert.equal(rule.id,'bs-change');probed=true;return {automaticArchive:true,pdfExport:true};}};
|
||||
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,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,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);
|
||||
const task=f.store.all('execution-tasks')[0],order=f.store.get('orders',task.orderId),before=f.counts();task.status='archiving';task.step='archive';task.error=null;f.store.put('execution-tasks',task);
|
||||
const archive={...f.archive,supportsRecovery};const execution=new OrderExecutionCoordinator({...f.execution,archive});
|
||||
assert.equal(execution.snapshot().tasks[0].status,'pending');assert.equal(execution.snapshot().tasks[0].step,'complete');
|
||||
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 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(),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);
|
||||
f.store.saveSettings({...f.store.settings(),channelId:'channel1'},'admin');const batch=f.store.prepare('2026-10-19T03:00:00Z','admin')[0];f.store.finishSending(batch.id,'failed','SMTP verify failed');
|
||||
let sends=0;const mail={exclusive:async(id,fn)=>fn(),store:{channelSecret:id=>({id,version:1,email:'sender@example.test',name:'s',smtp:{}}),guard:()=>{}},smtpFactory:()=>({verify:async()=>{},sendMail:async message=>{sends++;assert.deepEqual(message.to,['2639266652@qq.com']);return {accepted:message.to,rejected:[]};},close:()=>{}})};
|
||||
const dispatcher=new OrderRuleDispatcher({store:f.store,mail,clock:()=>new Date('2026-10-21T00:00:00Z'),providersReady:()=>true});
|
||||
const input={version:f.store.get('batches',batch.id).version,idempotencyKey:'resend1',note:'已检查SMTP已修复'};
|
||||
await assert.rejects(dispatcher.resend(batch.id,input,{username:'op',role:'operator'}),{status:403});
|
||||
const sent=await dispatcher.resend(batch.id,input,admin);assert.equal(sent.status,'sent');assert.equal(sent.parentBatchId,batch.id);
|
||||
assert.equal((await dispatcher.resend(batch.id,input,admin)).id,sent.id);assert.equal(sends,1);
|
||||
await assert.rejects(dispatcher.resend(batch.id,{...input,note:'与原请求不同的依据'},admin),{status:409});
|
||||
await assert.rejects(dispatcher.resend(batch.id,{...input,idempotencyKey:'again'},admin),{status:409});
|
||||
});
|
||||
test('scope, calendar and pause gates survive actual persisted capture provenance',async t=>{
|
||||
const f=fixture(t);await configure(f);
|
||||
assert.equal(f.execution.snapshot({user:{username:'other',role:'operator'},sessionId:'other'}).fields.samples.length,0);
|
||||
assert.equal(f.execution.snapshot({user:{username:'other',role:'operator'},sessionId:'other'}).tasks.length,0);
|
||||
await assert.rejects(f.execution.scan({connectionId:'c1',idempotencyKey:'foreign'}, {user:{username:'other',role:'operator'},sessionId:'other'}),{status:403});
|
||||
let scans=0;const scan=f.provider.scan;f.provider.scan=async(...args)=>{scans++;return scan(...args);};
|
||||
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=()=>[];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');
|
||||
assert.throws(()=>f.store.publish('bs-change',{version:f.store.get('rules','bs-change').draft.version},'admin'),{status:409});
|
||||
});
|
||||
test('restart converts a never-sent manual attempt into a reachable failed attempt',async t=>{
|
||||
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'resend-restart-'));let store=new RuleStore(dir);t.after(()=>{store.close();fs.rmSync(dir,{recursive:true,force:true});});
|
||||
store.put('orders',{id:'o1',status:'batched',batchId:'manual1'});store.put('batches',{id:'manual1',version:1,manual:true,status:'prepared',orderIds:['o1']});
|
||||
store.close();store=new RuleStore(dir);assert.equal(store.get('batches','manual1').status,'failed');assert.equal(store.get('orders','o1').status,'pending');
|
||||
store.put('batches',{id:'manual2',version:1,manual:true,status:'sending',orderIds:['o1']});store.put('orders',{id:'o1',status:'batched',batchId:'manual2'});
|
||||
store.close();store=new RuleStore(dir);assert.equal(store.get('batches','manual2').status,'unknown');assert.equal(store.get('orders','o1').status,'unknown');
|
||||
});
|
||||
test('workspace exceptions deduplicate per task and recovery requests verification without claiming manual closure',async t=>{
|
||||
const {WorkspaceStore}=require('../../src/modules/workspace/store.cjs');const f=fixture(t),dir=fs.mkdtempSync(path.join(os.tmpdir(),'execution-exception-')),workspace=new WorkspaceStore(dir);t.after(()=>{workspace.close();fs.rmSync(dir,{recursive:true,force:true});});
|
||||
const connection=f.execution.workspace.getConnection('c1');f.execution.workspace={getConnection:()=>connection,snapshot:()=>({...workspace.snapshot(),connections:[connection]}),createException:workspace.createException.bind(workspace),actOnException:workspace.actOnException.bind(workspace),record:workspace.record.bind(workspace)};
|
||||
await configure(f);await f.execution.scan({connectionId:'c1',idempotencyKey:'recover'},principal);assert.equal(workspace.snapshot().exceptions.length,1);assert.equal(workspace.snapshot().exceptions[0].status,'verifying');assert.equal(f.execution.snapshot().tasks[0].recovery.status,'awaiting_verification');
|
||||
connection.owner='';f.row.taskId='unassigned';f.row.instanceId='unassigned';f.setFail(true);await f.execution.scan({connectionId:'c1',idempotencyKey:'failed-unassigned'},principal);
|
||||
f.setFail(false);await f.execution.scan({connectionId:'c1',idempotencyKey:'recover-unassigned'},principal);const item=workspace.snapshot().exceptions.find(e=>!e.owner);assert.equal(item.status,'open');assert.equal(f.execution.snapshot().tasks.find(t=>t.row.taskId==='unassigned').recovery.status,'awaiting_verification');assert.equal(workspace.snapshot().exceptions.filter(e=>e.status==='resolved').length,0);
|
||||
});
|
||||
test('interrupted archive recovery is explicitly retried and never silently replayed by scan',async t=>{
|
||||
const f=fixture(t);await configure(f);f.archive.supportsRecovery=true;
|
||||
const archive=f.archive.archive;f.archive.archive=async()=>{throw Error('worker interrupted');};
|
||||
await f.execution.scan({connectionId:'c1',idempotencyKey:'second'},principal);
|
||||
const task=f.execution.snapshot().tasks[0];assert.equal(task.status,'failed');assert.equal(task.step,'archive');
|
||||
f.archive.archive=archive;await f.execution.scan({connectionId:'c1',idempotencyKey:'third'},principal);assert.equal(f.counts().exports,0);
|
||||
await f.execution.retry(task.id,{version:task.version,idempotencyKey:'retry',note:'已核对归档幂等凭据'},principal);
|
||||
assert.equal(f.execution.snapshot().tasks[0].status,'pending');assert.equal(f.counts().exports,1);
|
||||
const running=f.store.get('execution-tasks',task.id);running.status='archiving';running.step='archive';f.store.put('execution-tasks',running);
|
||||
const restarted=new OrderExecutionCoordinator({...f.execution,store:f.store,workspace:f.execution.workspace,provider:f.provider,archive:f.archive});
|
||||
assert.equal(restarted.snapshot().tasks[0].status,'pending');await restarted.stop();
|
||||
});
|
||||
test('unknown send first requires recorded verification; only then frozen manual resend is reachable',async t=>{
|
||||
const f=fixture(t);await configure(f);await f.execution.scan({connectionId:'c1',idempotencyKey:'second'},principal);
|
||||
f.store.saveSettings({...f.store.settings(),channelId:'channel1'},'admin');const batch=f.store.prepare('2026-10-19T03:00:00Z','admin')[0];
|
||||
f.store.beginSending(batch.id);f.store.finishSending(batch.id,'unknown','connection lost');
|
||||
const dispatcher=new OrderRuleDispatcher({store:f.store,mail:{exclusive:async(id,fn)=>fn()},providersReady:()=>true});
|
||||
await assert.rejects(dispatcher.resend(batch.id,{version:f.store.get('batches',batch.id).version,idempotencyKey:'bad',note:'尚未完成服务端核对'},admin),{status:409});
|
||||
const resolveInput={version:f.store.get('batches',batch.id).version,idempotencyKey:'verified',resolution:'retry',note:'服务器确认未接受本次邮件'};
|
||||
assert.throws(()=>f.store.resolve(batch.id,{...resolveInput,version:0},'admin',{controlled:true}),{status:409});
|
||||
const resolved=f.store.resolve(batch.id,resolveInput,'admin',{controlled:true});assert.equal(resolved.status,'failed');
|
||||
assert.equal(f.store.resolve(batch.id,resolveInput,'admin',{controlled:true}).status,'failed');
|
||||
assert.throws(()=>f.store.resolve(batch.id,{...resolveInput,note:'与原来不同的核验结论'},'admin',{controlled:true}),{status:409});
|
||||
assert.equal(f.store.prepare('2026-10-19T03:00:00Z','system').length,0);
|
||||
});
|
||||
test('all fifteen categories capture actual fixture fields, archive to temporary files and send through real loopback SMTP',async t=>{
|
||||
const {SMTPServer}=require('smtp-server'),nodemailer=require('nodemailer'),{simpleParser}=require('mailparser');
|
||||
const f=fixture(t),rows=f.store.snapshot().rules.map((rule,i)=>({...f.row,instanceId:'i'+i,taskId:'t'+i,processName:rule.processNames[0],nodeName:rule.nodeNames[0],processVersion:'fixture-1',title:'订单号:SO-'+i,serialNum:'S'+i}));
|
||||
f.provider.scan=async()=>rows;
|
||||
f.provider.capture=async(connection,principal,row)=>({sample:{...row,connectionId:connection.id,fields:{'actual.order':'SO-'+row.taskId.slice(1),'actual.summary':'采集摘要'}},snapshot:{processVersion:row.processVersion,html:'<p>captured fixture</p>',fields:[{path:'actual.order',label:'订单号',value:'SO-'+row.taskId.slice(1)},{path:'actual.summary',label:'摘要',value:'采集摘要'}]}});
|
||||
await f.execution.scan({connectionId:'c1',idempotencyKey:'capture15'},principal);
|
||||
for(const [index,current] of f.store.snapshot().rules.entries()){
|
||||
const captured=f.store.fields().samples.find(s=>s.processName===rows[index].processName);
|
||||
const adapter=activateFieldMapping(f.store,{sampleId:captured.id,processName:captured.processName,processVersion:captured.processVersion,fields:{orderNo:'actual.order',brief:'actual.summary'}},admin);
|
||||
const updated=f.store.snapshot().rules.find(r=>r.id===current.id);
|
||||
const saved=f.store.saveRule({...updated,processNames:[captured.processName],nodeNames:[rows[index].nodeName],adapterIds:[adapter.id],to:['2639266652@qq.com'],attachPdf:false,archiveDirectory:'\\\\server\\orders',filenameDate:'receivedAt'},'admin');
|
||||
assert.equal(f.store.capturedPreview(captured.id).valid,true);f.store.publish(saved.id,{version:saved.version},'admin');
|
||||
}
|
||||
await f.execution.scan({connectionId:'c1',idempotencyKey:'archive15'},principal);assert.equal(f.store.all('orders').filter(o=>o.status==='pending').length,15);
|
||||
let messages=[];const smtp=new SMTPServer({secure:false,hideSTARTTLS:true,authOptional:true,disabledCommands:['AUTH'],onData(stream,session,cb){const chunks=[];stream.on('data',chunk=>chunks.push(chunk));stream.on('end',()=>{messages.push(Buffer.concat(chunks));cb();});}});
|
||||
await new Promise(resolve=>smtp.listen(0,'127.0.0.1',resolve));t.after(()=>new Promise(resolve=>smtp.close(resolve)));
|
||||
const mail={exclusive:async(id,work)=>work(),store:{channelSecret:id=>({id,version:1,email:'sender@example.test',name:'通知',smtp:{}}),guard:()=>{}},smtpFactory:()=>nodemailer.createTransport({host:'127.0.0.1',port:smtp.server.address().port,secure:false,ignoreTLS:true})};
|
||||
f.store.saveSettings({...f.store.settings(),enabled:true,channelId:'channel1'},'admin');
|
||||
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),['2639266652@qq.com']);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?'blocks disallowed Cc before delivery':'complete envelope refusal is explicitly failed'}`,async t=>{
|
||||
const {SMTPServer}=require('smtp-server'),nodemailer=require('nodemailer');const f=fixture(t);await configure(f);
|
||||
const current=f.store.snapshot().rules.find(r=>r.id==='bs-change'),saved=f.store.saveRule({...current,to:['2639266652@qq.com'],cc:partial?['rejected@example.test']:[]},'admin');
|
||||
f.store.capturedPreview(f.store.fields().samples[0].id);f.store.publish(saved.id,{version:saved.version},'admin');
|
||||
await f.execution.scan({connectionId:'c1',idempotencyKey:'archive'},principal);f.store.saveSettings({...f.store.settings(),enabled:true,channelId:'channel1'},'admin');
|
||||
let messages=0;const smtp=new SMTPServer({secure:false,hideSTARTTLS:true,authOptional:true,disabledCommands:['AUTH'],onRcptTo(address,session,cb){if(!partial||address.address==='rejected@example.test'){const error=Error('Recipient refused');error.responseCode=550;return cb(error);}cb();},onData(stream,session,cb){stream.resume();stream.on('end',()=>{messages++;cb();});}});
|
||||
await new Promise(resolve=>smtp.listen(0,'127.0.0.1',resolve));t.after(()=>new Promise(resolve=>smtp.close(resolve)));
|
||||
const mail={exclusive:async(id,work)=>work(),store:{channelSecret:id=>({id,version:1,email:'sender@example.test',name:'通知',smtp:{}}),guard:()=>{}},smtpFactory:()=>nodemailer.createTransport({host:'127.0.0.1',port:smtp.server.address().port,secure:false,ignoreTLS:true})};
|
||||
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});
|
||||
await dispatcher.tick();now=new Date('2026-10-19T03:00:00Z');await dispatcher.tick();await dispatcher.stop();assert.equal(f.store.all('batches')[0].status,'failed');assert.equal(messages,0);
|
||||
assert.equal(f.store.prepare('2026-10-19T03:00:00Z','system').length,0);
|
||||
});
|
||||
|
||||
function deferred(){let resolve;const promise=new Promise(r=>resolve=r);return {promise,resolve};}
|
||||
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;
|
||||
f.provider.scan=()=>discovery.promise;
|
||||
f.provider.capture=async(c,p,row)=>{entered.resolve();await capture.promise;if(fail)throw Error('late capture failed');return {sample:{...row,connectionId:c.id,title:'订单号:'+row.taskId,brief:'摘要',fields:{order:row.taskId,brief:'真实摘要'}},snapshot:{processVersion:'1.4',html:'<p>fixture</p>',fields:[{path:'order',label:'订单号',value:row.taskId},{path:'brief',label:'摘要',value:'真实摘要'}]}};};
|
||||
const scanning=f.execution.scan({connectionId:'c1',idempotencyKey:'gated'},principal);
|
||||
assert.throws(()=>f.store.beginSending(batch.id),/扫描|完整/,'even a just queued discovery blocks existing batch');
|
||||
assert.equal(f.store.prepare(cutoff,'admin').length,0);
|
||||
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.equal(f.store.prepare(cutoff,'admin').length,0);
|
||||
fail=false;await f.execution.scan({connectionId:'c1',idempotencyKey:'recovered'},principal);
|
||||
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);
|
||||
const cutoff='2026-10-19T03:00:00Z';assert.equal(f.store.prepare(cutoff,'admin').length,0,'pre-cutoff snapshot cannot certify all arrivals');
|
||||
f.execution.clock=f.store.clock=()=>new Date(cutoff);const original=f.provider.scan;f.provider.scan=async()=>{throw Error('list unavailable');};
|
||||
await assert.rejects(f.execution.scan({connectionId:'c1',idempotencyKey:'failed-list'},principal),/list unavailable/);assert.equal(f.store.prepare(cutoff,'admin').length,0);assert.equal(f.execution.snapshot().query.status,'failed');
|
||||
f.provider.scan=original;await f.execution.scan({connectionId:'c1',idempotencyKey:'recovered-list'},principal);assert.equal(f.store.prepare(cutoff,'admin').length,1);
|
||||
});
|
||||
|
||||
test('dispatcher rechecks discovery after SMTP verification and keeps an unsent reservation recoverable',async t=>{
|
||||
const f=fixture(t);await configure(f);await f.execution.scan({connectionId:'c1',idempotencyKey:'ready'},principal);f.store.saveSettings({...f.store.settings(),enabled:true,channelId:'channel1'},'admin');const batch=f.store.prepare('2026-10-19T03:00:00Z','admin')[0];
|
||||
const verified=deferred(),verifyGate=deferred(),discovery=deferred();let sends=0;const mail={clients:new Set(),store:{channelSecret:id=>({id,version:1,email:'sender@example.test',smtp:{}}),guard(){}},smtpFactory:()=>({verify:async()=>{verified.resolve();await verifyGate.promise;},sendMail:async()=>{sends++;return {accepted:['2639266652@qq.com']};},close(){}})};
|
||||
const dispatcher=new OrderRuleDispatcher({store:f.store,mail,clock:f.execution.clock,providersReady:()=>true});const dispatch=dispatcher.dispatch(batch,f.store.settings());await verified.promise;
|
||||
f.provider.scan=()=>discovery.promise;const scan=f.execution.scan({connectionId:'c1',idempotencyKey:'during-verify'},principal);f.store.capabilities.pdfExport=false;verifyGate.resolve();assert.equal(await dispatch,false);assert.equal(sends,0);assert.equal(f.store.get('batches',batch.id).status,'prepared');
|
||||
discovery.resolve([f.row]);await scan;await dispatcher.dispatch(batch,f.store.settings());assert.equal(sends,1);assert.equal(f.store.get('batches',batch.id).status,'sent');await dispatcher.stop();
|
||||
});
|
||||
test('all configured sources require independent complete cutoff discovery and task retry capability matches owner authorization',async t=>{
|
||||
const f=fixture(t);await configure(f);await f.execution.scan({connectionId:'c1',idempotencyKey:'ready'},principal);
|
||||
const connections=[{id:'c1',owner:'admin',status:'connected'},{id:'c2',owner:'operator',status:'connected'}];f.execution.workspace={getConnection:id=>connections.find(c=>c.id===id),snapshot:()=>({connections})};const cutoff='2026-10-19T03:00:00Z';assert.equal(f.store.prepare(cutoff,'admin').length,0);
|
||||
f.provider.scan=async()=>[];await f.execution.scan({connectionId:'c2',idempotencyKey:'second-source'},principal);assert.equal(f.store.prepare(cutoff,'admin').length,1);
|
||||
const task=f.store.all('execution-tasks')[0];task.status='failed';task.step='archive';f.store.put('execution-tasks',task);const owner={user:{username:'admin',role:'operator'},sessionId:'owner'};
|
||||
assert.equal(f.execution.snapshot(owner).tasks[0].canRetry,true);assert.equal(f.execution.snapshot({user:{username:'admin',role:'viewer'},sessionId:'reader'}).tasks[0].canRetry,false);
|
||||
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.conflictRow?.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('an archived task cannot use an adopted revision to regenerate completed evidence',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')[0];
|
||||
await assert.rejects(f.execution.resolve(task.id,{version:task.version,idempotencyKey:'adopt2',resolution:'adopt',note:'人工修订不得重新生成成功回执'},principal),{status:409});
|
||||
assert.deepEqual(f.store.get('orders',original.id),original);assert.equal(f.counts().exports,1);assert.equal(f.store.all('execution-tasks').length,1);
|
||||
});
|
||||
test('R2 post-allowance trusted hints retain late and missed work but exclude preactivation history',async t=>{const f=fixture(t);await configure(f);await f.execution.scan({connectionId:'c1',idempotencyKey:'frozen-ready'},principal);const batch=f.store.prepare('2026-10-19T03:00:00Z','admin')[0],before=f.counts();f.store.put('settings',{...f.store.get('settings','main'),processingEnabled:true,processingSince:'2026-10-19T00:00:00Z'});f.execution.systemPrincipal=principal;f.execution.clock=f.store.clock=()=>new Date('2026-10-19T03:01:30Z');await f.execution.notifyDiscovery({connectionId:'c1',runId:'late90',rows:[{...f.row,taskId:'late90',receivedAt:'2026-10-19T02:59:00Z'},{...f.row,taskId:'old',receivedAt:'2026-10-18T02:00:00Z'}],startedAt:f.execution.now(),finishedAt:f.execution.now()});await f.execution.background();const late=f.store.all('execution-tasks').find(t=>t.row.taskId==='late90');assert.ok(late);assert.equal(late.status,'blocked');assert.equal(late.blockedByBatchId,batch.id);assert.equal(late.missedWindow.end,'2026-10-19T03:00:00.000Z');assert.equal(f.store.all('execution-tasks').some(t=>t.row.taskId==='old'),false);assert.deepEqual(f.counts(),before);f.execution.clock=f.store.clock=()=>new Date('2026-10-20T03:01:30Z');await f.execution.notifyDiscovery({connectionId:'c1',runId:'missed-next-day',rows:[{...f.row,taskId:'missed',receivedAt:'2026-10-19T08:00:00Z'}],startedAt:f.execution.now(),finishedAt:f.execution.now()});await f.execution.background();const missed=f.store.all('execution-tasks').find(t=>t.row.taskId==='missed');assert.equal(missed.status,'blocked');assert.equal(missed.missedWindow.end,'2026-10-19T09:00:00.000Z');assert.ok(f.store.all('business-issues').some(i=>i.taskId===missed.id&&i.owners.includes('admin')));assert.ok(require('../../src/modules/order-rules/access.cjs').publicSnapshot(f.store,f.execution.workspace,{username:'admin',role:'operator'}).issues.some(i=>i.taskId===missed.id));assert.deepEqual(f.counts(),before);});
|
||||
test('R3 non-five-minute cutoff forces distinct post-cutoff fallback',async t=>{const f=fixture(t);let now=new Date('2026-10-19T03:01:00Z'),scans=0;f.execution.clock=f.store.clock=()=>now;f.store.schedule=()=>({times:['11:02','17:02'],weekends:false});f.execution.systemPrincipal=principal;f.store.put('settings',{...f.store.get('settings','main'),processingEnabled:true,processingSince:'2026-10-19T00:00:00Z'});f.provider.scan=async()=>{scans++;return [];};await f.execution.background();now=new Date('2026-10-19T03:02:00Z');await f.execution.background();assert.equal(scans,2);assert.equal(f.store.get('execution-scans','c1').startedAt,now.toISOString());assert.deepEqual(f.store.discoveryBlockers(now.toISOString()),[]);});
|
||||
test('pending discovery runs retain an event missing from the next complete list',async t=>{const f=fixture(t);await configure(f);f.execution.systemPrincipal=principal;const row={...f.row,taskId:'transient',instanceId:'transient'};await f.execution.notifyDiscovery({connectionId:'c1',runId:'first-pending',rows:[row],startedAt:'2026-10-19T03:00:00Z',finishedAt:'2026-10-19T03:00:01Z'});await f.execution.notifyDiscovery({connectionId:'c1',runId:'next-empty',rows:[],startedAt:'2026-10-19T03:00:02Z',finishedAt:'2026-10-19T03:00:03Z'});await f.execution.background();assert.equal(f.store.all('execution-tasks').some(t=>t.row.taskId==='transient'),false);f.store.put('settings',{...f.store.get('settings','main'),processingEnabled:true,processingSince:'2026-10-19T00:00:00Z'});f.execution=new OrderExecutionCoordinator({...f.execution,systemPrincipal:principal});f.provider.capture=async()=>{throw Error('已离开授权节点,需核对历史证据');};await f.execution.background();const task=f.store.all('execution-tasks').find(t=>t.row.taskId==='transient');assert.ok(task);assert.equal(task.status,'failed');assert.match(task.error,/已离开授权节点/);assert.equal(f.store.get('execution-scans','c1').rowCount,0);assert.equal(f.store.all('execution-discovery-runs').filter(r=>r.status==='pending').length,0);});
|
||||
@@ -0,0 +1,50 @@
|
||||
'use strict';
|
||||
const test=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs/promises'),path=require('node:path');
|
||||
const {loadPlaywright,browserOptions}=require('../../src/platform/browser.cjs');
|
||||
async function setup(t,role='admin',legacy=false,noSampleReference=false){
|
||||
const browser=await loadPlaywright().chromium.launch(browserOptions());t.after(()=>browser.close());const page=await browser.newPage({viewport:{width:1200,height:1000}});page.setDefaultTimeout(5000);await page.setContent('<main id="root"></main><div id="notice"></div>');
|
||||
for(const file of ['navigation/lifecycle.js','field-mappings/sample-picker.js','field-mappings/recognition-panel.js','field-mappings/view.js'])await page.addScriptTag({content:await fs.readFile(path.resolve('web/modules',file),'utf8')});
|
||||
await page.addStyleTag({content:await fs.readFile(path.resolve('web/modules/field-mappings/view.css'),'utf8')});
|
||||
await page.evaluate(async({role,legacy,noSampleReference})=>{
|
||||
window.calls=[];window.active=true;window.failRefresh=false;window.deferSave=false;let sequence=0;
|
||||
const sample={id:'s1',processName:'真实流程',processVersion:'2.0',sample:{title:'订单号:TITLE-1 客户简称:标题客户',taskId:'T1',serialNum:'SER1',nodeName:'通知节点',receivedAt:'2026-10-20T01:00:00Z'},snapshot:{fields:[{path:'form.order',label:'订单号',value:'FORM-1'},{path:'form.qty',label:'数量',value:0},{path:'form.amount',label:'金额',value:500},{path:'form.other',label:'备注',value:'特殊值'},{path:'form.second',label:'主订单号',value:'SECOND'}]}};
|
||||
const directory={samples:[sample],adapters:[],processes:[{processName:'真实流程',categories:[{id:'cat',name:'真实分类',filenameDate:'appDate'}],versions:[{processVersion:'2.0',sampleCount:1,sampleIds:['s1'],status:'待配置'},{processVersion:'3.0',sampleCount:0,sampleIds:[],status:'未采集'}]}]};
|
||||
if(role!=='admin')Object.assign(directory.processes[0].versions[0],{status:'已核验',active:{id:'active1',version:4,sampleId:'s1',sources:{orderNo:{type:'form',path:'form.order'},brief:{type:'title'},processName:{type:'metadata',key:'processName'}}}});
|
||||
if(legacy)Object.assign(directory.processes[0].versions[0],{status:'已核验',active:{id:'legacy1',version:9,sampleId:'s1',fields:{orderNo:'form.order',quantity:'form.qty',brief:'form.other'}}});
|
||||
if(noSampleReference){directory.samples=[];Object.assign(directory.processes[0].versions[0],{status:'未采集',sampleCount:0,sampleIds:[],reference:{id:'ref1',reference:true,fields:{orderNo:'form.order',quantity:'form.qty'}}});}
|
||||
const api=async(url,body)=>{calls.push({url,body});if(url.startsWith('/order-rules/field-samples/catalog'))return {items:[],nextCursor:null};if(url.endsWith('/propose')){const item=directory.samples.find(s=>s.id===body.sampleId),version=directory.processes[0].versions.find(v=>v.processVersion===item.processVersion),chosen=version.draft||version.active,source=body.sources||chosen?.sources||(chosen?.fields?Object.fromEntries(Object.entries(chosen.fields).filter(([k])=>k!=='brief').map(([k,path])=>[k,{type:'form',path}])):{quantity:{type:'form',path:'form.qty'}});source.brief={type:'title'};return {sampleId:item.id,evidenceHash:'evidence-'+item.id,mapping:{basis:chosen?'draft':'recommended',sources:source},fields:[{key:'orderNo',label:'主订单号',state:source.orderNo?'recognized':'ambiguous',value:source.orderNo?'FORM-1':null,candidates:[{path:'form.order',label:'订单号',value:'FORM-1'},{path:'form.second',label:'主订单号',value:'SECOND'}]}],recognition:{event:{brief:'TITLE-1'},valid:false},blockedReasons:[],warnings:[]};} if(url==='/workspace')return {connections:[{id:'c1',name:'我的连接'}]};if(url.split('?')[0]==='/order-rules/fields'){if(window.deferRefresh)await new Promise(r=>window.releaseRefresh=r);if(failRefresh)throw Error('刷新断线');return structuredClone(directory);}if(url.endsWith('/draft')){const saved={...body,id:'mapping-1',version:++sequence,status:'draft',check:null};directory.processes[0].versions[0].draft=saved;if(deferSave)await new Promise(r=>window.releaseSave=r);return saved;}if(url.endsWith('/check'))return {id:'check-1',evidenceHash:'evidence-'+body.sampleId,valid:true,version:body.version,sampleId:body.sampleId,result:{event:{orderNo:'FORM-1',mainOrder:'FORM-1',brief:'订单号:TITLE-1',titleOrders:[{orderNo:'TITLE-1'}]},issues:[],checks:[{label:'订单号',ok:true,detail:'有效'}],filenames:[{categoryId:'cat',categoryName:'真实分类',filename:'FORM-1_20261020_SER1.pdf',issues:[]}],affectedCategories:[{id:'cat',name:'真实分类'}]}};if(url.endsWith('/activate'))return {...directory.processes[0].versions[0].draft,activeVersion:body.version,status:'active'};if(url.endsWith('/field-samples/list')&&window.failList)throw Object.assign(Error('列表读取失败'),{status:502});if(url.endsWith('/field-samples/list')&&window.uncertainList)throw Object.assign(Error('结果待核实'),{outcome:'uncertain'});if(url.endsWith('/field-samples/list'))return {id:'list-1',rows:[{id:'row-1',taskId:'T2',serialNum:'SER2',processName:'真实流程',processVersion:'3.0',nodeName:'通知节点',title:'订单号:NEW-2'}]};if(url.endsWith('/field-samples/capture')){if(window.failCapture)throw Object.assign(Error('采集断线'),{status:502});const captured={...structuredClone(sample),id:'s2',processVersion:'3.0',sample:{...sample.sample,title:'订单号:NEW-2',serialNum:'SER2'}};directory.samples.push(captured);Object.assign(directory.processes[0].versions[1],{sampleCount:1,sampleIds:['s2']});return captured;}throw Error('unexpected '+url);};
|
||||
PageLifecycle.attach(document.querySelector('#root'));window.controller=await FieldMappingViews.render(document.querySelector('#root'),{api,esc:v=>String(v??'').replaceAll('&','&').replaceAll('<','<').replaceAll('"','"'),formatDate:v=>v||'—',user:{role},isActive:()=>active,feedback:(m,type)=>document.querySelector('#notice').textContent=m});PageLifecycle.bind();
|
||||
},{role,legacy,noSampleReference});if(!noSampleReference)await page.waitForFunction(()=>document.querySelector('#fm-recognition')?.textContent.includes('当前订单识别结果'));await page.locator('#fm-manual').evaluate(e=>e.open=true);return page;
|
||||
}
|
||||
test('field mapping keeps no-sample versions visible, searches field values and never guesses quantity from amount',async t=>{
|
||||
const page=await setup(t);assert.match(await page.locator('#root').innerText(),/3.0/);assert.match(await page.locator('#root').innerText(),/真实分类/);await page.locator('#fm-orderNo').selectOption('form.order');assert.equal(await page.getByText('同名候选,尚未确认:FORM-1',{exact:true}).isVisible(),false);await page.locator('#fm-orderNo').selectOption('');await page.locator('#fm-search-orderNo').fill('特殊值');assert.equal(await page.locator('#fm-orderNo option[value="form.other"]').count(),1);assert.equal(await page.locator('#fm-orderNo option[value="form.order"]').count(),0);assert.equal(await page.locator('#fm-quantity').inputValue(),'form.qty');assert.equal(await page.locator('#fm-totalAmount').inputValue(),'');
|
||||
await page.locator('[data-fm-version="1"]').click();assert.match(await page.locator('#fm-editor').innerText(),/尚无真实样本/);await page.setViewportSize({width:390,height:844});assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true);
|
||||
});
|
||||
|
||||
test('reference paths without a real sample never count as configured fields',async t=>{
|
||||
const page=await setup(t,'admin',false,true);assert.match(await page.locator('#fm-editor').innerText(),/可选业务信息 · 0 项已对应/);assert.match(await page.locator('#fm-version-state').innerText(),/有参考配置,尚未核验/);assert.equal(await page.locator('#fm-save').isDisabled(),true);
|
||||
});
|
||||
test('save baseline stays clean after refresh failure and activation needs a fresh version check plus category confirmation',async t=>{
|
||||
const page=await setup(t);await page.locator('#fm-orderNo').selectOption('form.order');await page.getByText(/可选业务信息 ·/).evaluate(e=>e.parentElement.open=true);await page.locator('#fm-quantity').selectOption('form.qty');await page.evaluate(()=>failRefresh=true);await page.getByRole('button',{name:'保存草稿',exact:true}).click();await page.getByText(/刷新失败/).waitFor();assert.equal(await page.evaluate(()=>PageLifecycle.dirty()),false);assert.equal(await page.locator('#fm-orderNo').inputValue(),'form.order');
|
||||
const draft=await page.evaluate(()=>calls.find(c=>c.url.endsWith('/draft')).body);assert.deepEqual(draft.sources,{orderNo:{type:'form',path:'form.order'},brief:{type:'title'},quantity:{type:'form',path:'form.qty'}});assert.equal(draft.version,0);assert.equal(await page.locator('#fm-activate').isDisabled(),true);
|
||||
await page.getByRole('button',{name:'检查识别结果',exact:true}).click();await page.getByText('FORM-1_20261020_SER1.pdf',{exact:true}).waitFor();assert.match(await page.locator('#fm-result').innerText(),/TITLE-1/);await page.getByRole('button',{name:'检查识别结果',exact:true}).click();const checkKeys=await page.evaluate(()=>calls.filter(c=>c.url.endsWith('/check')).map(c=>c.body.idempotencyKey));assert.notEqual(checkKeys[0],checkKeys[1]);assert.equal(await page.locator('#fm-activate').isDisabled(),true);await page.locator('#fm-confirm').check();await page.locator('#fm-activate').click();await page.getByText(/字段对应已确认生效/).waitFor();assert.equal(await page.evaluate(()=>calls.filter(c=>c.url.endsWith('/activate')).length),1);
|
||||
await page.locator('#fm-quantity').selectOption('');assert.equal(await page.locator('#fm-activate').isDisabled(),true);assert.equal(await page.evaluate(()=>PageLifecycle.dirty()),true);
|
||||
});
|
||||
test('dirty switching is guarded and a pending save locks edits while a late response never refreshes a departed page',async t=>{
|
||||
const page=await setup(t);await page.locator('#fm-orderNo').selectOption('form.order');await page.locator('[data-fm-version="1"]').click();await page.getByRole('button',{name:'留在此页',exact:true}).click();assert.equal(await page.locator('#fm-orderNo').inputValue(),'form.order');await page.evaluate(()=>deferSave=true);await page.getByRole('button',{name:'保存草稿',exact:true}).click();await page.waitForFunction(()=>typeof releaseSave==='function');assert.equal(await page.locator('#fm-orderNo').isDisabled(),true);assert.equal(await page.locator('[data-fm-version="1"]').isDisabled(),true);await page.evaluate(()=>{active=false;releaseSave();});await page.waitForTimeout(50);assert.equal(await page.evaluate(()=>calls.filter(c=>c.url.startsWith('/order-rules/fields')).length),1);assert.equal(await page.locator('#notice').innerText(),'');
|
||||
});
|
||||
for(const role of ['operator','viewer'])test(role+' sees readonly bindings and never reads connection permissions or posts sample actions',async t=>{
|
||||
const page=await setup(t,role);assert.equal(await page.locator('#fm-orderNo').isDisabled(),true);assert.equal(await page.locator('#fm-orderNo').inputValue(),'form.order');assert.match(await page.locator('#fm-version-state').innerText(),/生效 v4/);assert.equal(await page.getByRole('button',{name:'保存草稿',exact:true}).count(),0);assert.equal(await page.evaluate(()=>calls.some(c=>c.url==='/workspace'||c.body&&!c.url.endsWith('/propose'))),false);
|
||||
});
|
||||
test('sample capture uses listed row identity, guards dirty input, and can fetch a new list after successful reads',async t=>{
|
||||
const page=await setup(t);await page.locator('#fm-orderNo').selectOption('form.order');await page.getByText('从 BPM 选择',{exact:true}).click();await page.locator('[data-picker=connection]').selectOption('c1');await page.getByRole('button',{name:'读取待办列表',exact:true}).click();await page.locator('[data-picker-capture]').waitFor();await page.getByRole('button',{name:'读取待办列表',exact:true}).click();await page.waitForFunction(()=>calls.filter(c=>c.url.endsWith('/field-samples/list')).length===2);const keys=await page.evaluate(()=>calls.filter(c=>c.url.endsWith('/field-samples/list')).map(c=>c.body.idempotencyKey));assert.notEqual(keys[0],keys[1]);await page.evaluate(()=>window.failCapture=true);await page.locator('[data-picker-capture]').click();await page.getByRole('button',{name:'放弃并继续',exact:true}).click();await page.getByText('采集断线',{exact:true}).waitFor();assert.equal(await page.locator('#fm-orderNo').inputValue(),'form.order');await page.evaluate(()=>window.failCapture=false);await page.locator('[data-picker-capture]').click();await page.getByRole('button',{name:'放弃并继续',exact:true}).click();await page.waitForFunction(()=>document.querySelector('#fm-sample')?.value==='s2');assert.equal(await page.locator('#fm-sample').inputValue(),'s2');const body=await page.evaluate(()=>calls.find(c=>c.url.endsWith('/field-samples/capture')).body);assert.equal(body.connectionId,'c1');assert.equal(body.listId,'list-1');assert.equal(body.rowId,'row-1');const captureKeys=await page.evaluate(()=>calls.filter(c=>c.url.endsWith('/field-samples/capture')).map(c=>c.body.idempotencyKey));assert.notEqual(captureKeys[0],captureKeys[1]);assert.equal(await page.evaluate(()=>calls.some(c=>/order-execution|adapters|pdf|mail/.test(c.url))),false);
|
||||
});
|
||||
|
||||
test('a definite sample-list failure can be retried with a new key while an uncertain attempt retains its key',async t=>{
|
||||
const page=await setup(t);await page.getByText('从 BPM 选择',{exact:true}).click();await page.locator('[data-picker=connection]').selectOption('c1');await page.evaluate(()=>window.failList=true);await page.getByRole('button',{name:'读取待办列表',exact:true}).click();await page.getByText('列表读取失败',{exact:true}).waitFor();await page.evaluate(()=>{window.failList=false;window.uncertainList=true;});await page.getByRole('button',{name:'读取待办列表',exact:true}).click();await page.getByText('结果待核实',{exact:true}).waitFor();await page.evaluate(()=>window.uncertainList=false);await page.getByRole('button',{name:'读取待办列表',exact:true}).click();await page.locator('[data-picker-capture]').waitFor();const keys=await page.evaluate(()=>calls.filter(c=>c.url.endsWith('/field-samples/list')).map(c=>c.body.idempotencyKey));assert.notEqual(keys[0],keys[1]);assert.equal(keys[1],keys[2]);
|
||||
});
|
||||
test('legacy active-only mappings load field paths and start an independent draft revision that survives refresh failures',async t=>{
|
||||
const page=await setup(t,'admin',true);assert.equal(await page.locator('#fm-orderNo').inputValue(),'form.order');assert.equal(await page.locator('#fm-quantity').inputValue(),'form.qty');assert.match(await page.locator('#fm-version-state').innerText(),/生效 v9/);assert.equal(await page.locator('#fm-check').isDisabled(),true);await page.evaluate(()=>window.failRefresh=true);await page.getByRole('button',{name:'保存草稿',exact:true}).click();await page.getByText(/刷新失败/).waitFor();assert.equal(await page.evaluate(()=>PageLifecycle.dirty()),false);await page.locator('[data-fm-version="1"]').click();await page.locator('[data-fm-version="0"]').click();await page.locator('#fm-manual').evaluate(e=>e.open=true);await page.locator('#fm-quantity').selectOption('');await page.getByRole('button',{name:'保存草稿',exact:true}).click();await page.waitForFunction(()=>calls.filter(c=>c.url.endsWith('/draft')).length===2&&!document.querySelector('#fm-save').disabled);const writes=await page.evaluate(()=>calls.filter(c=>c.url.endsWith('/draft')).map(c=>c.body));assert.deepEqual(writes.map(body=>body.version),[0,1]);assert.deepEqual(writes[0].sources,{brief:{type:'title'},orderNo:{type:'form',path:'form.order'},quantity:{type:'form',path:'form.qty'}});assert.equal(await page.evaluate(()=>PageLifecycle.dirty()),false);assert.match(await page.locator('#fm-version-state').innerText(),/草稿 v2/);
|
||||
});
|
||||
|
||||
test('directory refresh locks edits until its response is applied',async t=>{const page=await setup(t,'admin',true);await page.evaluate(()=>window.deferRefresh=true);await page.getByRole('button',{name:'刷新目录',exact:true}).click();await page.waitForFunction(()=>typeof releaseRefresh==='function');assert.equal(await page.locator('#fm-orderNo').isDisabled(),true);assert.equal(await page.locator('[data-fm-version="1"]').isDisabled(),true);await page.evaluate(()=>releaseRefresh());await page.waitForFunction(()=>!document.querySelector('#fm-refresh').disabled);assert.equal(await page.locator('#fm-orderNo').isDisabled(),false);assert.equal(await page.locator('#fm-orderNo').inputValue(),'form.order');});
|
||||
@@ -0,0 +1,17 @@
|
||||
'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 admin={username:'admin',role:'admin'};
|
||||
function fixture(t){const dir=fs.mkdtempSync(path.join(os.tmpdir(),'mapping-domain-'));const store=new RuleStore(dir,{clock:()=>new Date('2026-10-20T02:00:00Z')});t.after(()=>{store.close();fs.rmSync(dir,{recursive:true,force:true});});const sample={source:'todo',connectionId:'c1',instanceId:'i1',taskId:'t1',revision:1,processName:'备损订单更改评审',processVersion:'1.4',nodeName:'订单专员(订单通知书)',receivedAt:'2026-10-20T01:00:00Z',serialNum:'S-1',title:'客户等级:C毛利:绿标订单号:148396机芯号:X客户简称:客户总数量:0订单号:HA148396客户简称:惠州总数量:5000',fields:{number:'148396',count:'0',date:'2026-10-20',amount:'100'}};const capture=s=>store.recordCapture({sample:s,snapshot:{processVersion:s.processVersion,fields:Object.entries(s.fields).map(([path,value])=>({path,value,label:({number:'订单号',count:'数量',amount:'总金额',date:'申请日期'})[path]||path}))},taskId:s.taskId});return {store,sample,capture,captured:capture(sample)};}
|
||||
const input=f=>({processName:f.sample.processName,processVersion:f.sample.processVersion,sampleId:f.captured.id,version:0,sources:{orderNo:{type:'form',path:'number'},brief:{type:'title'},quantity:{type:'form',path:'count'}},idempotencyKey:'save-1'});
|
||||
function checked(f,draft){return f.store.checkMapping({id:draft.id,version:draft.version,sampleId:f.captured.id,idempotencyKey:'check-'+draft.version},admin);}
|
||||
test('mapping drafts require server check then activation; main order and all title orders use one engine',t=>{const f=fixture(t),before=f.store.adapters(),draft=f.store.saveMapping(input(f),admin);assert.deepEqual(f.store.adapters(),before);assert.deepEqual(f.store.saveMapping(input(f),admin),draft);assert.throws(()=>f.store.activateMapping({id:draft.id,version:1,checkId:'invented',idempotencyKey:'bad'},admin),/检查/);const check=checked(f,draft);assert.equal(check.valid,true);assert.equal(check.result.event.orderNo,'148396');assert.equal(check.result.event.quantity,0);assert.equal(check.result.event.titleOrders.length,2);assert.match(check.result.event.brief,/HA148396/);const active=f.store.activateMapping({id:draft.id,version:1,checkId:check.id,idempotencyKey:'activate-1'},admin);assert.equal(active.activeVersion,1);assert.equal(f.store.adapters().filter(a=>a.processName===f.sample.processName&&a.processVersion==='1.4').length,1);assert.equal(f.store.adapters().find(a=>a.id===draft.id).reference,false);assert.equal(f.store.settings().enabled,false);f.capture({...f.sample,processVersion:'1.5',taskId:'new-version'});assert.equal(f.store.fields().processes.find(p=>p.processName===f.sample.processName).versions.find(v=>v.processVersion==='1.5').status,'版本变化');const next=f.store.saveMapping({...input(f),version:1,idempotencyKey:'save-2'},admin);assert.equal(next.check,null);assert.equal(f.store.adapters().find(a=>a.id===draft.id).version,1);assert.throws(()=>f.store.activateMapping({id:draft.id,version:2,checkId:check.id,idempotencyKey:'activate-stale'},admin),/检查/);});
|
||||
test('checks reject title conflicts, invalid dates and wrong typed source without changing active configuration',t=>{const f=fixture(t);const rule=f.store.get('rules','bs-change');rule.draft.filenameDate='appDate';f.store.put('rules',rule);const bad={...f.sample,taskId:'bad',fields:{...f.sample.fields,number:'OTHER',date:'2026-02-30'}};const capture=f.capture(bad),draft=f.store.saveMapping({...input(f),sampleId:capture.id,sources:{...input(f).sources,appDate:{type:'form',path:'date'}}},admin);const check=f.store.checkMapping({id:draft.id,version:1,sampleId:capture.id,idempotencyKey:'check'},admin);assert.equal(check.valid,false);assert.match(check.result.issues.join(';'),/主订单号|标题/);assert.match(check.result.issues.join(';'),/日期/);assert.throws(()=>f.store.saveMapping({...input(f),version:1,idempotencyKey:'source-bad',sources:{...input(f).sources,orderNo:{type:'metadata',key:'taskId'}}},admin),/主订单号|表单/);assert.throws(()=>f.store.saveMapping({...input(f),version:1,idempotencyKey:'unknown-path',sources:{...input(f).sources,quantity:{type:'form',path:'invented'}}},admin),/字段/);assert.throws(()=>f.store.saveMapping(input(f),{username:'reader',role:'viewer'}),{status:403});assert.throws(()=>f.store.saveMapping({...input(f),idempotencyKey:'save-1',sources:{}},admin),{status:409});});
|
||||
test('activation pauses affected publications, invalidates evidence, preserves frozen batches and persists drafts',t=>{const f=fixture(t),draft=f.store.saveMapping(input(f),admin),check=checked(f,draft);f.store.activateMapping({id:draft.id,version:1,checkId:check.id,idempotencyKey:'a1'},admin);let r=f.store.get('rules','bs-change');r.draft.adapterIds=[draft.id];r.published={...r.draft,status:'enabled'};r.trialVersion=r.draft.version;r.trialSampleId=f.captured.id;f.store.put('rules',r);const frozen={id:'frozen',status:'prepared',version:1,ruleSnapshot:structuredClone(r.published),text:'frozen'};f.store.put('batches',frozen);const d2=f.store.saveMapping({...input(f),version:1,idempotencyKey:'s2'},admin);assert.equal(f.store.get('rules','bs-change').published.status,'enabled');const c2=checked(f,d2);f.store.activateMapping({id:d2.id,version:2,checkId:c2.id,idempotencyKey:'a2'},admin);r=f.store.get('rules','bs-change');assert.equal(r.published.status,'paused');assert.equal(r.trialVersion,null);assert.match(r.mappingIssue,/重新检查/);assert.deepEqual(f.store.get('batches','frozen'),frozen);const directory=f.store.fields();assert.ok(directory.processes.some(p=>p.versions.some(v=>v.status==='未采集')));assert.equal(directory.processes.find(p=>p.processName===f.sample.processName).versions.find(v=>v.processVersion==='1.4').active.version,2);});
|
||||
test('legacy adapter write creates an unverified draft and cannot bypass confirmation',t=>{const f=fixture(t),old=f.store.adapters();const draft=f.store.saveAdapter({sampleId:f.captured.id,processName:f.sample.processName,processVersion:'1.4',fields:{orderNo:'number'}},admin);assert.equal(draft.status,'draft');assert.notEqual(draft.verified,true);assert.deepEqual(f.store.adapters(),old);});
|
||||
|
||||
test('real orders cannot use reference adapters or form summaries as title evidence',t=>{const f=fixture(t),reference=require('../../src/modules/order-rules/catalog.cjs').adapters.find(a=>a.id==='bs-change'),sample={...reference.sample,demo:false};assert.equal(f.store.preview(sample).valid,false);const draft=f.store.get('rules','bs-change').draft;assert.ok(require('../../src/modules/order-rules/validation.cjs').publicationIssues(draft,f.store.adapters()).some(x=>/核验/.test(x)));assert.throws(()=>f.store.saveMapping({...input(f),sources:{orderNo:{type:'form',path:'number'},brief:{type:'form',path:'date'}}},admin),/标题/);const missing=f.capture({...f.sample,title:undefined,brief:'订单号:148396',taskId:'missing-title'}),d=f.store.saveMapping({...input(f),sampleId:missing.id},admin),check=f.store.checkMapping({id:d.id,version:d.version,sampleId:missing.id,idempotencyKey:'missing-title-check'},admin);assert.equal(check.valid,false);});
|
||||
|
||||
test('activating replaces duplicate legacy mappings for the same version and keeps history',t=>{const f=fixture(t);for(const id of ['old-a','old-b'])f.store.put('field-adapters',{id,processName:f.sample.processName,processVersion:'1.4',fields:{orderNo:'number'},verified:true,version:1});assert.equal(f.store.adapters().some(a=>a.verified&&a.processName===f.sample.processName),false);assert.match(f.store.fields().processes.find(p=>p.processName===f.sample.processName).versions.find(v=>v.processVersion==='1.4').issues.join(';'),/重复映射/);const draft=f.store.saveMapping(input(f),admin),check=checked(f,draft);f.store.activateMapping({id:draft.id,version:1,checkId:check.id,idempotencyKey:'unique'},admin);const active=f.store.adapters().filter(a=>a.processName===f.sample.processName&&a.processVersion==='1.4');assert.deepEqual(active.map(a=>a.id),[draft.id]);assert.deepEqual(f.store.get('rules','bs-change').draft.adapterIds,[draft.id]);assert.equal(f.store.all('field-mapping-history').length,2);assert.equal(f.store.get('field-adapters','old-a').status,'superseded');});
|
||||
|
||||
test('checks bind category context and chosen field availability; concurrent drafts cannot overwrite',t=>{const f=fixture(t),draft=f.store.saveMapping(input(f),admin);assert.throws(()=>f.store.saveMapping({...input(f),idempotencyKey:'concurrent'},admin),{status:409});assert.throws(()=>f.store.saveMapping({...input(f),version:1,idempotencyKey:'ambiguous-amount',sources:{...input(f).sources,totalAmount:{type:'form',path:'count'}}},admin),/数量和总金额/);assert.throws(()=>f.store.saveMapping({...input(f),version:1,idempotencyKey:'amount-as-count',sources:{...input(f).sources,quantity:{type:'form',path:'amount'}}},admin),/数量和总金额/);const missing={...f.sample,taskId:'no-count',fields:{number:'148396'}};const captured=f.capture(missing),bad=f.store.checkMapping({id:draft.id,version:1,sampleId:captured.id,idempotencyKey:'missing-source'},admin);assert.equal(bad.valid,false);assert.match(bad.result.issues.join(';'),/来源字段不存在/);const check=checked(f,draft),record=f.store.get('rules','bs-change');record.draft.filenameDate='appDate';f.store.put('rules',record);assert.throws(()=>f.store.activateMapping({id:draft.id,version:1,checkId:check.id,idempotencyKey:'expired-context'},admin),{status:409});});
|
||||
@@ -0,0 +1,111 @@
|
||||
'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 {orderExecutionApi}=require('../../src/modules/order-execution/api.cjs');
|
||||
const admin={username:'admin',role:'admin'},principal={user:admin,sessionId:'sample-session'};
|
||||
function fixture(t){
|
||||
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'field-samples-'));let now=new Date('2026-10-20T02:00:00Z');
|
||||
const store=new RuleStore(dir,{clock:()=>now});t.after(()=>{store.close();fs.rmSync(dir,{recursive:true,force:true});});
|
||||
const connection={id:'c1',owner:'admin',status:'connected'},workspace={getConnection:id=>{assert.equal(id,connection.id);return connection;},snapshot:()=>({connections:[connection]})};
|
||||
const row={source:'todo',instanceId:'i1',taskId:'t1',revision:'1',processName:'备损订单更改评审',nodeName:'订单专员(订单通知书)',processVersion:'1.4',receivedAt:'2026-10-20T01:00:00Z',serialNum:'S1',title:'真实订单',detailUrl:'https://bpm.example.test/private'};
|
||||
let scans=0,captures=0,rows=[row];const provider={scan:async()=>{scans++;return structuredClone(rows);},capture:async(c,p,r)=>{captures++;return {sample:{...r,connectionId:c.id,fields:{order:'SO-1',brief:'实际摘要'}},snapshot:{processVersion:r.processVersion,html:'SECRET SNAPSHOT',fields:[{path:'order',value:'SO-1'},{path:'brief',value:'实际摘要'}]}};}};
|
||||
const forbidden=()=>{throw Error('forbidden execution side effect');};const execution=new OrderExecutionCoordinator({store,workspace,provider,archive:{archive:forbidden},mail:{send:forbidden},clock:()=>now});execution.execute=forbidden;store.ingest=forbidden;store.recordArchive=forbidden;
|
||||
return {store,execution,provider,row,connection,dir,setNow:v=>{now=new Date(v);},setRows:v=>{rows=v;},counts:()=>({scans,captures})};
|
||||
}
|
||||
const list=f=>f.execution.listFieldSamples({connectionId:'c1',idempotencyKey:'list'},principal);
|
||||
const capture=(f,l,key='capture')=>f.execution.captureFieldSample({connectionId:'c1',listId:l.id,rowId:l.rows[0].id,idempotencyKey:key},principal);
|
||||
|
||||
test('configuration-only discovery can sample older pending tasks without executing historical orders',async t=>{
|
||||
const f=fixture(t);f.setRows([{...f.row,receivedAt:'2026-10-01T01:00:00Z'}, {...f.row,taskId:'wrong',nodeName:'其他节点'}]);
|
||||
const l=await f.execution.listFieldSamples({connectionId:'c1',scope:'configuration',idempotencyKey:'config-list'},principal);
|
||||
assert.equal(l.rows.length,2);assert.equal(l.scope,'configuration');
|
||||
const captured=await capture(f,l);assert.equal(captured.sample.taskId,'t1');
|
||||
for(const kind of ['execution-tasks','orders','batches'])assert.deepEqual(f.store.all(kind),[]);
|
||||
await assert.rejects(f.execution.listFieldSamples({connectionId:'c1',scope:'all-history',idempotencyKey:'bad'},principal),e=>e.status===400);
|
||||
await assert.rejects(f.execution.listFieldSamples({connectionId:'c1',idempotencyKey:'config-list'},principal),e=>e.status===409);
|
||||
});
|
||||
|
||||
test('history sampling keeps its source, rechecks the selected process and rejects changed or expired evidence',async t=>{
|
||||
for(const mode of ['valid','changed','expired']){
|
||||
const f=fixture(t),row={...f.row,source:'history',configurationOnly:true,timestampType:'process-start',nodeName:'历史查看(未提供办理节点)',receivedAt:'2025-10-01T01:00:00Z'};
|
||||
let historyCalls=0,fieldCalls=0;f.provider.scan=async()=>{throw Error('history must not use todo discovery');};
|
||||
f.provider.scanHistory=async(c,p,names)=>{historyCalls++;if(historyCalls>1)assert.deepEqual(names,[row.processName]);return [{...row,...(mode==='changed'&&historyCalls>1?{processVersion:'9.9'}:{})}];};
|
||||
f.provider.captureFields=async(c,p,r)=>{fieldCalls++;return {sample:{...r,connectionId:c.id,fields:{order:'SO-1'}},snapshot:{purpose:'field-mapping',processVersion:r.processVersion,fields:[{path:'order',value:'SO-1'}]}};};
|
||||
const listing=await f.execution.listFieldSamples({connectionId:'c1',scope:'history',idempotencyKey:'history'},principal);
|
||||
if(mode==='expired')f.setNow('2026-10-20T02:15:00Z');
|
||||
if(mode!=='valid'){await assert.rejects(capture(f,listing),e=>e.status===409);assert.equal(fieldCalls,0);assert.equal(f.store.all('capture-samples').length,0);continue;}
|
||||
const saved=await capture(f,listing);assert.equal(saved.sample.source,'history');assert.equal(saved.sample.configurationOnly,true);assert.equal(saved.sample.timestampType,'process-start');assert.equal(fieldCalls,1);assert.equal(f.counts().captures,0);
|
||||
for(const kind of ['execution-tasks','orders','batches'])assert.deepEqual(f.store.all(kind),[]);
|
||||
}
|
||||
});
|
||||
test('sample discovery filters historical, future, wrong scope and non-todo rows without execution writes',async t=>{
|
||||
const f=fixture(t),before=f.store.capabilities;
|
||||
f.setRows([f.row,{...f.row,taskId:'lower',receivedAt:f.store.snapshot().window.start},{...f.row,taskId:'now',receivedAt:'2026-10-20T02:00:00Z'},{...f.row,taskId:'old',receivedAt:'2026-10-18T01:00:00Z'},{...f.row,taskId:'future',receivedAt:'2026-10-20T02:00:01Z'},{...f.row,taskId:'wrong',nodeName:'其他节点'},{...f.row,taskId:'history',source:'history'},{...f.row,taskId:'invalid',receivedAt:'invalid'}]);
|
||||
const l=await list(f);assert.equal(l.rows.length,3);assert.equal(l.window.end,'2026-10-20T02:00:00.000Z');assert.equal(l.window.endInclusive,true);assert.equal(l.rows[0].taskId,'t1');assert.equal(l.rows[0].detailUrl,undefined);
|
||||
const result=await capture(f,l);assert.equal(result.provenance,'server-provider');assert.equal(result.snapshot,undefined);assert.equal(result.fields.length,2);assert.equal(JSON.stringify(result).includes('SECRET SNAPSHOT'),false);
|
||||
for(const kind of ['execution-tasks','execution-scans','execution-requests','orders','batches'])assert.deepEqual(f.store.all(kind),[]);
|
||||
assert.equal(f.store.activeDiscoveries,0);assert.deepEqual(f.store.capabilities,before);assert.equal(f.store.all('capture-samples').length,1);
|
||||
for(const name of ['rules.sqlite','rules.sqlite-wal']){const file=path.join(f.dir,name);if(fs.existsSync(file))assert.equal(fs.readFileSync(file).includes(Buffer.from('真实订单')),false);}
|
||||
});
|
||||
test('concurrent identical keys are idempotent and a reused key cannot change request body',async t=>{
|
||||
const f=fixture(t),[a,b]=await Promise.all([list(f),list(f)]);assert.deepEqual(a,b);assert.equal(f.counts().scans,1);
|
||||
const [x,y]=await Promise.all([capture(f,a),capture(f,a)]);assert.deepEqual(x,y);assert.deepEqual(f.counts(),{scans:2,captures:1});
|
||||
await assert.rejects(f.execution.captureFieldSample({connectionId:'c1',listId:a.id,rowId:'other',idempotencyKey:'capture'},principal),e=>e.status===409);
|
||||
});
|
||||
test('sample ownership, authenticated admin role, expiry and disabled connection are enforced',async t=>{
|
||||
const f=fixture(t);await assert.rejects(f.execution.listFieldSamples({connectionId:'c1',idempotencyKey:'anon'},{user:admin}),e=>e.status===401);
|
||||
await assert.rejects(f.execution.listFieldSamples({connectionId:'c1',idempotencyKey:'operator'},{user:{username:'admin',role:'operator'},sessionId:'sample-session'}),e=>e.status===403);
|
||||
const l=await list(f);
|
||||
await assert.rejects(f.execution.captureFieldSample({connectionId:'c1',listId:l.id,rowId:l.rows[0].id,idempotencyKey:'other-session'},{...principal,sessionId:'other'}),e=>e.status===403);
|
||||
f.setNow('2026-10-20T02:15:00Z');await assert.rejects(capture(f,l),e=>e.status===409);assert.equal(f.counts().captures,0);
|
||||
f.connection.status='disabled';await assert.rejects(list(f),e=>e.status===409);
|
||||
});
|
||||
test('changed node, version, revision or received timestamp fails before capture',async t=>{
|
||||
for(const [key,value]of Object.entries({nodeName:'other',processVersion:'2',revision:'2',receivedAt:'2026-10-20T01:01:00Z'})){
|
||||
const f=fixture(t),l=await list(f);f.setRows([{...f.row,[key]:value}]);await assert.rejects(capture(f,l),e=>e.status===409);assert.equal(f.counts().captures,0);assert.equal(f.store.all('capture-samples').length,0);
|
||||
}
|
||||
});
|
||||
test('capture result version and event identity are checked; failed keys do not retry provider',async t=>{
|
||||
for(const mutate of [r=>{r.sample.revision='changed';},r=>{r.snapshot.processVersion='2';},r=>{r.sample.processVersion=r.snapshot.processVersion='';}]){
|
||||
const f=fixture(t),l=await list(f),original=f.provider.capture;f.provider.capture=async(...args)=>{const result=await original(...args);mutate(result);return result;};
|
||||
await assert.rejects(capture(f,l),e=>e.status===409);await assert.rejects(capture(f,l),e=>e.status===409);assert.equal(f.counts().captures,1);assert.equal(f.store.all('capture-samples').length,0);
|
||||
}
|
||||
});
|
||||
test('post-capture reauthorization and window validation prevent stale evidence commit',async t=>{
|
||||
for(const change of [f=>{f.connection.status='disabled';},f=>{f.connection.owner='other';},f=>{f.setNow('2026-10-20T04:00:00Z');},f=>{f.store.schedule=()=>({times:['09:00','17:00'],weekends:false});}]){
|
||||
const f=fixture(t),l=await list(f),original=f.provider.capture;f.provider.capture=async(...args)=>{const result=await original(...args);change(f);return result;};
|
||||
await assert.rejects(capture(f,l),e=>e.status===409);assert.equal(f.store.all('capture-samples').length,0);
|
||||
}
|
||||
});
|
||||
test('API recognizes admin mapping and sample actions before generic rules routes',async()=>{
|
||||
let reply,called;const args={orderRules:{fields:()=>({samples:[]}),saveMapping:(body,user)=>{called={body,user};return {id:'m'};},checkMapping:()=>({valid:true}),activateMapping:()=>({active:true})},user:admin,sessionId:'s',method:'POST',body:{id:'m'},reply:(status,value)=>{reply={status,value};}};
|
||||
for(const action of ['draft','check','activate']){assert.equal(await orderExecutionApi({...args,route:'/api/order-rules/field-mappings/'+action}),true);assert.equal(reply.status,200);}
|
||||
assert.equal(called.user,admin);
|
||||
await assert.rejects(orderExecutionApi({...args,user:{role:'operator'},route:'/api/order-rules/field-mappings/draft'}),e=>e.status===403);
|
||||
assert.equal(await orderExecutionApi({...args,method:'GET',route:'/api/order-rules/fields'}),true);assert.deepEqual(reply.value,{samples:[]});
|
||||
let body;const execution={listFieldSamples:async input=>{body=input;return {id:'l'};},captureFieldSample:async()=>({id:'s'})};
|
||||
for(const action of ['list','capture']){assert.equal(await orderExecutionApi({...args,execution,body:{connectionId:'c',idempotencyKey:'k',...(action==='capture'?{listId:'l',rowId:'r'}:{})},route:'/api/order-rules/field-samples/'+action}),true);assert.equal(reply.status,200);}
|
||||
assert.equal(body.connectionId,'c');await assert.rejects(orderExecutionApi({...args,execution,body:{connectionId:'c',idempotencyKey:'k',detailUrl:'http://forged'},route:'/api/order-rules/field-samples/list'}),e=>e.status===400);
|
||||
});
|
||||
test('field APIs authorize directory and advanced evidence while paused owned sources remain readable',async t=>{
|
||||
const f=fixture(t),hiddenId='hidden-sample',ownId='own-sample';f.connection.owner='operator';
|
||||
const foreign={id:'c2',owner:'other',status:'connected'};
|
||||
f.execution.workspace.getConnection=id=>id==='c1'?f.connection:foreign;
|
||||
const sample=(id,connectionId)=>({id,processName:f.row.processName,processVersion:'1.4',sample:{connectionId,fields:{value:id==='own-sample'?'OWN FIELD':'SECRET OTHER CONNECTION'}},fields:[{value:id==='own-sample'?'OWN FIELD':'SECRET OTHER CONNECTION'}]});
|
||||
const hidden={id:'hidden-mapping',sampleId:hiddenId,check:{sampleId:hiddenId,result:{fieldTrace:[{value:'SECRET OTHER CONNECTION'}]}}};
|
||||
f.store.fields=()=>({samples:[sample(hiddenId,'c2'),sample(ownId,'c1')],adapters:[{id:'demo',reference:true},{id:'secret-active',sampleId:hiddenId,reference:false}],processes:[{processName:f.row.processName,versions:[{processVersion:'1.4',sampleIds:[hiddenId,ownId],sampleCount:2,draft:hidden,active:{...hidden},reference:{id:'demo'}}]}]});
|
||||
const operator={user:{username:'operator',role:'operator'},sessionId:'operator-session'};
|
||||
async function read(path,who=operator){let value;assert.equal(await orderExecutionApi({execution:f.execution,orderRules:f.store,workspace:f.execution.workspace,...who,url:new URL(path,'http://fixture'),route:path.split('?')[0],method:'GET',reply:(status,result)=>{assert.equal(status,200);value=result;}}),true);return value;}
|
||||
const execution=await read('/api/order-execution');
|
||||
assert.equal(execution.fields.processes,undefined);assert.doesNotMatch(JSON.stringify(execution),/OWN FIELD|SECRET OTHER CONNECTION/);
|
||||
const visible=await read('/api/order-rules/fields?view=directory');
|
||||
assert.doesNotMatch(JSON.stringify(visible),/OWN FIELD|SECRET OTHER CONNECTION/);
|
||||
assert.equal(visible.processes[0].versions[0].sampleCount,1);assert.deepEqual(visible.processes[0].versions[0].sampleIds,[ownId]);assert.equal(visible.processes[0].versions[0].draft,null);assert.equal(visible.processes[0].versions[0].active,null);assert.deepEqual(visible.adapters.map(a=>a.id),['demo']);
|
||||
const advanced=await read('/api/order-rules/fields');assert.match(JSON.stringify(advanced),/OWN FIELD/);assert.doesNotMatch(JSON.stringify(advanced),/SECRET OTHER CONNECTION/);
|
||||
f.connection.status='disabled';foreign.status='disabled';
|
||||
const paused=await read('/api/order-rules/fields');assert.deepEqual(paused.samples.map(s=>s.id),[ownId]);assert.doesNotMatch(JSON.stringify(paused),/SECRET OTHER CONNECTION/);
|
||||
await assert.rejects(f.execution.listFieldSamples({connectionId:'c1',scope:'configuration',idempotencyKey:'paused'},principal),e=>e.status===409);
|
||||
assert.match(JSON.stringify(await read('/api/order-rules/fields',principal)),/SECRET OTHER CONNECTION/);
|
||||
f.connection.owner='new-owner';const transferred=await read('/api/order-rules/fields?view=directory');assert.equal(transferred.samples.length,0);assert.equal(transferred.processes[0].versions[0].sampleCount,0);assert.doesNotMatch(JSON.stringify(transferred),/OWN FIELD|SECRET OTHER CONNECTION/);
|
||||
});
|
||||
@@ -0,0 +1,11 @@
|
||||
'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:['2639266652@qq.com'],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:['2639266652@qq.com']};},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/);});
|
||||
test('R1 empty and completed slots advance to afternoon and next day',async()=>{const {OrderRuleDispatcher}=require('../../src/modules/order-rules/dispatcher.cjs');for(const completed of [false,true]){let now,prepared=[];const store={settings:()=>({enabled:true,channelId:'c'}),snapshot:()=>({capabilities:{liveTodo:true,pdfExport:true,automaticArchive:true},batches:completed?[{status:'sent',cutoff:'2026-10-21T03:00:00Z'}]:[]}),discoveryBlockers:()=>[],prepare:cutoff=>{prepared.push(cutoff);return [];}};const d=new OrderRuleDispatcher({store,mail:{exclusive:async(_,fn)=>fn()},clock:()=>now,settings:()=>({schedule:{times:['11:00','17:00'],weekends:false}}),providersReady:()=>true});for(const time of ['2026-10-21T02:59:59Z','2026-10-21T03:00:00Z','2026-10-21T03:01:30Z','2026-10-21T09:00:00Z','2026-10-22T03:00:00Z']){now=new Date(time);await d.tick();}assert.deepEqual(prepared,['2026-10-21T03:00:00.000Z','2026-10-21T09:00:00.000Z','2026-10-22T03:00:00.000Z']);}});
|
||||
@@ -0,0 +1,45 @@
|
||||
'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 {Store}=require('../../src/modules/dashboard/store.cjs');const {WorkspaceStore}=require('../../src/modules/workspace/store.cjs');
|
||||
const {RuleStore}=require('../../src/modules/order-rules/store.cjs');const {createDashboard}=require('../../src/app/dashboard.cjs');
|
||||
test('rule HTTP authorizes drafts and trials, prevents origin forgery and archive-success claims',async t=>{
|
||||
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'rule-http-')),store=new Store(path.join(dir,'users')),workspace=new WorkspaceStore(path.join(dir,'workspace'));
|
||||
store.bootstrap('admin','Test-password-123');for(const role of ['operator','viewer'])store.addUser({username:role,password:'Test-password-123',role},'admin');
|
||||
const orderRules=new RuleStore(path.join(dir,'rules')),server=createDashboard({store,workspace,orderRules,outputDir:dir});
|
||||
await new Promise(r=>server.listen(0,'127.0.0.1',r));
|
||||
t.after(async()=>{server.closeAllConnections();await new Promise(r=>server.close(r));workspace.close();orderRules.close();fs.rmSync(dir,{recursive:true,force:true});});
|
||||
const base='http://127.0.0.1:'+server.address().port;
|
||||
const call=(route,body,cookie,origin=base)=>fetch(base+'/api'+route,{method:body===undefined?'GET':'POST',headers:{...(body===undefined?{}:{'Content-Type':'application/json',Origin:origin}),...(cookie?{Cookie:cookie}:{})},body:body===undefined?undefined:JSON.stringify(body)});
|
||||
const login=async user=>(await call('/login',{username:user,password:'Test-password-123'})).headers.get('set-cookie').split(';')[0];
|
||||
assert.equal((await call('/order-rules')).status,401);
|
||||
const admin=await login('admin'),operator=await login('operator'),viewer=await login('viewer');
|
||||
const snapshot=await(await call('/order-rules',undefined,viewer)).json();assert.equal(snapshot.rules.length,15);assert.equal(snapshot.settings.enabled,false);
|
||||
const rule=snapshot.rules.find(r=>r.id==='bs-change');
|
||||
assert.equal((await call('/order-rules/rules',rule,operator)).status,403);
|
||||
assert.equal((await call('/order-rules/rules',rule,admin,'https://evil.test')).status,403);
|
||||
assert.equal((await call('/order-rules/rules',rule,admin)).status,200);
|
||||
const sample=snapshot.adapters.find(a=>a.id==='bs-change').sample;
|
||||
assert.equal((await call('/order-rules/preview',{sample},viewer)).status,403);
|
||||
const preview=await(await call('/order-rules/preview',{sample},operator)).json();assert.equal(preview.valid,true);assert.equal(orderRules.snapshot().orders.length,0);
|
||||
assert.equal((await call('/order-rules/orders/not-real/archive',{status:'archived',files:[]},admin)).status,404);
|
||||
assert.equal((await call('/order-rules/settings',{...snapshot.settings,enabled:true,channelId:'fake'},admin)).status,409);
|
||||
assert.equal((await call('/order-rules/events',{sample:{...sample,demo:true}},admin)).status,410);
|
||||
assert.equal((await call('/order-rules/preview',{sample:{...sample,demo:false}},operator)).status,200);
|
||||
assert.equal(orderRules.get('rules','bs-change').trialVersion,null);
|
||||
assert.equal((await call('/order-rules/preview',{sample,ruleId:'untrusted'},operator)).status,400);
|
||||
const current=orderRules.get('rules',rule.id).draft,trialRoute='/order-rules/rules/'+rule.id+'/trial';
|
||||
assert.equal((await call(trialRoute,{version:current.version,draft:current,sample},operator)).status,403);
|
||||
assert.equal((await call(trialRoute,{version:current.version,sample},viewer)).status,403);
|
||||
assert.equal((await call(trialRoute,{version:current.version,sample},admin,'https://evil.test')).status,403);
|
||||
assert.equal((await call(trialRoute,{version:current.version-1,sample},admin)).status,409);
|
||||
assert.equal((await call(trialRoute,{version:current.version,sampleId:{}},admin)).status,400);
|
||||
assert.equal((await call(trialRoute,{version:current.version,sample},operator)).status,200);assert.equal(orderRules.get('rules',rule.id).trialSampleId,null);
|
||||
const members=[{username:'admin',role:'admin'},{username:'operator',role:'operator'}];
|
||||
for(const owner of ['admin','operator']){
|
||||
const connection=workspace.createConnection({name:'隔离连接 '+owner,owner},members[0],members),real={...sample,demo:false,connectionId:connection.id};
|
||||
const captured=orderRules.recordCapture({taskId:owner,sample:real,snapshot:{processVersion:real.processVersion,fields:Object.entries(real.fields).map(([path,value])=>({path,value}))}});
|
||||
assert.equal((await call(trialRoute,{version:current.version,sampleId:captured.id},operator)).status,owner==='admin'?403:200);
|
||||
}
|
||||
const candidate=await(await call(trialRoute,{version:current.version,draft:{...current,name:'未保存类别'},sample},admin)).json();assert.equal(candidate.trial.saved,false);assert.equal(candidate.trial.publishEvidence,false);assert.equal(orderRules.get('rules',rule.id).draft.name,current.name);
|
||||
});
|
||||
@@ -0,0 +1,66 @@
|
||||
'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'),{MailStore}=require('../../src/modules/mail/store.cjs');
|
||||
const {orderRuleApi}=require('../../src/modules/order-rules/api.cjs');
|
||||
const {activateReferenceMapping}=require('../fixtures/activate-field-mapping.cjs');
|
||||
function fixture(t){const dir=fs.mkdtempSync(path.join(os.tmpdir(),'hui-config-'));let rules=new RuleStore(dir);const mail=new MailStore(dir),channel=mail.saveChannel({readOnly:true,name:'test',email:'orders@example.test',imap:{host:'imap.example.test',port:993,security:'tls',user:'orders',password:'isolated-test'}});let uid=0;t.after(()=>{rules.close();mail.close();fs.rmSync(dir,{recursive:true,force:true});});return {get rules(){return rules;},mail,template(mode='normal'){const n=++uid,d=mail.ingest(channel.id,'test',n,{subject:'Notice',scope:'',text:'Body',html:'',sender:'author@example.test',attachments:[]},Buffer.from('test '+n),1);return mail.confirm(d.id,{version:1,subject:'Notice',scope:'',useText:false,notificationMode:mode},'admin');},reopen(){rules.close();rules=new RuleStore(dir);},async call(route,body,role='admin',withMail=true){let result;await orderRuleApi({orderRules:rules,mail:withMail?{store:mail}:null,user:{username:'admin',role},route,method:'POST',body,reply:(status,value)=>{result={status,value};}});return result;}};}
|
||||
test('old rules default Hui off and settings persist without accepting separate recipients',t=>{
|
||||
const f=fixture(t),old=f.rules.get('rules','bs-change').draft;assert.equal(old.huizhouEnabled,false);assert.equal(old.huizhouTemplateId,'');
|
||||
const legacy={...old};delete legacy.huizhouEnabled;delete legacy.huizhouTemplateId;f.rules.put('rules',{...f.rules.get('rules',old.id),draft:legacy});
|
||||
const saved=f.rules.saveRule({...legacy,huizhouTo:['intruder@example.test'],huizhouCc:['intruder@example.test']},'admin');assert.equal(saved.huizhouEnabled,false);assert.equal(saved.huizhouTemplateId,'');assert.equal(saved.huizhouTo,undefined);assert.equal(saved.huizhouCc,undefined);
|
||||
const enabled=f.rules.saveRule({...saved,huizhouEnabled:true,huizhouTemplateId:'selected',to:['owner@example.test'],cc:['copy@example.test']},'admin');f.reopen();const restored=f.rules.snapshot().rules.find(r=>r.id===old.id);assert.equal(restored.huizhouEnabled,true);assert.equal(restored.huizhouTemplateId,'selected');assert.deepEqual(restored.to,enabled.to);assert.deepEqual(restored.cc,enabled.cc);
|
||||
});
|
||||
test('invalid Hui booleans and template identifiers are rejected atomically',t=>{
|
||||
const f=fixture(t),old=f.rules.get('rules','bs-change').draft;
|
||||
for(const patch of [{huizhouEnabled:'true'},{huizhouEnabled:1},{huizhouEnabled:null},{huizhouTemplateId:1},{huizhouTemplateId:null},{huizhouTemplateId:'bad/id'},{huizhouTemplateId:'x'.repeat(101)}])assert.throws(()=>f.rules.saveRule({...old,...patch},'admin'),e=>e.status===400);
|
||||
assert.equal(f.rules.get('rules',old.id).draft.version,old.version);
|
||||
});
|
||||
test('GET projects missing legacy Hui fields as off without rewriting persisted snapshots',async t=>{
|
||||
const f=fixture(t),record=f.rules.get('rules','bs-change');delete record.draft.huizhouEnabled;delete record.draft.huizhouTemplateId;f.rules.put('rules',record);let snapshot;
|
||||
await orderRuleApi({orderRules:f.rules,user:{username:'admin',role:'admin'},route:'/api/order-rules',method:'GET',reply:(status,value)=>{snapshot=value;}});
|
||||
const rule=snapshot.rules.find(r=>r.id==='bs-change');assert.equal(rule.huizhouEnabled,false);assert.equal(rule.huizhouTemplateId,'');assert.equal(f.rules.get('rules','bs-change').draft.huizhouEnabled,undefined);
|
||||
});
|
||||
test('save API validates effective Hui selection including partial saves and unavailable mail',async t=>{
|
||||
const f=fixture(t),normal=f.template(),hui=f.template('huizhou'),old=f.rules.get('rules','bs-change').draft;
|
||||
for(const patch of [{huizhouEnabled:true,huizhouTemplateId:''},{huizhouEnabled:true,huizhouTemplateId:normal.id},{bodyTemplateId:hui.id}])await assert.rejects(f.call('/api/order-rules/rules',{...old,...patch}),e=>e.status===409);
|
||||
await assert.rejects(f.call('/api/order-rules/rules',{...old,huizhouEnabled:true,huizhouTemplateId:hui.id},'admin',false),e=>e.status===503);
|
||||
const saved=(await f.call('/api/order-rules/rules',{...old,bodyTemplateId:normal.id,huizhouEnabled:true,huizhouTemplateId:hui.id})).value;
|
||||
f.template('huizhou');await assert.rejects(f.call('/api/order-rules/rules',{id:saved.id,categoryId:saved.categoryId,version:saved.version,name:'partial edit'}),e=>e.status===409);
|
||||
await assert.rejects(f.call('/api/order-rules/rules',{...saved,huizhouEnabled:false},'viewer'),e=>e.status===403);
|
||||
});
|
||||
test('publish and resume recheck Hui templates using draft and published snapshot respectively',async t=>{
|
||||
const f=fixture(t),normal=f.template(),hui=f.template('huizhou'),{captured}=activateReferenceMapping(f.rules),old=f.rules.get('rules','bs-change').draft;
|
||||
const saved=(await f.call('/api/order-rules/rules',{...old,to:['owner@example.test'],archiveDirectory:'\\\\server\\share',filenameDate:'receivedAt',bodyTemplateId:normal.id,huizhouEnabled:true,huizhouTemplateId:hui.id})).value;
|
||||
f.rules.trial(saved.id,{version:saved.version,sampleId:captured.id});f.mail.db.prepare("UPDATE templates SET status='archived' WHERE id=?").run(hui.id);
|
||||
await assert.rejects(f.call('/api/order-rules/rules/bs-change/publish',{version:saved.version}),e=>e.status===409);assert.equal(f.rules.get('rules',saved.id).published,null);
|
||||
f.mail.db.prepare("UPDATE templates SET status='active' WHERE id=?").run(hui.id);await f.call('/api/order-rules/rules/bs-change/publish',{version:saved.version});await f.call('/api/order-rules/rules/bs-change/pause',{version:saved.version});
|
||||
const edited=f.rules.saveRule({...saved,huizhouEnabled:false},'admin'),record=f.rules.get('rules',saved.id),input={version:edited.version,publishedVersion:saved.version,activationVersion:record.activationVersion};
|
||||
f.template('huizhou');await assert.rejects(f.call('/api/order-rules/rules/bs-change/resume',input),e=>e.status===409);assert.equal(f.rules.get('rules',saved.id).published.status,'paused');
|
||||
await assert.rejects(f.call('/api/order-rules/rules/bs-change/resume',input,'admin',false),e=>e.status===503);
|
||||
});
|
||||
function importTable(f,ids=['bs-notice','bs-change']){return {rows:[['类别编号','订单评审流程','电子流状态','邮件命名','收件人'],...ids.map(id=>{const r=f.rules.get('rules',id).draft;return [id,r.processNames.join('\n'),r.nodeNames.join('\n'),r.subjectPrefix,'imported@example.test'];})]};}
|
||||
test('Excel import rechecks replaced Hui selection and rejects all rows before any write',async t=>{
|
||||
const f=fixture(t),hui=f.template('huizhou'),old=f.rules.get('rules','bs-change').draft;
|
||||
await f.call('/api/order-rules/rules',{...old,huizhouEnabled:true,huizhouTemplateId:hui.id});
|
||||
const plan=(await f.call('/api/order-rules/import/preview',importTable(f))).value;assert.equal(plan.canCommit,true);f.template('huizhou');
|
||||
const rules=f.rules.all('rules'),history=f.rules.all('rule-history'),audit=f.rules.all('audit'),revision=f.rules.queryRevision();
|
||||
await assert.rejects(f.call('/api/order-rules/import/commit',{id:plan.id}),e=>e.status===409);
|
||||
assert.deepEqual(f.rules.all('rules'),rules);assert.deepEqual(f.rules.all('rule-history'),history);assert.deepEqual(f.rules.all('audit'),audit);assert.equal(f.rules.queryRevision(),revision);assert.equal(f.rules.get('rule-imports',plan.id).result,undefined);
|
||||
});
|
||||
test('Excel import requires mail for an enabled Hui candidate and failed commit remains retryable',async t=>{
|
||||
const f=fixture(t),hui=f.template('huizhou'),old=f.rules.get('rules','bs-change').draft;
|
||||
await f.call('/api/order-rules/rules',{...old,huizhouEnabled:true,huizhouTemplateId:hui.id});
|
||||
const plan=(await f.call('/api/order-rules/import/preview',importTable(f))).value,before=f.rules.all('rules');
|
||||
await assert.rejects(f.call('/api/order-rules/import/commit',{id:plan.id},'admin',false),e=>e.status===503);assert.deepEqual(f.rules.all('rules'),before);assert.equal(f.rules.get('rule-imports',plan.id).result,undefined);
|
||||
const committed=(await f.call('/api/order-rules/import/commit',{id:plan.id})).value;assert.equal(committed.count,2);assert.deepEqual(f.rules.get('rules','bs-change').draft.to,['imported@example.test']);
|
||||
f.template('huizhou');const revision=f.rules.queryRevision(),after=f.rules.all('rules'),history=f.rules.all('rule-history'),audit=f.rules.all('audit');
|
||||
assert.deepEqual((await f.call('/api/order-rules/import/commit',{id:plan.id},'admin',false)).value,committed);assert.equal(f.rules.queryRevision(),revision);assert.deepEqual(f.rules.all('rules'),after);assert.deepEqual(f.rules.all('rule-history'),history);assert.deepEqual(f.rules.all('audit'),audit);
|
||||
});
|
||||
test('Excel import rejects missing and wrong-mode effective selections through the shared save contract',async t=>{
|
||||
const f=fixture(t),normal=f.template(),hui=f.template('huizhou');
|
||||
for(const patch of [{huizhouEnabled:true,huizhouTemplateId:''},{huizhouEnabled:true,huizhouTemplateId:normal.id},{bodyTemplateId:hui.id}]){
|
||||
const old=f.rules.get('rules','bs-change').draft;f.rules.saveRule({...old,huizhouEnabled:false,huizhouTemplateId:'',bodyTemplateId:'',...patch},'admin');
|
||||
const plan=(await f.call('/api/order-rules/import/preview',importTable(f))).value,before=f.rules.all('rules');
|
||||
await assert.rejects(f.call('/api/order-rules/import/commit',{id:plan.id}),e=>e.status===409);assert.deepEqual(f.rules.all('rules'),before);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,174 @@
|
||||
'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={},attachPdf}={}){
|
||||
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:['2639266652@qq.com'],cc:[],attachPdf:false,archiveDirectory:'\\\\server\\orders',filenameDate:'receivedAt',huizhouEnabled:enabled,huizhouTemplateId:enabled?'hui-template':'',...(attachPdf===undefined?{}:{attachPdf})},'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 separator of ['', '\n', '<br>'])test('title mode ownership survives own-summary formatting '+JSON.stringify(separator),t=>{
|
||||
const title=['订单号:H-100','业务模式:惠州数字','客户简称:普通客户','订单号:O-200','客户简称:普通客户'].join(separator);
|
||||
const f=fixture(t,{title}),{normal,hui}=pair(f);assert.deepEqual(hui.orderNos,['H-100']);assert.doesNotMatch(hui.subject+hui.text,/O-200/);assert.match(normal.text,/H-100/);assert.match(normal.text,/O-200/);
|
||||
});
|
||||
for(const title of [
|
||||
'订单号:O-100客户简称:普通客户订单类别:参考订单订单类型:C业务模式:惠州数字毛利:绿标订单号:H-200客户简称:终端客户',
|
||||
'订单号:O-100客户简称:普通客户\n业务模式:惠州数字\n毛利:绿标\n订单号:H-200客户简称:终端客户',
|
||||
'业务模式:惠州数字订单号:H-200客户简称:终端客户订单号:O-100客户简称:普通客户'
|
||||
])test('title prefix header keeps its following owner '+JSON.stringify(title),()=>{
|
||||
const {selectHuizhou}=require('../../src/modules/order-rules/huizhou.cjs'),selected=selectHuizhou({titleOrders:extractTitle(title).orders});assert.deepEqual(selected.orderNos,['H-200']);assert.deepEqual(selected.issues,[]);
|
||||
});
|
||||
test('title mode at an unmarked boundary blocks Hui instead of silently choosing an adjacent order',t=>{
|
||||
const f=fixture(t,{title:'订单号:O-100客户简称:普通客户业务模式:惠州数字订单号:H-200客户简称:终端客户'}),batches=f.store.prepare(cutoff,'admin');assert.equal(batches.length,1);assert.equal(batches[0].notificationMode,'normal');
|
||||
const hui=orderDetail(f.context(),f.order.id,admin).notifications.huizhou;assert.equal(hui.status,'blocked');assert.deepEqual(hui.orderNos,[]);assert.ok(hui.issues.length);
|
||||
});
|
||||
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');
|
||||
});
|
||||
for(const ordinaryStatus of ['sent','unknown'])for(const observed of [true,false])test(`blocked Hui without PDF attachments checks corrupt receipts and recovers after repair; normal=${ordinaryStatus}, todo observed=${observed}`,async t=>{
|
||||
const f=fixture(t,{attachPdf:false}),d=f.dispatcher();t.after(()=>d.stop());f.store.templateResolver=()=>null;
|
||||
const batches=f.store.prepare(cutoff,'admin');assert.equal(batches.length,1);const normal=batches[0];assert.deepEqual(normal.attachments,[]);f.failSend(ordinaryStatus==='unknown');await d.dispatch(normal,f.store.settings());f.failSend(false);assert.equal(f.store.get('batches',normal.id).status,ordinaryStatus);assert.equal(f.store.get('orders',f.order.id).notifications.huizhou.status,'blocked');
|
||||
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',runtimeCheck:{status:'ready'}});
|
||||
let corrupt=true,reads=0;
|
||||
const provider={scan:async()=>observed?[row]:[],capabilities:()=>({liveTodo:true,pdfExport:true}),capture:async()=>{throw Error('must not recapture blocked Hui receipt');}};
|
||||
const archive={capabilities:()=>({automaticArchive:true,pdfExport:true}),probe:async()=>({automaticArchive:true,pdfExport:true}),read:async()=>{reads++;return corrupt?Buffer.from('corrupt receipt'):f.bytes;},archive:async()=>{throw Error('must not reexport blocked Hui receipt');}};
|
||||
const execution=new OrderExecutionCoordinator({store:f.store,workspace:{getConnection:()=>connection,snapshot:()=>({connections:[connection]})},provider,archive,clock:()=>new Date(cutoff)});t.after(()=>execution.stop());
|
||||
const principal={user:admin,sessionId:'fixture-session'};
|
||||
await execution.scan({connectionId:'c1',idempotencyKey:'blocked-corrupt'},principal);
|
||||
f.store.templateResolver=(category,rule,mode)=>mode==='huizhou'?f.huiTemplate:null;
|
||||
assert.deepEqual(f.store.prepare(cutoff,'admin'),[]);assert.equal(reads,1);assert.equal(f.store.get('execution-tasks',taskId).runtimeCheck.status,'blocked');assert.equal(f.sent.length,1);
|
||||
corrupt=false;await execution.scan({connectionId:'c1',idempotencyKey:'blocked-repaired'},principal);assert.equal(reads,2);assert.equal(f.store.get('execution-tasks',taskId).runtimeCheck.status,'ready');
|
||||
const repaired=f.store.prepare(cutoff,'admin');assert.equal(repaired.length,1);const hui=repaired[0];assert.equal(hui.notificationMode,'huizhou');assert.deepEqual(hui.attachments,[]);await d.dispatch(hui,f.store.settings());
|
||||
assert.equal(f.store.get('batches',hui.id).status,'sent');assert.equal(f.store.get('batches',normal.id).status,ordinaryStatus);assert.deepEqual(f.sent.map(message=>message.subject),[normal.subject,hui.subject]);assert.equal(f.store.all('orders').length,1);
|
||||
});
|
||||
@@ -0,0 +1,95 @@
|
||||
'use strict';
|
||||
const test=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs/promises'),os=require('node:os'),path=require('node:path');
|
||||
const {startTestDashboard,login}=require('../fixtures/dashboard-runtime.cjs');
|
||||
const {activateReferenceMapping}=require('../fixtures/activate-field-mapping.cjs');
|
||||
const {loadPlaywright,browserOptions}=require('../../src/platform/browser.cjs');
|
||||
const mixed='订单号:O-100机芯号:CORE-O客户简称:普通客户总数量:10\n业务模式:惠州数字毛利:绿标订单号:H-200机芯号:CORE-H客户简称:惠州创维数字技术有限公司总数量:20';
|
||||
async function fixture(t){
|
||||
const dir=await fs.mkdtemp(path.join(os.tmpdir(),'hui-ui-')),runtime=await startTestDashboard({stateDir:dir,mailHistory:true}),browser=await loadPlaywright().chromium.launch(browserOptions());
|
||||
t.after(async()=>{await browser.close();await runtime.close();await fs.rm(dir,{recursive:true,force:true});});
|
||||
const mail=runtime.mail.store,channel=mail.saveChannel({name:'隔离模板邮箱',email:'orders@example.test',senders:['author@example.test'],enabled:false,smtp:{host:'smtp.example.test',port:465,security:'tls',user:'orders',password:'Isolated-test-password'},imap:{host:'imap.example.test',port:993,security:'tls',user:'orders',password:'Isolated-test-password'}});let uid=0;
|
||||
function pending(subject){const n=++uid,parsed={subject,scope:'',text:'业务访问 https://example.test/business\n{{订单明细}}',html:'',sender:'author@example.test',attachments:[]},raw=Buffer.from('isolated template '+n);return mail.ingest(channel.id,'isolated',n,parsed,raw,channel.version);}
|
||||
function template(mode,subject){const d=pending(subject);return mail.confirm(d.id,{version:d.version,subject,scope:'',notificationMode:mode,useText:false},'admin');}
|
||||
const normal=template('normal','普通 {{订单号}}'),hui=template('huizhou','惠州 {{订单号}}');runtime.orderRules.templateResolver=(category,rule,mode='normal')=>require('../../src/modules/mail/rule-template.cjs').ruleTemplate(mail,category,rule,mode);
|
||||
const page=await browser.newPage({viewport:{width:1440,height:1000}});page.setDefaultTimeout(6000);
|
||||
const errors=[];page.on('pageerror',e=>errors.push(e.message));t.after(()=>assert.deepEqual(errors,[]));
|
||||
const base='http://127.0.0.1:'+runtime.server.address().port;
|
||||
return {runtime,page,browser,base,normal,hui,pending,async open(route='#order-rules'){await page.goto(base+'/'+route);await login(page);},configure(extra={}){const old=runtime.orderRules.get('rules','bs-change').draft;return runtime.orderRules.saveRule({...old,to:['owner@example.test'],cc:['copy@example.test'],archiveDirectory:'\\\\fixture\\orders',filenameDate:'receivedAt',bodyTemplateId:normal.id,huizhouEnabled:true,huizhouTemplateId:hui.id,...extra},'admin');}};
|
||||
}
|
||||
|
||||
test('Hui selector filters modes, saves and reloads without extra recipients, retaining failed and unsaved edits',{timeout:90000},async t=>{
|
||||
const f=await fixture(t),{page,runtime}=f;await f.open();await page.locator('[data-rule-id="bs-change"]').click();
|
||||
const toggle=page.getByRole('switch',{name:'额外发送惠州通知',exact:true}),choice=page.getByLabel('惠州邮件模板',{exact:true});
|
||||
assert.equal(await toggle.isChecked(),false);assert.equal(await choice.isVisible(),false);
|
||||
assert.deepEqual(await page.getByLabel('邮件模板',{exact:true}).locator('option').evaluateAll(options=>options.map(o=>o.value)),['',f.normal.id]);
|
||||
await toggle.check();assert.equal(await choice.isVisible(),true);assert.equal(await choice.evaluate(e=>e.required),true);
|
||||
assert.deepEqual(await choice.locator('option').evaluateAll(options=>options.map(o=>o.value)),['',f.hui.id]);
|
||||
assert.equal(await page.locator('[name=to]').count(),1);assert.equal(await page.locator('[name=cc]').count(),1);assert.equal(await page.locator('[name=attachPdf]').count(),1);
|
||||
await choice.selectOption(f.hui.id);await page.getByLabel('收件人',{exact:true}).fill('owner@example.test');await page.getByLabel('抄送人',{exact:true}).fill('copy@example.test');
|
||||
await page.getByRole('button',{name:'保存草稿',exact:true}).click();await page.getByText('规则草稿已保存。',{exact:true}).waitFor();
|
||||
let draft=runtime.orderRules.get('rules','bs-change').draft;assert.equal(draft.huizhouEnabled,true);assert.equal(draft.huizhouTemplateId,f.hui.id);assert.deepEqual(draft.to,['owner@example.test']);assert.deepEqual(draft.cc,['copy@example.test']);
|
||||
assert.equal(await toggle.isChecked(),true);assert.equal(await choice.inputValue(),f.hui.id);
|
||||
let requests=0;await page.route('**/api/order-rules/rules',async route=>{requests++;await new Promise(r=>setTimeout(r,100));await route.fulfill({status:503,json:{error:'隔离保存失败'}});});
|
||||
await toggle.uncheck();await page.getByRole('button',{name:'保存草稿',exact:true}).dblclick();await page.getByText('隔离保存失败',{exact:true}).waitFor();assert.equal(requests,1);
|
||||
assert.equal(await toggle.isChecked(),false);assert.equal(await choice.isVisible(),false);assert.equal(await choice.evaluate(e=>e.required),false);assert.equal(await page.evaluate(()=>PageLifecycle.dirty()),true);
|
||||
await page.locator('[data-rule-id="bs-notice"]').click();await page.getByRole('button',{name:'留在此页',exact:true}).click();assert.equal(await toggle.isChecked(),false);
|
||||
await page.locator('[data-rule-id="bs-notice"]').click();await page.getByRole('button',{name:'放弃并继续',exact:true}).click();await page.locator('[data-rule-id="bs-change"]').click();assert.equal(await toggle.isChecked(),true);
|
||||
await page.unroute('**/api/order-rules/rules');await toggle.uncheck();await page.getByRole('button',{name:'保存草稿',exact:true}).click();await page.getByText('规则草稿已保存。',{exact:true}).waitFor();draft=runtime.orderRules.get('rules','bs-change').draft;assert.equal(draft.huizhouEnabled,false);assert.equal(draft.huizhouTemplateId,f.hui.id);
|
||||
await page.setViewportSize({width:390,height:844});assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true);assert.equal(runtime.orderRules.settings().enabled,false);
|
||||
});
|
||||
|
||||
test('viewers can inspect Hui choices but cannot edit rules or confirm template modes',{timeout:90000},async t=>{
|
||||
const f=await fixture(t),{page,runtime}=f;f.configure();runtime.store.addUser({username:'viewer',password:'Test-password-123',role:'viewer'},'admin');
|
||||
await page.goto(f.base+'/#order-rules');await page.getByLabel('账号',{exact:true}).fill('viewer');await page.getByLabel('密码',{exact:true}).fill('Test-password-123');await page.getByRole('button',{name:'登录',exact:true}).click();await page.locator('[data-rule-id="bs-change"]').click();
|
||||
assert.equal(await page.getByRole('switch',{name:'额外发送惠州通知',exact:true}).isDisabled(),true);assert.equal(await page.getByLabel('惠州邮件模板',{exact:true}).isDisabled(),true);assert.equal(await page.getByRole('button',{name:'保存草稿',exact:true}).count(),0);
|
||||
const pending=f.pending('只读模板');await page.goto(f.base+'/#templates');await page.locator('[data-template="'+pending.id+'"]').click();assert.equal(await page.getByLabel('通知模式',{exact:true}).isDisabled(),true);assert.equal(await page.getByRole('button',{name:'确认生效',exact:true}).count(),0);
|
||||
});
|
||||
|
||||
test('template confirmation sends selected Hui mode and lists mode-specific published usage',{timeout:90000},async t=>{
|
||||
const f=await fixture(t),{page,runtime}=f,rule=f.configure(),record=runtime.orderRules.get('rules',rule.id);record.published={...rule,status:'enabled'};runtime.orderRules.put('rules',record);
|
||||
const pending=f.pending('新惠州模板');await f.open('#templates');await page.locator('[data-template="'+pending.id+'"]').click();await page.getByLabel('通知模式',{exact:true}).selectOption('huizhou');assert.match(await page.locator('#template-review .card-header').innerText(),/惠州通知/);assert.doesNotMatch(await page.locator('#template-review .card-header').innerText(),/普通通知/);
|
||||
await page.getByRole('button',{name:'关闭',exact:true}).click();await page.getByRole('button',{name:'留在此页',exact:true}).click();assert.equal(await page.getByLabel('通知模式',{exact:true}).inputValue(),'huizhou');
|
||||
let failed=true;await page.route('**/api/mail/templates/'+pending.id+'/confirm',r=>failed?r.fulfill({status:503,json:{error:'隔离模板确认失败'}}):r.continue());await page.getByRole('button',{name:'确认生效',exact:true}).click();await page.getByText('隔离模板确认失败',{exact:true}).waitFor();assert.equal(await page.getByLabel('通知模式',{exact:true}).inputValue(),'huizhou');assert.equal(await page.evaluate(()=>PageLifecycle.dirty()),true);
|
||||
failed=false;await page.getByRole('button',{name:'确认生效',exact:true}).click();await page.getByText('模板已确认生效。',{exact:true}).waitFor();assert.equal(runtime.mail.store.template(pending.id).notificationMode,'huizhou');assert.equal(runtime.mail.store.template(f.normal.id).status,'active');
|
||||
await page.getByLabel('模板状态',{exact:true}).selectOption('active');const normalRow=page.locator('tr').filter({has:page.locator('[data-template="'+f.normal.id+'"]')});assert.match(await normalRow.innerText(),/普通通知/);
|
||||
const huiRow=page.locator('tr').filter({has:page.locator('[data-template="'+pending.id+'"]')});assert.match(await huiRow.innerText(),/惠州通知/);
|
||||
const usage=page.locator('#category-templates .list-group-item').filter({hasText:'备损订单更改通知书'});assert.match(await usage.innerText(),/普通通知:普通 \{\{订单号\}\}/);assert.match(await usage.innerText(),/惠州通知:惠州 \{\{订单号\}\}/);assert.doesNotMatch(await usage.innerText(),/新惠州模板/);
|
||||
});
|
||||
|
||||
test('real trial separates mixed Hui mail and exposes no-match and uncertain selections',{timeout:90000},async t=>{
|
||||
const f=await fixture(t),{runtime,page}=f,reference=require('../../src/modules/order-rules/catalog.cjs').adapters.find(a=>a.id==='bs-change');activateReferenceMapping(runtime.orderRules,'bs-change',{title:mixed,fields:{[reference.fields.orderNo]:'O-100'}});f.configure();await f.open();await page.locator('[data-rule-id="bs-change"]').click();await page.getByRole('button',{name:'检查识别结果',exact:true}).click();
|
||||
const normal=page.locator('[data-notification-preview="normal"]'),hui=page.locator('[data-notification-preview="huizhou"]');await hui.waitFor();
|
||||
assert.match(await normal.locator('pre').textContent(),/O-100/);assert.match(await normal.locator('pre').textContent(),/H-200/);assert.match(await hui.locator('pre').textContent(),/H-200/);assert.doesNotMatch((await hui.locator('dd').first().textContent())+(await hui.locator('pre').textContent()),/O-100|CORE-O/);assert.match(await hui.textContent(),/owner@example.test/);assert.match(await hui.textContent(),/copy@example.test/);assert.equal(await hui.locator('dd').last().textContent(),await normal.locator('dd').last().textContent());assert.match(await hui.locator('dd').last().textContent(),/不附带 PDF/);assert.doesNotMatch(await page.locator('#order-rule-preview-result').textContent(),/额外通知规则尚未确认/);
|
||||
await fs.mkdir('output/verification',{recursive:true});await page.screenshot({path:'output/verification/huizhou-task3-preview-desktop.png',fullPage:true});
|
||||
for(const [title,status] of [['订单号:O-100客户简称:普通客户','empty'],['订单号:HA200客户简称:未知客户','blocked']]){
|
||||
// Use the real capture/mapping pipeline for each selection; storage is isolated per test.
|
||||
const sample={...structuredClone(reference.sample),demo:false,title,taskId:'ui-'+status,fields:{...reference.sample.fields,[reference.fields.orderNo]:status==='empty'?'O-100':'HA200'}};
|
||||
const captured=runtime.orderRules.recordCapture({sample,taskId:'ui-'+status,snapshot:{processVersion:sample.processVersion,fields:Object.entries(sample.fields).map(([path,value])=>({path,value}))}});
|
||||
await page.getByRole('button',{name:'刷新规则与字段',exact:true}).click();await page.locator('[data-rule-id="bs-change"]').click();await page.locator('#order-rule-sample-source').selectOption('capture:'+captured.id);await page.getByRole('button',{name:'检查识别结果',exact:true}).click();await page.locator('[data-notification-preview="huizhou"][data-notification-status="'+status+'"]').waitFor();
|
||||
assert.match(await page.locator('[data-notification-preview="huizhou"]').textContent(),status==='empty'?/未匹配惠州明细/:/需核实|不能|无法|不足|确认/);
|
||||
}
|
||||
await page.setViewportSize({width:390,height:844});assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true);await page.screenshot({path:'output/verification/huizhou-task3-preview-mobile.png',fullPage:true});
|
||||
});
|
||||
|
||||
test('record lists and details show independent results and batch modes without changing recovery targets',{timeout:90000},async t=>{
|
||||
const f=await fixture(t),{runtime,page}=f;
|
||||
runtime.orderRules.put('orders',{id:'dual-order',categoryId:'bs-change',status:'sent',batchId:'normal-batch',event:{connectionId:'c',orderNo:'O-100',receivedAt:'2026-10-21T01:00:00Z'},notifications:{huizhou:{status:'unknown',batchId:'hui-batch',error:'惠州连接结果不明',orderNos:['H-200'],issues:['仅惠州待核实']}},createdAt:'2026-10-21T01:00:00Z'});
|
||||
for(const [id,mode,status] of [['normal-batch','normal','sent'],['hui-batch','huizhou','unknown']])runtime.orderRules.put('batches',{id,version:1,notificationMode:mode,status,categoryId:'bs-change',subject:id,orderIds:['dual-order'],orderNos:mode==='huizhou'?['H-200']:['O-100','H-200'],text:'冻结正文',to:['owner@example.test'],cc:[],attachments:[]});
|
||||
await f.open('#notification-orders');const row=page.locator('tr').filter({has:page.getByText('O-100',{exact:true})});await row.waitFor();assert.match(await row.innerText(),/普通通知.*已提交邮件服务器/s);assert.match(await row.innerText(),/惠州通知.*待核实/s);
|
||||
await row.getByRole('button',{name:'查看详情',exact:true}).click();const dialog=page.getByRole('dialog',{name:'业务详情'});await dialog.getByRole('heading',{name:'惠州通知',exact:true}).waitFor();assert.match(await dialog.textContent(),/H-200/);assert.match(await dialog.textContent(),/惠州连接结果不明/);assert.equal(await dialog.getByRole('button',{name:'人工补发原冻结批次',exact:true}).count(),0);
|
||||
await page.getByRole('button',{name:'关闭详情',exact:true}).click();await page.goto(f.base+'/#notification-batches?scope=all');const batch=page.locator('tr').filter({has:page.getByText('hui-batch',{exact:true})});await batch.waitFor();assert.match(await batch.innerText(),/惠州通知/);await batch.getByRole('button',{name:'查看详情',exact:true}).click();await dialog.getByRole('heading',{name:'保存核验结论',exact:true}).waitFor();assert.match(await dialog.textContent(),/通知模式惠州通知/);assert.equal(await dialog.getByRole('button',{name:'人工补发原冻结批次',exact:true}).count(),0);
|
||||
await page.setViewportSize({width:390,height:844});assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true);
|
||||
});
|
||||
|
||||
test('order list retains execution failure and conflict causes beside independent notification results',{timeout:90000},async t=>{
|
||||
const f=await fixture(t),{runtime,page}=f;
|
||||
const cases=[{id:'execution-failed',status:'failed',error:'归档读取校验失败,通知尚待处理'},{id:'execution-conflict',status:'blocked',error:'新来源修订与已归档版本冲突,请核对',conflict:true}];
|
||||
for(const item of cases){
|
||||
runtime.orderRules.put('orders',{id:item.id,status:'sent',error:'普通路已有结果说明',event:{connectionId:'c',orderNo:item.id,receivedAt:'2026-10-21T01:00:00Z'},notifications:{huizhou:{status:'pending',batchId:null,error:'惠州路独立等待原因',orderNos:['H-200'],issues:[]}}});
|
||||
runtime.orderRules.put('execution-tasks',{id:'task-'+item.id,orderId:item.id,connectionId:'c',version:1,status:item.status,error:item.error,conflict:item.conflict||false,row:{orderNo:item.id}});
|
||||
}
|
||||
runtime.orderRules.put('execution-tasks',{id:'bare-execution',connectionId:'c',version:1,status:'failed',error:'尚未生成订单的采集失败',row:{orderNo:'bare-execution'}});
|
||||
await f.open('#notification-orders');
|
||||
for(const item of cases){const row=page.locator('tr').filter({has:page.getByText(item.id,{exact:true})});await row.waitFor();const text=await row.innerText();assert.ok(text.includes(item.error),text);assert.match(text,/普通通知.*已提交邮件服务器/s);assert.match(text,/惠州通知.*等待汇总/s);assert.match(text,/普通路已有结果说明/);assert.match(text,/惠州路独立等待原因/);}
|
||||
const bare=page.locator('tr').filter({has:page.getByText('bare-execution',{exact:true})});assert.match(await bare.innerText(),/尚未生成订单的采集失败/);assert.doesNotMatch(await bare.innerText(),/普通通知|惠州通知/);
|
||||
});
|
||||
@@ -0,0 +1,136 @@
|
||||
'use strict';
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const { seedRules, adapters } = require('../../src/modules/order-rules/catalog.cjs');
|
||||
const { previewMatch, describeRule } = require('../../src/modules/order-rules/matching.cjs');
|
||||
|
||||
const sampleFor = id => structuredClone(adapters.find(item => item.id === id).sample);
|
||||
|
||||
test('title becomes separate order paragraphs without metadata and retains the raw evidence', () => {
|
||||
const sample=sampleFor('bs-change');
|
||||
sample.title='客户等级:C毛利:绿标订单号:148396机芯号:TDY0B8500V2MJS061产品型号:TDY0B-GJK0K06-001客户简称:江苏移动(家客版)总数量:5000订单类别:参考订单订单类型:C业务模式:惠州数字毛利:绿标订单号:HA148396机芯号:TDY0B-GJK0K06-H01客户简称:惠州创维数字技术有限公司总数量:5000';
|
||||
sample.brief='过时的摘要,不应覆盖标题';
|
||||
sample.fields['OFR_BS_Applicant.OrderNum']='148396';
|
||||
const result=previewMatch(seedRules(),adapters,sample);
|
||||
assert.equal(result.valid,true);
|
||||
assert.equal(result.event.brief,'订单号:148396机芯号:TDY0B8500V2MJS061产品型号:TDY0B-GJK0K06-001客户简称:江苏移动(家客版)总数量:5000订单类别:参考订单\n订单号:HA148396机芯号:TDY0B-GJK0K06-H01客户简称:惠州创维数字技术有限公司总数量:5000');
|
||||
assert.equal(result.event.rawTitle,sample.title);
|
||||
assert.deepEqual(result.event.titleOrders.map(o=>o.orderNo),['148396','HA148396']);
|
||||
assert.ok(result.event.factoryHints.some(h=>h.value==='惠州数字'&&h.source==='业务模式'));
|
||||
assert.ok(result.fieldTrace.some(f=>f.key==='brief'&&f.path==='title → 订单段落'));
|
||||
});
|
||||
|
||||
test('title extraction accepts Chinese colons and line breaks but rejects missing order identifiers',()=>{
|
||||
const sample=sampleFor('bs-change');
|
||||
sample.title='毛利:绿标<br>订单号:HA1机芯号:X总数量:0订单类型:C';
|
||||
const result=previewMatch(seedRules(),adapters,sample);
|
||||
assert.equal(result.event.brief,'订单号:HA1机芯号:X总数量:0');
|
||||
assert.deepEqual(result.event.factoryHints,[]); // HA alone is not factory evidence.
|
||||
for(const title of ['客户等级:C毛利:绿标','订单号:机芯号:X','订单号:A订单号:机芯号:X']){
|
||||
const invalid=previewMatch(seedRules(),adapters,{...sample,title});
|
||||
assert.equal(invalid.valid,false,title);
|
||||
assert.ok(invalid.issues.some(i=>i.includes('标题')));
|
||||
}
|
||||
});
|
||||
|
||||
test('sample must contain the chosen filename date and serial number before it can authorize a rule',()=>{
|
||||
const rules=seedRules();rules.find(r=>r.id==='bs-change').filenameDate='appDate';
|
||||
const sample=sampleFor('bs-change');delete sample.fields['OFR_BS_Applicant.AppDate'];delete sample.serialNum;
|
||||
const result=previewMatch(rules,adapters,sample);assert.equal(result.valid,false);assert.match(result.issues.join(';'),/申请日期/);assert.match(result.issues.join(';'),/流水/);
|
||||
sample.serialNum='SERIAL-1';sample.fields['OFR_BS_Applicant.AppDate']='2026-02-31';
|
||||
assert.equal(previewMatch(rules,adapters,sample).valid,false);
|
||||
sample.fields['OFR_BS_Applicant.AppDate']='2026-10-19 09:30:00';assert.equal(previewMatch(rules,adapters,sample).valid,true);
|
||||
});
|
||||
|
||||
test('exact Excel process and notification node select overseas change independently of product line', () => {
|
||||
const sample = sampleFor('overseas-change');
|
||||
sample.nodeName = '订单专员(订单通知书)';
|
||||
sample.fields['unrelated.ProductLine'] = '备损';
|
||||
const result = previewMatch(seedRules(), adapters, sample);
|
||||
assert.equal(result.valid, true);
|
||||
assert.equal(result.ruleId, 'overseas-change');
|
||||
assert.equal(result.event.orderNo, 'DEMO-OVERSEAS-001');
|
||||
assert.equal(result.event.processVersion, '1.1');
|
||||
assert.equal(result.event.documentNum, 'DEMO-SERIAL-002');
|
||||
assert.equal(result.fieldTrace.find(item => item.key === 'orderNo').path, 'OFR_HWLS_Applicant.OrderNum');
|
||||
assert.equal(sample.demo, true);
|
||||
});
|
||||
|
||||
test('unlisted node and similar process names never silently fuzzy match', () => {
|
||||
for (const patch of [{ nodeName: '订单更改通知' }, { processName: '海外返工订单更改评审(新)' }]) {
|
||||
const result = previewMatch(seedRules(), adapters, { ...sampleFor('overseas-change'), ...patch });
|
||||
assert.equal(result.valid, false);
|
||||
assert.deepEqual(result.candidates, []);
|
||||
assert.ok(result.issues.length > 0);
|
||||
}
|
||||
});
|
||||
|
||||
test('supported draft rules normalize raw bound fields and preserve a zero quantity', () => {
|
||||
const rules = seedRules();
|
||||
rules.find(item => item.id === 'bs-change').status = 'draft';
|
||||
const customAdapters = structuredClone(adapters);
|
||||
customAdapters.find(item => item.id === 'bs-change').fields.quantity = 'Demo.Quantity';
|
||||
const sample = sampleFor('bs-change');
|
||||
sample.fields['Demo.Quantity'] = 0;
|
||||
const result = previewMatch(rules, customAdapters, sample);
|
||||
assert.equal(result.valid, true);
|
||||
assert.equal(result.event.quantity, 0);
|
||||
assert.equal(result.event.customer, '演示客户');
|
||||
assert.equal(result.fieldTrace.find(item => item.key === 'quantity').value, 0);
|
||||
});
|
||||
|
||||
test('a missing adapter or wrong adapter process version is never a valid preview', () => {
|
||||
for (const [available, sample] of [[[], sampleFor('bs-change')], [adapters, { ...sampleFor('bs-change'), processVersion: '9.9' }]]) {
|
||||
const result = previewMatch(seedRules(), available, sample);
|
||||
assert.equal(result.valid, false);
|
||||
assert.equal(result.ruleId, 'bs-change');
|
||||
assert.ok(result.checks.some(item => !item.ok && item.label.includes('适配')));
|
||||
}
|
||||
});
|
||||
|
||||
test('colliding exact rules block rather than selecting the first candidate', () => {
|
||||
const rules = seedRules();
|
||||
rules.push({ ...rules.find(item => item.id === 'bs-change'), id: 'collision' });
|
||||
const result = previewMatch(rules, adapters, sampleFor('bs-change'));
|
||||
assert.equal(result.valid, false);
|
||||
assert.equal(result.ruleId, null);
|
||||
assert.deepEqual(result.candidates, ['bs-change', 'collision']);
|
||||
});
|
||||
|
||||
test('reports every missing identity and required field without early return', () => {
|
||||
const sample = sampleFor('bs-change');
|
||||
for (const key of ['connectionId', 'source', 'instanceId', 'taskId', 'revision', 'receivedAt', 'brief']) delete sample[key];
|
||||
delete sample.fields['OFR_BS_Applicant.OrderNum'];
|
||||
const result = previewMatch(seedRules(), adapters, sample);
|
||||
assert.equal(result.valid, false);
|
||||
assert.ok(result.issues.length >= 7);
|
||||
assert.equal(result.checks.find(item=>item.label==='事件修订').ok,true,'source may omit its business revision');
|
||||
for (const key of ['connectionId', 'source', 'instanceId', 'taskId', 'receivedAt', 'orderNo', 'brief']) {
|
||||
assert.ok(result.checks.some(item => !item.ok && item.detail.includes(key)), key);
|
||||
}
|
||||
});
|
||||
|
||||
test('invalid timestamps and negative or nonnumeric supplied quantities are rejected, revision zero survives', () => {
|
||||
const customAdapters = structuredClone(adapters);
|
||||
customAdapters.find(item => item.id === 'bs-change').fields.quantity = 'Demo.Quantity';
|
||||
for (const value of [-1, 'not a number']) {
|
||||
const sample = sampleFor('bs-change'); sample.fields['Demo.Quantity'] = value;
|
||||
assert.equal(previewMatch(seedRules(), customAdapters, sample).valid, false);
|
||||
}
|
||||
assert.equal(previewMatch(seedRules(), adapters, { ...sampleFor('bs-change'), receivedAt: 'yesterday' }).valid, false);
|
||||
assert.equal(previewMatch(seedRules(), adapters, { ...sampleFor('bs-change'), revision: 0 }).valid, true);
|
||||
});
|
||||
|
||||
test('all fifteen categories stay separate, paused and privately configurable with deterministic execution summaries', () => {
|
||||
const rules = seedRules();
|
||||
assert.equal(rules.length, 15);
|
||||
assert.equal(new Set(rules.map(item => item.categoryId)).size, 15);
|
||||
assert.deepEqual(rules.map(item => item.sourceRow), Array.from({ length: 15 }, (_, index) => index + 2));
|
||||
assert.ok(rules.every(item => item.status === 'paused' && !item.archiveDirectory && !item.to.length && !item.cc.length));
|
||||
assert.match(describeRule(rules.find(item => item.id === 'bs-change')), /备损订单更改通知书/);
|
||||
assert.match(describeRule(rules[0]), /同类.*一封/);
|
||||
rules[0].processNames.push('mutation');
|
||||
assert.ok(!seedRules()[0].processNames.includes('mutation'));
|
||||
});
|
||||
|
||||
test('title extraction supersedes an absent legacy form summary source',()=>{const sample=sampleFor('bs-change'),legacy=structuredClone(adapters);sample.title='订单号:DEMO-BS-001总数量:0';legacy.find(a=>a.id==='bs-change').fields.brief='Removed.Summary';const result=previewMatch(seedRules(),legacy,sample);assert.equal(result.valid,true);assert.equal(result.event.brief,sample.title);});
|
||||
@@ -0,0 +1,37 @@
|
||||
'use strict';
|
||||
const test=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs/promises');
|
||||
const {orderDrivenUI}=require('../fixtures/order-driven-ui.cjs');
|
||||
|
||||
test('mapping output shows separate mail summary columns including shipping and zero without merging customer text',{timeout:90000},async t=>{
|
||||
const {page,capture,runtime}=await orderDrivenUI(t);capture({taskId:'summary',serialNum:'SUMMARY',title:'订单号:148396机芯号:CORE-A产品型号:MODEL-A客户简称:示例甲出货方式:CBU总数量:0订单号:HA148396机芯号:CORE-B产品型号:MODEL-B客户简称:示例乙出货方式:SKD总数量:200'});
|
||||
await page.getByRole('button',{name:'重新读取',exact:true}).click();await page.getByRole('button',{name:'选择订单 SUMMARY',exact:true}).click();
|
||||
const table=page.locator('#fm-recognition [data-summary-orders]');await table.getByRole('cell',{name:'CBU',exact:true}).waitFor();
|
||||
assert.equal(await table.getByRole('cell',{name:'示例甲',exact:true}).count(),1);assert.equal(await table.getByRole('cell',{name:'0',exact:true}).count(),1);assert.equal(await table.getByRole('cell',{name:'SKD',exact:true}).count(),1);
|
||||
assert.deepEqual(runtime.orderRules.all('field-mapping-drafts'),[]);await page.setViewportSize({width:390,height:844});assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true);
|
||||
});
|
||||
test('selecting an order locates its real version and recognizes zero and HA without configuration writes',{timeout:90000},async t=>{
|
||||
const {page,runtime,captured}=await orderDrivenUI(t),before=runtime.orderRules.all('rules');await page.getByRole('button',{name:'选择订单 S-1',exact:true}).click();await page.locator('#fm-recognition [data-recognition-field="orderNo"]').getByText('148396',{exact:true}).waitFor();assert.match(await page.locator('#fm-heading').innerText(),/备损订单更改评审.*1.4/);assert.match(await page.locator('#fm-recognition').innerText(),/HA148396/);assert.equal(await page.locator('#fm-orderNo').isVisible(),false);assert.equal(await page.evaluate(()=>PageLifecycle.dirty()),false);assert.deepEqual(runtime.orderRules.all('rules'),before);assert.deepEqual(runtime.orderRules.all('field-mapping-drafts'),[]);assert.equal(runtime.orderRules.settings().enabled,false);
|
||||
await page.locator('#fm-save').click();await page.getByText('字段对应草稿已保存。',{exact:true}).waitFor();assert.equal(runtime.orderRules.all('field-mapping-drafts').length,1);assert.equal(runtime.orderRules.all('field-adapters').length,0);assert.equal(await page.locator('#fm-activate').isDisabled(),true);await page.locator('#fm-check').click();await page.getByText('识别检查完成,请核对订单与文件名。',{exact:true}).waitFor();await page.locator('#fm-confirm').check();await page.locator('#fm-activate').click();await page.getByText('字段对应已确认生效。',{exact:true}).waitFor();assert.equal(runtime.orderRules.all('field-adapters')[0].sampleId,captured.id);assert.deepEqual(runtime.orderRules.all('orders'),[]);assert.deepEqual(runtime.orderRules.all('batches'),[]);
|
||||
await fs.mkdir('output/verification',{recursive:true});await page.screenshot({path:'output/verification/order-driven-mapping-desktop.png',fullPage:true});await page.setViewportSize({width:390,height:844});assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true);await page.screenshot({path:'output/verification/order-driven-mapping-mobile.png',fullPage:true});
|
||||
});
|
||||
test('ambiguous candidates edit page only, guard context changes, and an acknowledged lost save is verified before retry',{timeout:90000},async t=>{
|
||||
const {page,runtime,capture}=await orderDrivenUI(t);capture({taskId:'amb',serialNum:'AMB',fields:{one:'148396',two:'HA148396'}},{one:'订单号',two:'订单号'});await page.getByRole('button',{name:'重新读取',exact:true}).click();await page.getByRole('button',{name:'选择订单 AMB',exact:true}).click();await page.locator('#fm-recognition').getByRole('button',{name:'订单号 · 148396',exact:true}).click();await page.waitForFunction(()=>PageLifecycle.dirty());assert.deepEqual(runtime.orderRules.all('field-mapping-drafts'),[]);await page.getByRole('button',{name:'选择订单 S-1',exact:true}).click();await page.getByRole('button',{name:'留在此页',exact:true}).click();assert.match(await page.locator('#fm-sample-meta').innerText(),/AMB/);
|
||||
let writes=0;await page.route('**/api/order-rules/field-mappings/draft',async route=>{writes++;await route.fetch();await route.abort('failed');});await page.locator('#fm-save').click();await page.getByText(/字段对应草稿已保存/).waitFor();assert.equal(writes,1);assert.equal(runtime.orderRules.all('field-mapping-drafts')[0].version,1);assert.equal(await page.evaluate(()=>PageLifecycle.dirty()),false);
|
||||
});
|
||||
|
||||
test('a late proposal cannot replace a newer order and an expired login retires the page',{timeout:90000},async t=>{
|
||||
const {page,capture,captured,base}=await orderDrivenUI(t);capture({taskId:'second',serialNum:'SECOND',title:'订单号:200机芯号:Z',fields:{order:'200',qty:8}});await page.getByRole('button',{name:'重新读取',exact:true}).click();let release,arrive;const gate=new Promise(r=>release=r),arrived=new Promise(r=>arrive=r);await page.route('**/api/order-rules/field-mappings/propose',async route=>{if(route.request().postDataJSON().sampleId===captured.id){const response=await route.fetch();arrive();await gate;await route.fulfill({response});}else await route.continue();});await page.getByRole('button',{name:'选择订单 S-1',exact:true}).click();await arrived;await page.getByRole('button',{name:'选择订单 SECOND',exact:true}).click();await page.locator('#fm-recognition [data-recognition-field="orderNo"]').getByText('200',{exact:true}).waitFor();release();await page.waitForTimeout(100);assert.equal(await page.locator('#fm-sample-meta').textContent(),'SECOND · 订单专员(订单通知书)');assert.equal(await page.locator('#fm-recognition [data-recognition-field="orderNo"]').innerText().then(s=>s.includes('200')),true);
|
||||
await page.unroute('**/api/order-rules/field-mappings/propose');await page.request.post(base+'/api/logout',{headers:{Origin:base},data:{}});await page.getByRole('button',{name:'选择订单 S-1',exact:true}).click();await page.getByLabel('账号',{exact:true}).waitFor();assert.equal(await page.locator('#fm-recognition').count(),0);
|
||||
});
|
||||
|
||||
test('operators and viewers only select their own evidence on both pages and never see configuration actions',{timeout:90000},async t=>{
|
||||
const {runtime,browser,base,capture}=await orderDrivenUI(t),admin=runtime.store.users()[0];for(const role of ['operator','viewer']){runtime.store.addUser({username:role,password:'Test-password-123',role:'operator'},'admin');const connection=runtime.workspace.createConnection({name:role,owner:role},admin,runtime.store.users());runtime.store.commit(d=>{d.users.find(u=>u.username===role).role=role;});capture({taskId:role,connectionId:connection.id,serialNum:'OWN-'+role});const context=await browser.newContext({viewport:{width:390,height:844}}),page=await context.newPage();page.setDefaultTimeout(7000);await page.goto(base+'/#rule-fields');await page.getByLabel('账号',{exact:true}).fill(role);await page.getByLabel('密码',{exact:true}).fill('Test-password-123');await page.getByRole('button',{name:'登录',exact:true}).click();await page.getByRole('button',{name:'选择订单 OWN-'+role,exact:true}).click();await page.locator('#fm-recognition [data-recognition-field="orderNo"]').getByText('148396',{exact:true}).waitFor();assert.equal(await page.getByRole('button',{name:'选择订单 S-1',exact:true}).count(),0);assert.equal(await page.locator('#fm-save').count(),0);assert.equal(await page.getByText('从 BPM 选择',{exact:true}).count(),0);assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true);await page.locator('a[href="#order-rules"]').first().click();await page.locator('[data-rule-id="bs-change"]').click();assert.match(await page.locator('#order-rule-sample-source').innerText(),new RegExp('OWN-'+role));assert.doesNotMatch(await page.locator('#order-rule-sample-source').innerText(),/S-1/);assert.equal(await page.getByRole('button',{name:'检查识别结果',exact:true}).count(),role==='operator'?1:0);assert.equal(await page.locator('#rule-inline-open').count(),0);assert.equal(await page.locator('.rule-save-bar').count(),0);await context.close();}
|
||||
});
|
||||
|
||||
test('an old check cannot confirm a different interrupted check request',{timeout:90000},async t=>{const {page,runtime}=await orderDrivenUI(t);await page.getByRole('button',{name:'选择订单 S-1',exact:true}).click();await page.locator('#fm-recognition [data-recognition-field="orderNo"]').getByText('148396',{exact:true}).waitFor();await page.locator('#fm-save').click();await page.getByText('字段对应草稿已保存。',{exact:true}).waitFor();await page.locator('#fm-check').click();await page.getByText('识别检查完成,请核对订单与文件名。',{exact:true}).waitFor();const before=runtime.orderRules.all('field-mapping-drafts')[0].check.id;await page.route('**/api/order-rules/field-mappings/check',route=>route.abort('failed'));await page.locator('#fm-check').click();await page.getByText(/结果待核实:未能确认同次操作/).waitFor();assert.equal(runtime.orderRules.all('field-mapping-drafts')[0].check.id,before);assert.equal(await page.locator('#fm-activate').isDisabled(),true);});
|
||||
|
||||
test('saving a recommendation refreshes its displayed basis and persisted version',{timeout:90000},async t=>{const {page}=await orderDrivenUI(t);await page.getByRole('button',{name:'选择订单 S-1',exact:true}).click();await page.locator('#fm-recognition').getByText(/当前订单自动候选/).waitFor();await page.locator('#fm-save').click();await page.locator('#fm-recognition').getByText(/草稿 v1/).waitFor();assert.equal(await page.evaluate(()=>PageLifecycle.dirty()),false);});
|
||||
|
||||
test('verified lost save, check and activation responses show one confirmed result without a contradictory unknown banner',{timeout:90000},async t=>{const {page,runtime}=await orderDrivenUI(t);await page.getByRole('button',{name:'选择订单 S-1',exact:true}).click();await page.locator('#fm-recognition [data-recognition-field="orderNo"]').getByText('148396',{exact:true}).waitFor();let writes=0;for(const action of ['draft','check','activate'])await page.route('**/api/order-rules/field-mappings/'+action,async route=>{writes++;await route.fetch();await route.abort('failed');});await page.locator('#fm-save').click();await page.getByText('字段对应草稿已保存。',{exact:true}).waitFor();assert.equal(await page.locator('#operation-uncertain').count(),0);await page.locator('#fm-check').click();await page.getByText('识别检查完成,请核对订单与文件名。',{exact:true}).waitFor();await page.locator('#fm-confirm').check();await page.locator('#fm-activate').click();await page.getByText('字段对应已确认生效。',{exact:true}).waitFor();assert.equal(await page.locator('#operation-uncertain').count(),0);assert.equal(writes,3);assert.equal(runtime.orderRules.all('field-adapters')[0].version,1);});
|
||||
|
||||
test('a failed read-only proposal never creates an uncertain-write banner or state readback',{timeout:90000},async t=>{const {page,runtime}=await orderDrivenUI(t);await page.getByRole('button',{name:'选择订单 S-1',exact:true}).waitFor();let readbacks=0;page.on('request',request=>{if(new URL(request.url()).pathname==='/api/order-rules/fields')readbacks++;});await page.route('**/api/order-rules/field-mappings/propose',route=>route.abort('failed'));await page.getByRole('button',{name:'选择订单 S-1',exact:true}).click();await page.locator('#fm-recognition').getByText(/识别读取失败/).waitFor();assert.equal(await page.locator('#operation-uncertain').count(),0);assert.equal(readbacks,0);assert.deepEqual(runtime.orderRules.all('field-mapping-requests'),[]);});
|
||||
@@ -0,0 +1,44 @@
|
||||
'use strict';
|
||||
const test=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs/promises');
|
||||
const {orderDrivenUI}=require('../fixtures/order-driven-ui.cjs');
|
||||
function activate(runtime,captured){
|
||||
const store=runtime.orderRules,admin={username:'admin',role:'admin'};
|
||||
const draft=store.saveMapping({processName:captured.processName,processVersion:captured.processVersion,sampleId:captured.id,version:0,sources:{orderNo:{type:'form',path:'order'},quantity:{type:'form',path:'qty'},brief:{type:'title'}},idempotencyKey:'business-map'},admin);
|
||||
const check=store.checkMapping({id:draft.id,version:draft.version,sampleId:captured.id,idempotencyKey:'business-check'},admin);
|
||||
store.activateMapping({id:draft.id,version:draft.version,checkId:check.id,idempotencyKey:'business-activate'},admin);
|
||||
}
|
||||
test('classification edits distribution and checks an active interface without exposing or writing mappings',{timeout:90000},async t=>{
|
||||
const {page,runtime}=await orderDrivenUI(t,'#order-rules');await page.locator('[data-rule-id="bs-change"]').click();
|
||||
assert.equal(await page.locator('#rule-inline-open,#rule-inline-mapping,[data-recognition-candidate],[data-recognition-advanced]').count(),0);
|
||||
await page.getByRole('heading',{name:'适用通知',exact:true}).waitFor();
|
||||
assert.equal(await page.getByLabel('搜索订单号、流水号或标题',{exact:true}).count(),0);
|
||||
assert.equal(await page.getByLabel('第1行适用流程',{exact:true}).isVisible(),true);
|
||||
const before=runtime.orderRules.all('field-mapping-drafts');await page.getByLabel('收件人',{exact:true}).fill('distribution@example.test');
|
||||
await page.getByRole('button',{name:'检查识别结果',exact:true}).click();await page.locator('#order-rule-preview-result').getByText('需要处理',{exact:true}).waitFor();
|
||||
assert.equal(runtime.orderRules.get('rules','bs-change').trialVersion,null);assert.deepEqual(runtime.orderRules.all('field-mapping-drafts'),before);
|
||||
assert.equal(await page.getByLabel('收件人',{exact:true}).inputValue(),'distribution@example.test');
|
||||
assert.deepEqual(runtime.orderRules.all('orders'),[]);assert.deepEqual(runtime.orderRules.all('batches'),[]);assert.equal(runtime.orderRules.settings().enabled,false);
|
||||
});
|
||||
test('business verification consumes the active mapping even when a different mapping draft exists',{timeout:90000},async t=>{
|
||||
const {page,runtime,captured}=await orderDrivenUI(t,'#order-rules');activate(runtime,captured);
|
||||
const active=runtime.orderRules.all('field-adapters')[0];runtime.orderRules.saveMapping({processName:captured.processName,processVersion:captured.processVersion,sampleId:captured.id,version:1,sources:{orderNo:{type:'form',path:'date'},brief:{type:'title'}},idempotencyKey:'different-draft'},{username:'admin',role:'admin'});
|
||||
await page.getByRole('button',{name:'刷新规则与字段',exact:true}).click();await page.locator('[data-rule-id="bs-change"]').click();
|
||||
await page.getByRole('button',{name:'检查识别结果',exact:true}).click();await page.locator('#order-rule-preview-result').getByText('148396',{exact:true}).waitFor();
|
||||
assert.match(await page.locator('#order-rule-preview-result').innerText(),/HA148396/);assert.equal(runtime.orderRules.all('field-adapters')[0].version,active.version);
|
||||
assert.equal(runtime.orderRules.all('field-mapping-drafts')[0].version,2);
|
||||
await fs.mkdir('output/verification',{recursive:true});await page.screenshot({path:'output/verification/business-distribution-desktop.png',fullPage:true});
|
||||
await page.setViewportSize({width:390,height:844});assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true);await page.screenshot({path:'output/verification/business-distribution-mobile.png',fullPage:true});
|
||||
});
|
||||
test('classification excludes history from notification verification and never offers guessed historical nodes',{timeout:90000},async t=>{
|
||||
const {page,capture}=await orderDrivenUI(t,'#order-rules');capture({taskId:'history',source:'history',configurationOnly:true,timestampType:'process-start',nodeName:'历史查看(未提供办理节点)',serialNum:'HISTORY'});
|
||||
await page.getByRole('button',{name:'刷新规则与字段',exact:true}).click();await page.locator('[data-rule-id="bs-change"]').click();
|
||||
assert.doesNotMatch(await page.locator('#order-rule-sample-source').innerText(),/HISTORY/);assert.equal(await page.locator('[data-scope-node] option').filter({hasText:'历史查看'}).count(),0);
|
||||
});
|
||||
test('leaving distribution for mapping respects unsaved inputs and business search does not submit the rule',{timeout:90000},async t=>{
|
||||
const {page,runtime}=await orderDrivenUI(t,'#order-rules');await page.locator('[data-rule-id="bs-change"]').click();const version=runtime.orderRules.get('rules','bs-change').draft.version;
|
||||
await page.getByLabel('收件人',{exact:true}).fill('keep@example.test');await page.getByLabel('搜索流程或节点',{exact:true}).fill('备损');await page.getByLabel('搜索流程或节点',{exact:true}).press('Enter');
|
||||
assert.equal(runtime.orderRules.get('rules','bs-change').draft.version,version);
|
||||
await page.getByRole('link',{name:'字段映射',exact:true}).first().click();await page.getByRole('button',{name:'留在此页',exact:true}).click();assert.equal(await page.getByLabel('收件人',{exact:true}).inputValue(),'keep@example.test');
|
||||
await page.getByRole('link',{name:'字段映射',exact:true}).first().click();await page.getByRole('button',{name:'放弃并继续',exact:true}).click();await page.locator('#fm-orderNo').waitFor({state:'attached'});
|
||||
assert.deepEqual(runtime.orderRules.all('field-mapping-drafts'),[]);
|
||||
});
|
||||
@@ -0,0 +1,60 @@
|
||||
'use strict';
|
||||
const test=require('node:test'),assert=require('node:assert/strict');
|
||||
const {queryOrders,queryBatches,orderDetail,batchDetail,readOrderFile}=require('../../src/modules/order-rules/query.cjs');
|
||||
function fixture(){
|
||||
const rows=Array.from({length:83},(_,i)=>({id:'o'+i,status:'pending',categoryId:'cat',event:{connectionId:'a',orderNo:'NO'+i,receivedAt:'2026-10-20T10:00:00Z',fields:{secret:'raw'}},sample:{connectionId:'a',fields:{secret:'raw'}}}));
|
||||
rows.push({id:'foreign',sample:{connectionId:'b'},event:{orderNo:'PRIVATE'},status:'blocked'});
|
||||
const records={orders:rows,batches:[{id:'old',orderIds:['o0'],status:'prepared',windowStart:'2020-01-01',text:'frozen'},{id:'mixed',orderIds:['o0','foreign'],status:'unknown',text:'SECRET'}],'execution-tasks':[], 'execution-candidates':[], 'business-issues':[]};
|
||||
const store={all:k=>records[k]||[],get:(k,id)=>(records[k]||[]).find(r=>r.id===id),queryRevision:()=>1};
|
||||
return {orderRules:store,workspace:{recordSources:()=>[{id:'a',owner:'alice'},{id:'b',owner:'bob'}]},execution:{archive:{read:async()=>Buffer.from('%PDF-x')}}};
|
||||
}
|
||||
const user={username:'alice',role:'operator'};
|
||||
test('authorized queries paginate to actual last page, filter and reject invalid enums',()=>{
|
||||
const c=fixture(),result=queryOrders(c,{page:999,pageSize:25},user);assert.equal(result.page,4);assert.equal(result.total,83);assert.equal(result.items.length,8);assert.equal(result.from,76);assert.equal(result.to,83);
|
||||
assert.equal(JSON.stringify(result).includes('raw'),false);
|
||||
assert.equal(queryOrders(c,{q:'PRIVATE'},user).total,0);assert.equal(queryOrders(c,{q:'none',page:99},user).page,1);
|
||||
assert.throws(()=>queryOrders(c,{status:'made-up'},user));assert.throws(()=>queryBatches(c,{scope:'made-up'},user));
|
||||
});
|
||||
test('old prepared remains active, mixed source evidence is denied and permissions are rechecked',()=>{
|
||||
const c=fixture();assert.deepEqual(queryBatches(c,{scope:'active'},user).items.map(b=>b.id),['old']);assert.throws(()=>orderDetail(c,'foreign',user));assert.throws(()=>batchDetail(c,'mixed',user));
|
||||
c.workspace.recordSources=()=>[{id:'a',owner:'bob'}];assert.equal(queryOrders(c,{},user).total,0);
|
||||
});
|
||||
test('task-only blocked work remains visible and private raw fields never leave detail',()=>{
|
||||
const c=fixture();c.orderRules.all('execution-tasks').push({id:'task',connectionId:'a',status:'blocked',row:{orderNo:'MISSED',fields:{secret:'raw'}},missedWindow:{start:'2020'}});
|
||||
assert.equal(queryOrders(c,{},user).total,84);assert.equal(orderDetail(c,'task:task',user).executionTask.id,'task');assert.equal(JSON.stringify(orderDetail(c,'o0',user)).includes('raw'),false);
|
||||
});
|
||||
|
||||
test('unconfirmed notification candidates are visible with reasons and retain connection permissions',()=>{
|
||||
const c=fixture();c.orderRules.all('execution-candidates').push({id:'candidate-a',connectionId:'a',status:'candidate',reason:'未确认通知节点,需要核验',row:{source:'todo',taskId:'T-A',processName:'海外运营订单评审',nodeName:'订单专员(生效)',receivedAt:'2026-10-23T00:00:00Z',fields:{secret:'raw'}}},{id:'candidate-b',connectionId:'b',status:'candidate',reason:'PRIVATE',row:{taskId:'T-B'}});
|
||||
const result=queryOrders(c,{status:'candidate'},user);assert.equal(result.total,1);assert.equal(result.items[0].id,'candidate:candidate-a');assert.equal(result.items[0].reason,'未确认通知节点,需要核验');assert.equal(result.items[0].nodeName,'订单专员(生效)');
|
||||
const detail=orderDetail(c,result.items[0].id,user);assert.equal(detail.status,'candidate');assert.equal(detail.executionTask,null);assert.deepEqual(detail.files,[]);assert.deepEqual(detail.batches,[]);assert.equal(JSON.stringify(detail).includes('raw'),false);assert.throws(()=>orderDetail(c,'candidate:candidate-b',user));
|
||||
});
|
||||
test('file endpoint reauthorizes and validates bytes against durable evidence',async()=>{
|
||||
const c=fixture(),bytes=Buffer.from('%PDF-x');c.orderRules.get('orders','o0').archive={files:[{name:'a.pdf',path:'server-only',size:bytes.length,sha256:require('node:crypto').createHash('sha256').update(bytes).digest('hex')}]};
|
||||
assert.deepEqual((await readOrderFile(c,'o0',0,user)).bytes,bytes);c.execution.archive.read=async()=>Buffer.from('tampered');await assert.rejects(()=>readOrderFile(c,'o0',0,user));await assert.rejects(()=>readOrderFile(c,'foreign',0,user));
|
||||
});
|
||||
test('batch pagination covers more than three pages and scope all retains completed history',()=>{
|
||||
const c=fixture();for(let i=0;i<85;i++)c.orderRules.all('batches').push({id:'b'+i,orderIds:['o0'],status:i===0?'sent':'prepared',subject:'Batch '+i});
|
||||
const active=queryBatches(c,{page:999,pageSize:25},user);assert.equal(active.page,4);assert.equal(active.total,85);assert.equal(active.items.length,10);assert.equal(queryBatches(c,{scope:'all'},user).total,86);
|
||||
});
|
||||
test('HTTP query routing rejects missing services, invalid parameters and malformed encoding',async()=>{
|
||||
const {orderRuleQueryApi}=require('../../src/modules/order-rules/query-api.cjs');const c=fixture(),invoke=(route,extra={})=>orderRuleQueryApi({...c,user,route,method:'GET',url:new URL(route,'http://localhost'),reply(){},...extra});
|
||||
await assert.rejects(()=>invoke('/api/order-rules/orders?unused=1',{route:'/api/order-rules/orders'}),e=>e.status===400||e.statusCode===400);
|
||||
await assert.rejects(()=>invoke('/api/order-rules/orders/%ZZ'),e=>e.status===400||e.statusCode===400);
|
||||
await assert.rejects(()=>invoke('/api/order-rules/orders',{orderRules:null}),e=>e.status===503||e.statusCode===503);
|
||||
assert.equal(await invoke('/api/unrelated'),false);
|
||||
});
|
||||
test('date filters use the displayed Beijing business day rather than UTC midnight',()=>{
|
||||
const c=fixture();c.orderRules.all('orders').push({id:'night',status:'pending',sample:{connectionId:'a'},event:{connectionId:'a',orderNo:'NIGHT',receivedAt:'2026-10-20T16:30:00Z'}});
|
||||
assert.equal(queryOrders(c,{from:'2026-10-21',to:'2026-10-21'},user).total,1);
|
||||
assert.equal(queryOrders(c,{from:'2026-10-20',to:'2026-10-20'},user).total,83);
|
||||
});
|
||||
test('batch date range follows the frozen business window, including old prepared work',()=>{
|
||||
const c=fixture(),batch=c.orderRules.get('batches','old');batch.createdAt='2026-10-21T00:00:00Z';batch.window={start:'2020-01-01T00:00:00Z',end:'2020-01-01T03:00:00Z'};
|
||||
assert.equal(queryBatches(c,{from:'2020-01-01',to:'2020-01-01'},user).total,1);
|
||||
});
|
||||
|
||||
test('order list and detail select the same latest live revision with genuine previous evidence',()=>{
|
||||
const c=fixture(),tasks=c.orderRules.all('execution-tasks');tasks.push({id:'original',connectionId:'a',orderId:'o0',row:{revision:'1',orderNo:'OLD'},status:'archived',createdAt:'2026-10-20T00:00:00Z'},{id:'incoming',connectionId:'a',orderId:'o0',previousTaskId:'original',conflict:true,conflictRow:{revision:'2',orderNo:'NEW'},row:{revision:'2',orderNo:'NEW'},status:'blocked',createdAt:'2026-10-21T00:00:00Z'});
|
||||
const row=queryOrders(c,{q:'o0'},user).items.find(i=>i.id==='o0'),detail=orderDetail(c,'o0',user);assert.equal(row.executionTaskId,'incoming');assert.equal(detail.executionTask.id,row.executionTaskId);assert.equal(detail.executionTask.conflict,true);assert.equal(detail.executionTask.revisionEvidence.previous.revision,'1');assert.equal(detail.executionTask.revisionEvidence.incoming.revision,'2');
|
||||
});
|
||||
@@ -0,0 +1,57 @@
|
||||
'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 {recommendFields}=require('../../src/modules/order-rules/field-recommendation.cjs');
|
||||
const admin={username:'admin',role:'admin'};
|
||||
function fixture(t){
|
||||
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'recognition-')),store=new RuleStore(dir,{clock:()=>new Date('2026-10-20T02:00:00Z')});
|
||||
t.after(()=>{store.close();fs.rmSync(dir,{recursive:true,force:true});});
|
||||
const sample={source:'todo',connectionId:'c1',instanceId:'i1',taskId:'t1',revision:1,processName:'备损订单更改评审',processVersion:'1.4',nodeName:'订单专员(订单通知书)',receivedAt:'2026-10-20T01:00:00Z',serialNum:'S-1',title:'订单号:148396机芯号:X客户简称:甲总数量:0订单号:HA148396客户简称:乙总数量:5',fields:{order:'148396',qty:0,amount:500,date:'2026-10-20'}};
|
||||
const capture=(overrides={},labels={})=>{const s={...sample,...overrides};return store.recordCapture({taskId:s.taskId,sample:s,snapshot:{processVersion:s.processVersion,fields:Object.entries(s.fields).map(([path,value])=>({path,value,label:labels[path]||({order:'订单号',qty:'订单数量',amount:'总金额',date:'申请日期'})[path]||path}))}});};
|
||||
return {store,sample,capture,captured:capture()};
|
||||
}
|
||||
const kinds=['rules','field-mapping-drafts','field-adapters','orders','batches','execution-tasks','field-mapping-requests','audit'];
|
||||
const snapshot=store=>Object.fromEntries(kinds.map(k=>[k,store.all(k)]));
|
||||
test('unique explicit labels recommend real sources, preserving zero and rejecting component quantities',()=>{
|
||||
const r=recommendFields([{path:'form.order',label:'订单号',value:'148396'},{path:'form.qty',label:'订单数量',value:0},{path:'form.amount',label:'总金额',value:500},{path:'part.count',label:'数量',value:2}]);
|
||||
assert.equal(r.sources.orderNo.path,'form.order');assert.equal(r.sources.quantity.path,'form.qty');assert.equal(r.sources.totalAmount.path,'form.amount');assert.equal(r.sources.customer,undefined);assert.deepEqual(r.sources.brief,{type:'title'});
|
||||
const a=recommendFields([{path:'one',label:'订单号',value:'148396'},{path:'two',label:'订单号',value:'HA148396'}]);assert.equal(a.sources.orderNo,undefined);assert.equal(a.candidates.orderNo.length,2);
|
||||
assert.equal(recommendFields([{label:'订单号',value:'123'}]).sources.orderNo,undefined);
|
||||
});
|
||||
test('selected orders recognize their own values and proposals never persist configuration or publication evidence',t=>{
|
||||
const f=fixture(t),before=snapshot(f.store),p=f.store.proposeMapping({sampleId:f.captured.id,ruleId:'bs-change',ruleVersion:1});
|
||||
assert.equal(p.mapping.basis,'recommended');assert.equal(p.recognition.valid,true);assert.equal(p.recognition.event.quantity,0);assert.match(p.recognition.event.brief,/HA148396/);assert.equal(p.recognition.publishEvidence,false);assert.deepEqual(p.scopeCandidate,{processName:f.sample.processName,nodeName:f.sample.nodeName});assert.equal(p.classification.status,'matched');assert.deepEqual(snapshot(f.store),before);
|
||||
const draft=f.store.saveMapping({processName:f.sample.processName,processVersion:'1.4',sampleId:f.captured.id,sources:{orderNo:{type:'form',path:'order'},brief:{type:'title'}},version:0,idempotencyKey:'d'},admin);
|
||||
const second=f.capture({taskId:'two',title:'订单号:200机芯号:Y',fields:{order:'200',qty:8}}),b=snapshot(f.store),p2=f.store.proposeMapping({sampleId:second.id});assert.equal(p2.mapping.basis,'draft');assert.equal(p2.mapping.id,draft.id);assert.equal(p2.recognition.event.orderNo,'200');assert.equal(p2.mapping.sources.quantity,undefined);assert.equal(p2.recognition.event.quantity,null);assert.deepEqual(snapshot(f.store),b);
|
||||
const next=f.capture({taskId:'new',processVersion:'1.5'});assert.equal(f.store.proposeMapping({sampleId:next.id}).mapping.basis,'recommended');
|
||||
});
|
||||
test('ambiguity and missing order fields produce complete blocked results; forged sources are rejected',t=>{
|
||||
const f=fixture(t),amb=f.capture({taskId:'amb',fields:{a:'148396',b:'HA148396'}},{a:'订单号',b:'订单号'}),p=f.store.proposeMapping({sampleId:amb.id});
|
||||
assert.equal(p.recognition.valid,false);assert.equal(p.fields.find(f=>f.key==='orderNo').state,'ambiguous');assert.equal(p.fields.find(f=>f.key==='orderNo').candidates.length,2);assert.ok(p.blockedReasons.length);
|
||||
assert.throws(()=>f.store.proposeMapping({sampleId:amb.id,sources:{orderNo:{type:'form',path:'invented'}}}),{status:400});
|
||||
const unknown=f.capture({taskId:'unknown',processVersion:''});assert.equal(f.store.proposeMapping({sampleId:unknown.id}).recognition.valid,false);
|
||||
});
|
||||
test('history never proposes a node; unconfirmed scope is candidate and other categories block matching',t=>{
|
||||
const f=fixture(t),h=f.capture({taskId:'history',source:'history',configurationOnly:true,timestampType:'process-start',nodeName:'历史查看(未提供办理节点)'}),hp=f.store.proposeMapping({sampleId:h.id,ruleId:'bs-change',ruleVersion:1});assert.equal(hp.scopeCandidate,null);assert.equal(hp.classification.status,'history');assert.equal(hp.effects,null);
|
||||
const n=f.capture({taskId:'other-node',nodeName:'主管审核'}),p=f.store.proposeMapping({sampleId:n.id,ruleId:'bs-change',ruleVersion:1});assert.equal(p.classification.status,'candidate');assert.equal(p.effects,null);
|
||||
const rule=f.store.get('rules','bs-change').draft,other=f.store.get('rules','bs-notice');other.draft.scopes=[{processName:f.sample.processName,nodeName:'主管审核'}];f.store.put('rules',other);
|
||||
const conflict=f.store.proposeMapping({sampleId:n.id,ruleId:rule.id,ruleVersion:rule.version,ruleDraft:{...rule,scopes:[...require('../../src/modules/order-rules/scopes.cjs').scopesFor(rule),{processName:f.sample.processName,nodeName:'主管审核'}]}});assert.equal(conflict.classification.status,'conflict');assert.ok(conflict.conflicts.some(c=>c.ruleId==='bs-notice'));assert.equal(conflict.effects,null);
|
||||
});
|
||||
test('unsaved rule dates, subject and directory affect preview without changing stored rules',t=>{
|
||||
const f=fixture(t),rule=f.store.get('rules','bs-change').draft,before=snapshot(f.store),draft={...rule,filenameDate:'appDate',subjectPrefix:'待保存主题',archiveDirectory:'\\\\server\\share\\pending',to:['test@example.test']};
|
||||
const p=f.store.proposeMapping({sampleId:f.captured.id,ruleId:rule.id,ruleVersion:rule.version,ruleDraft:draft});assert.equal(p.recognition.valid,true);assert.match(p.effects.path,/pending/);assert.match(p.effects.mail.subject,/待保存主题/);assert.equal(p.effects.simulation,true);assert.equal(p.effects.archiveVerified,false);assert.deepEqual(snapshot(f.store),before);
|
||||
const bad=f.capture({taskId:'bad-date',fields:{order:'148396',date:'2026-02-30'}});const b=f.store.proposeMapping({sampleId:bad.id,ruleId:rule.id,ruleVersion:rule.version,ruleDraft:draft});assert.equal(b.recognition.valid,false);assert.match(b.blockedReasons.join(' '),/日期/);assert.equal(b.effects,null);
|
||||
assert.throws(()=>f.store.proposeMapping({sampleId:f.captured.id,ruleId:rule.id,ruleVersion:0}),{status:409});
|
||||
});
|
||||
|
||||
test('duplicate active mappings remain blocked even when a saved draft exists',t=>{const f=fixture(t);f.store.saveMapping({processName:f.sample.processName,processVersion:'1.4',sampleId:f.captured.id,sources:{orderNo:{type:'form',path:'order'}},version:0,idempotencyKey:'duplicate-draft'},admin);for(const id of ['active-one','active-two'])f.store.put('field-adapters',{id,processName:f.sample.processName,processVersion:'1.4',verified:true,version:1,sources:{orderNo:{type:'form',path:'order'}}});const p=f.store.proposeMapping({sampleId:f.captured.id});assert.equal(p.recognition.valid,false);assert.match(p.blockedReasons.join(';'),/多个生效映射/);});
|
||||
|
||||
test('all fifteen categories reuse methods and recognize the next order independently, including HA and attachment distinctions',t=>{
|
||||
const f=fixture(t);const ids=['overseas-notice','overseas-change','new-retail-notice','new-retail-change','domestic-notice','carrier-notice','hardware-notice','retail-notice','domestic-change','domestic-rework','processing-notice','bs-notice','bs-change','trial-notice','trial-change'];
|
||||
for(const [index,id]of ids.entries()){const rule=f.store.get('rules',id).draft,name=rule.processNames[0],node=rule.nodeNames[0],no='ORDER'+index,title='订单号:'+no+'机芯号:X总数量:0订单号:HA'+no+'机芯号:Y总数量:5',captured=f.capture({taskId:'all-'+id,processName:name,processVersion:'test-'+id,nodeName:node,title,fields:{order:no,qty:0}}),p=f.store.proposeMapping({sampleId:captured.id,ruleId:id,ruleVersion:rule.version});assert.equal(p.classification.status,'matched',id);assert.equal(p.recognition.valid,true,id);assert.equal(p.recognition.event.orderNo,no);assert.equal(p.recognition.event.quantity,0);assert.equal(p.recognition.event.titleOrders.length,2);assert.match(p.recognition.event.brief,new RegExp('HA'+no));
|
||||
const draft=f.store.saveMapping({processName:name,processVersion:'test-'+id,sampleId:captured.id,sources:p.mapping.sources,version:0,idempotencyKey:'save-'+id},admin),check=f.store.checkMapping({id:draft.id,version:draft.version,sampleId:captured.id,idempotencyKey:'check-'+id},admin);assert.equal(check.valid,true,id);f.store.activateMapping({id:draft.id,version:draft.version,checkId:check.id,idempotencyKey:'activate-'+id},admin);
|
||||
const next=f.capture({taskId:'second-'+id,processName:name,processVersion:'test-'+id,nodeName:node,title:'订单号:NEXT'+index+'机芯号:Z',fields:{order:'NEXT'+index,qty:7}}),result=f.store.proposeMapping({sampleId:next.id});assert.equal(result.recognition.event.orderNo,'NEXT'+index);assert.equal(result.recognition.event.quantity,7);assert.equal(f.store.get('field-mapping-drafts',draft.id).version,1);
|
||||
assert.equal(rule.attachPdf,false);
|
||||
}
|
||||
assert.equal(f.store.settings().enabled,false);assert.deepEqual(f.store.all('orders'),[]);assert.deepEqual(f.store.all('batches'),[]);
|
||||
});
|
||||
@@ -0,0 +1,17 @@
|
||||
'use strict';
|
||||
const test=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs/promises'),path=require('node:path');
|
||||
const {loadPlaywright,browserOptions}=require('../../src/platform/browser.cjs');
|
||||
async function setup(t,role='admin'){
|
||||
const browser=await loadPlaywright().chromium.launch(browserOptions());t.after(()=>browser.close());const page=await browser.newPage({viewport:{width:390,height:844}});page.setDefaultTimeout(5000);await page.setContent('<main id="root"></main>');
|
||||
await page.addScriptTag({content:await fs.readFile(path.resolve('web/modules/order-notifications/view.js'),'utf8')});
|
||||
await page.evaluate(async role=>{window.active=true;window.calls=[];window.PageLifecycle={onDispose:()=>{},guard:fn=>fn(),dirty:()=>false};window.run={id:'run-1',version:2,enabled:true,recipient:'test@qq.com',archiveRoot:'\\\\localhost\\C$\\Users\\test\\Desktop\\run',since:'2026-10-22T01:00:00Z',ruleCount:15,readyCount:15,uncovered:[]};window.OrderNotificationViews.configure({user:{role},esc:v=>String(v??'').replaceAll('<','<'),formatDate:v=>v||'—',api:async(url,body)=>{if(body){calls.push({url,body});return new Promise((resolve,reject)=>{window.finish=()=>resolve({...run,version:3,enabled:false});window.fail=()=>reject(Error('保存失败'));});}return url==='/mail'?{channels:[]}:{settings:{version:1,enabled:true,processingEnabled:true},restrictedTest:run};}});await OrderNotificationViews.render(document.querySelector('#root'),()=>active,'settings');},role);return page;
|
||||
}
|
||||
test('settings shows fixed restricted scope and pause is single-flight with failure recovery',async t=>{
|
||||
const page=await setup(t);assert.match(await page.locator('main').innerText(),/受限稳定性测试/);assert.match(await page.locator('main').innerText(),/15/);assert.match(await page.locator('main').innerText(),/test@qq.com/);
|
||||
const button=page.getByRole('button',{name:'暂停测试',exact:true});await button.click();assert.equal(await button.isDisabled(),true);await page.evaluate(()=>fail());await page.getByText('保存失败',{exact:true}).waitFor();assert.equal(await button.isEnabled(),true);
|
||||
await button.click();await page.evaluate(()=>finish());await page.getByRole('button',{name:'恢复测试',exact:true}).waitFor();
|
||||
assert.deepEqual(await page.evaluate(()=>calls.map(c=>c.body)),[{version:2,enabled:false},{version:2,enabled:false}]);assert.equal(await page.locator('input[value="test@qq.com"]').count(),0);
|
||||
});
|
||||
test('readonly members see restricted scope without an enable or pause action',async t=>{
|
||||
const page=await setup(t,'viewer');assert.match(await page.locator('main').innerText(),/受限稳定性测试/);assert.equal(await page.getByRole('button',{name:'暂停测试',exact:true}).count(),0);
|
||||
});
|
||||
@@ -0,0 +1,115 @@
|
||||
'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;
|
||||
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);
|
||||
});
|
||||
@@ -0,0 +1,19 @@
|
||||
'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 {catalogFieldSamples}=require('../../src/modules/order-execution/field-sample-catalog.cjs');
|
||||
const {orderExecutionApi}=require('../../src/modules/order-execution/api.cjs');
|
||||
function fixture(t){const dir=fs.mkdtempSync(path.join(os.tmpdir(),'sample-catalog-')),store=new RuleStore(dir);t.after(()=>{store.close();fs.rmSync(dir,{recursive:true,force:true});});const connections={one:{id:'one',owner:'member',status:'connected'},two:{id:'two',owner:'other',status:'connected'}},workspace={getConnection:id=>connections[id]};
|
||||
const add=(id,connectionId='one',at='2026-10-20T01:00:00Z',source='todo')=>{const sample={connectionId,source,processName:'流程',processVersion:'1',nodeName:source==='history'?'历史查看(未提供办理节点)':'通知',serialNum:id,title:'订单号:123机芯号:X <script>bad()</script>',fields:{order:'123'},receivedAt:at};const s={id,provenance:'server-provider',evidenceHash:'hash',processName:'流程',processVersion:'1',capturedAt:at,sample,snapshot:{fields:[{path:'order',label:'订单号',value:'123'}]}};store.put('capture-samples',s);return s;};add('a');add('b','one','2026-10-20T00:00:00Z');add('c','two');add('h','one','2026-10-19T00:00:00Z','history');return {store,workspace,connections,add};}
|
||||
const principal=role=>({user:{username:'member',role},sessionId:'session'});
|
||||
test('catalog authorizes before search and paging, returns only summaries and separates history',t=>{const f=fixture(t);for(const role of ['operator','viewer']){const p=catalogFieldSamples(f,{},principal(role));assert.deepEqual(p.items.map(x=>x.id),['a','b']);assert.equal(p.items[0].orderNo,'123');assert.equal(JSON.stringify(p).includes('snapshot'),false);assert.equal(p.items[0].fields,undefined);assert.equal(p.items[0].title.includes('<script>'),true);assert.throws(()=>catalogFieldSamples(f,{connectionId:'two'},principal(role)),{status:403});}
|
||||
assert.equal(catalogFieldSamples(f,{},principal('admin')).items.length,3);assert.equal(catalogFieldSamples(f,{source:'history'},principal('viewer')).items[0].nodeName,null);assert.equal(catalogFieldSamples(f,{q:'123'},principal('viewer')).items.length,2);assert.equal(catalogFieldSamples(f,{q:'order'},principal('viewer')).items.length,0);
|
||||
f.connections.one.status='disabled';assert.equal(catalogFieldSamples(f,{},principal('admin')).items.length,1);assert.throws(()=>catalogFieldSamples(f,{connectionId:'one'},principal('admin')),{status:403});
|
||||
});
|
||||
test('exclusive cursor boundaries survive insertions, reject malformed queries and never confer authorization',t=>{const f=fixture(t),p=principal('viewer'),first=catalogFieldSamples(f,{limit:'1'},p);assert.equal(first.items[0].id,'a');assert.ok(first.nextCursor);f.add('new','one','2026-10-20T02:00:00Z');assert.deepEqual(catalogFieldSamples(f,{limit:'1',cursor:first.nextCursor},p).items.map(x=>x.id),['b']);f.connections.one.owner='other';assert.deepEqual(catalogFieldSamples(f,{cursor:first.nextCursor},p),{items:[],nextCursor:null});for(const query of [{limit:0},{limit:51},{limit:'1.5'},{source:'invalid'},{q:'x'.repeat(201)},{cursor:'invalid'},{cursor:Buffer.from(JSON.stringify({at:'bad',id:'x'})).toString('base64url')},{unknown:'x'}])assert.throws(()=>catalogFieldSamples(f,query,p),{status:400});});
|
||||
test('preview API permits authorized read roles while overrides and original mutations remain admin-only',async t=>{const f=fixture(t);let output;const args={orderRules:f.store,workspace:f.workspace,reply:(status,value)=>{output={status,value};},sessionId:'session'};for(const role of ['admin','operator','viewer']){const user=principal(role).user;assert.equal(await orderExecutionApi({...args,user,method:'GET',route:'/api/order-rules/field-samples/catalog',url:new URL('http://local/api/order-rules/field-samples/catalog?limit=1')}),true);assert.equal(output.value.items.length,1);assert.equal(await orderExecutionApi({...args,user,method:'POST',route:'/api/order-rules/field-mappings/propose',body:{sampleId:'a'}}),true);assert.equal(output.value.sampleId,'a');if(role!=='admin')for(const override of [{sources:{}},{ruleDraft:{}}])await assert.rejects(orderExecutionApi({...args,user,method:'POST',route:'/api/order-rules/field-mappings/propose',body:{sampleId:'a',...override}}),{status:403});}
|
||||
for(const [body,status]of [[{sampleId:'a',fields:{}},400],[{sampleId:'missing'},404],[{sampleId:'a',ruleId:'bs-change',ruleVersion:0},409],[{sampleId:'c'},403]])await assert.rejects(orderExecutionApi({...args,user:principal('viewer').user,method:'POST',route:'/api/order-rules/field-mappings/propose',body}),{status});
|
||||
await assert.rejects(orderExecutionApi({...args,method:'POST',route:'/api/order-rules/field-mappings/propose',body:{sampleId:'a'}}),{status:401});for(const action of ['draft','check','activate'])await assert.rejects(orderExecutionApi({...args,user:principal('viewer').user,method:'POST',route:'/api/order-rules/field-mappings/'+action,body:{}}),{status:403});
|
||||
});
|
||||
|
||||
test('directory view omits full fields and old check values; selected advanced fields stay available',async t=>{const f=fixture(t);let result;f.store.put('field-mapping-drafts',{id:'d',processName:'流程',processVersion:'1',sampleId:'a',sources:{orderNo:{type:'form',path:'order'}},version:1,check:{sampleId:'a',valid:true,result:{event:{customer:'OLD PRIVATE VALUE'}}}});const args={orderRules:f.store,workspace:f.workspace,user:principal('admin').user,sessionId:'s',method:'GET',route:'/api/order-rules/fields',reply:(status,value)=>{result=value;}};await orderExecutionApi({...args,url:new URL('http://local/api/order-rules/fields?view=directory')});assert.equal(JSON.stringify(result).includes('OLD PRIVATE VALUE'),false);assert.equal(result.samples[0].fields,undefined);assert.equal(result.samples[0].sample.fields,undefined);await orderExecutionApi(args);assert.equal(result.samples[0].fields[0].path,'order');});
|
||||
@@ -0,0 +1,17 @@
|
||||
'use strict';
|
||||
const test=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs/promises'),path=require('node:path');
|
||||
const {loadPlaywright,browserOptions}=require('../../src/platform/browser.cjs');
|
||||
async function setup(t){const browser=await loadPlaywright().chromium.launch(browserOptions());t.after(()=>browser.close());const page=await browser.newPage({viewport:{width:1000,height:900}});page.setDefaultTimeout(5000);await page.setContent('<main id="picker"></main><section id="result"></section>');for(const file of ['sample-picker.js','recognition-panel.js'])await page.addScriptTag({content:await fs.readFile(path.resolve('web/modules/field-mappings',file),'utf8')});await page.addStyleTag({content:await fs.readFile('web/modules/field-mappings/view.css','utf8')});return page;}
|
||||
test('search and paging select evidence without writes, escape titles, cancel selection and fit mobile',async t=>{const page=await setup(t);await page.evaluate(()=>{window.calls=[];window.selectedSamples=[];const esc=v=>String(v??'').replaceAll('&','&').replaceAll('<','<').replaceAll('"','"');window.picker=FieldSamplePicker.mount(document.querySelector('#picker'),{esc,user:{role:'viewer'},processNames:[],connections:[],api:async(url,body)=>{calls.push({url,body});return {items:[{id:url.includes('cursor=next')?'s2':'s1',serialNum:url.includes('cursor=next')?'S-2':'S-1',processName:'流程',processVersion:'1.4',source:'todo',nodeName:'真实节点',title:'<img src=x onerror=window.injected=true>',capturedAt:'2026-10-20T01:00:00Z'}],nextCursor:url.includes('cursor=next')?null:'next'};},guardSelection:apply=>apply(),onSelect:async value=>selectedSamples.push(value)});});
|
||||
await page.getByLabel('搜索订单号、流水号或标题').fill('148396');await page.waitForFunction(()=>calls.some(c=>c.url.includes('q=148396')));await page.getByRole('button',{name:'下一页',exact:true}).click();await page.getByRole('button',{name:'选择订单 S-2',exact:true}).click();assert.deepEqual(await page.evaluate(()=>selectedSamples),[{sampleId:'s2'}]);assert.equal(await page.evaluate(()=>calls.some(c=>c.body)),false);assert.equal(await page.locator('#picker img').count(),0);await page.getByRole('button',{name:'取消选择',exact:true}).click();assert.equal(await page.evaluate(()=>selectedSamples.at(-1).sampleId),null);await page.setViewportSize({width:390,height:844});assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true);
|
||||
});
|
||||
test('late searches and disposed responses cannot overwrite current list',async t=>{const page=await setup(t);await page.evaluate(()=>{window.held=[];window.picker=FieldSamplePicker.mount(document.querySelector('#picker'),{esc:String,user:{role:'viewer'},api:url=>new Promise(resolve=>held.push({url,resolve})),guardSelection:apply=>apply(),onSelect:()=>{}});});await page.waitForFunction(()=>held.length===1);await page.getByLabel('搜索订单号、流水号或标题').fill('new');await page.waitForFunction(()=>held.length===2);await page.evaluate(()=>held[1].resolve({items:[{id:'new',serialNum:'NEW'}],nextCursor:null}));await page.getByRole('button',{name:'选择订单 NEW',exact:true}).waitFor();await page.evaluate(()=>held[0].resolve({items:[{id:'old',serialNum:'OLD'}]}));assert.equal(await page.getByRole('button',{name:'选择订单 OLD',exact:true}).count(),0);await page.getByLabel('搜索订单号、流水号或标题').fill('last');await page.waitForFunction(()=>held.length===3);await page.evaluate(()=>{picker.dispose();document.querySelector('#picker').textContent='已离开';held[2].resolve({items:[{id:'last',serialNum:'LAST'}]});});assert.equal(await page.locator('#picker').innerText(),'已离开');});
|
||||
test('recognition shows candidates and loads advanced fields lazily, only changing page sources',async t=>{const page=await setup(t);await page.evaluate(()=>{window.loaded=0;window.changes=[];window.panel=FieldRecognitionPanel.render(document.querySelector('#result'),{sampleId:'s1',mapping:{basis:'recommended',sources:{brief:{type:'title'}}},fields:[{key:'orderNo',label:'主订单号',state:'ambiguous',value:null,candidates:[{path:'a',label:'订单号',value:'123'},{path:'b',label:'订单号',value:'HA123'}]},{key:'quantity',label:'数量',state:'recognized',value:0,candidates:[]}],recognition:{valid:false,event:{brief:'123、HA123'}},blockedReasons:['请选择主订单来源'],warnings:[]},{esc:v=>String(v??'').replaceAll('<','<'),admin:true,loadFields:async()=>{loaded++;return [{path:'a',label:'订单号',value:'123'},{path:'b',label:'订单号',value:'HA123'}];},onChangeSources:s=>changes.push(s)});});assert.equal(await page.evaluate(()=>loaded),0);await page.getByRole('button',{name:'订单号 · HA123',exact:true}).click();assert.equal(await page.evaluate(()=>changes[0].orderNo.path),'b');await page.getByText('调整字段对应(高级)',{exact:true}).click();await page.waitForFunction(()=>loaded===1);await page.locator('[data-recognition-source="orderNo"]').selectOption('a');assert.equal(await page.evaluate(()=>changes.at(-1).orderNo.path),'a');assert.match(await page.locator('#result').innerText(),/0/);});
|
||||
|
||||
test('failed paging keeps its boundary and keyboard selection works after retry',async t=>{const page=await setup(t);await page.evaluate(()=>{window.failed=false;window.selectedSamples=[];FieldSamplePicker.mount(document.querySelector('#picker'),{esc:String,user:{role:'viewer'},onSelect:async s=>selectedSamples.push(s),api:async url=>{if(url.includes('cursor=page2')&&!failed){failed=true;throw Error('分页断线');}return {items:[{id:url.includes('cursor=page2')?'two':'one',serialNum:url.includes('cursor=page2')?'TWO':'ONE'}],nextCursor:url.includes('cursor=page2')?null:'page2'};}});});await page.getByRole('button',{name:'选择订单 ONE',exact:true}).waitFor();await page.getByRole('button',{name:'下一页',exact:true}).click();await page.getByText('订单读取失败:分页断线',{exact:true}).waitFor();await page.getByRole('button',{name:'下一页',exact:true}).click();const button=page.getByRole('button',{name:'选择订单 TWO',exact:true});await button.focus();await page.keyboard.press('Enter');assert.deepEqual(await page.evaluate(()=>selectedSamples),[{sampleId:'two'}]);});
|
||||
|
||||
test('advanced field failure can retry while disposed reads cannot replace the next panel',async t=>{const page=await setup(t);await page.evaluate(()=>{window.loads=0;window.panel=FieldRecognitionPanel.render(document.querySelector('#result'),{sampleId:'s',mapping:{sources:{orderNo:{type:'form',path:'a'}}},fields:[],recognition:{event:{}},blockedReasons:[]},{esc:String,admin:true,loadFields:async()=>{loads++;if(loads===1)throw Error('字段断线');return new Promise(resolve=>window.releaseFields=resolve);}});});await page.getByText('调整字段对应(高级)',{exact:true}).click();await page.getByText('字段读取失败:字段断线',{exact:false}).waitFor();await page.getByRole('button',{name:'重试读取字段',exact:true}).click();await page.waitForFunction(()=>typeof releaseFields==='function');await page.evaluate(()=>{panel.dispose();document.querySelector('#result').textContent='新的样本';releaseFields([{path:'old',label:'旧字段',value:'OLD'}]);});assert.equal(await page.locator('#result').innerText(),'新的样本');});
|
||||
|
||||
test('configuration capture locks duplicate actions and cancel only discards the selected result',async t=>{const page=await setup(t);await page.addScriptTag({content:await fs.readFile('web/modules/navigation/lifecycle.js','utf8')});await page.evaluate(()=>{window.calls=[];window.selectedSamples=[];FieldSamplePicker.mount(document.querySelector('#picker'),{esc:String,user:{role:'admin'},connections:[{id:'c',name:'授权连接'}],onSelect:async s=>selectedSamples.push(s),api:async(url,body)=>{calls.push({url,body});if(url.includes('/catalog'))return {items:[],nextCursor:null};if(url.endsWith('/list'))return {id:'list',rows:[{id:'row',serialNum:'LIVE',source:'todo',processName:'流程',processVersion:'1',nodeName:'主管审核'}]};if(url.endsWith('/capture'))return new Promise(resolve=>window.finishCapture=resolve);throw Error('unexpected');}});});await page.getByText('从 BPM 选择',{exact:true}).click();await page.getByLabel('BPM 连接',{exact:true}).selectOption('c');await page.getByRole('button',{name:'读取待办列表',exact:true}).click();assert.equal(await page.getByLabel('读取范围',{exact:true}).inputValue(),'configuration');await page.getByRole('button',{name:'读取并选择 LIVE',exact:true}).click();await page.waitForFunction(()=>typeof finishCapture==='function');assert.equal(await page.getByRole('button',{name:'读取并选择 LIVE',exact:true}).isDisabled(),true);await page.getByRole('button',{name:'取消选择',exact:true}).click();await page.evaluate(()=>finishCapture({id:'captured'}));await page.waitForFunction(()=>!document.querySelector('[data-picker="list"]').disabled);assert.deepEqual(await page.evaluate(()=>selectedSamples),[{sampleId:null}]);assert.equal(await page.evaluate(()=>calls.filter(c=>c.url.endsWith('/capture')).length),1);});
|
||||
|
||||
test('a background catalog failure stays in its own status and cannot replace a durable save message',async t=>{const page=await setup(t);await page.evaluate(()=>{window.feedbackMessages=[];FieldSamplePicker.mount(document.querySelector('#picker'),{esc:String,user:{role:'viewer'},onSelect:()=>{},feedback:m=>feedbackMessages.push(m),api:async()=>{throw Error('目录暂不可用');}});});await page.getByText('订单读取失败:目录暂不可用',{exact:true}).waitFor();assert.deepEqual(await page.evaluate(()=>feedbackMessages),[]);});
|
||||
@@ -0,0 +1,19 @@
|
||||
'use strict';
|
||||
const test=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs'),path=require('node:path'),os=require('node:os');
|
||||
const {RuleStore}=require('../../src/modules/order-rules/store.cjs'),{OrderRuleDispatcher}=require('../../src/modules/order-rules/dispatcher.cjs');
|
||||
const {activateReferenceMapping}=require('../fixtures/activate-field-mapping.cjs');
|
||||
test('verified restricted configuration can retain scheduled intent while runtime evidence still blocks every send',async t=>{
|
||||
const directory=fs.mkdtempSync(path.join(os.tmpdir(),'scheduled-intent-')),desktop=path.join(directory,'Desktop'),target=path.join(desktop,'test');fs.mkdirSync(target,{recursive:true});
|
||||
const store=new RuleStore(path.join(directory,'state'),{desktopRoot:desktop});t.after(()=>{store.close();fs.rmSync(directory,{recursive:true,force:true});});
|
||||
const {active}=activateReferenceMapping(store),rule=store.get('rules','bs-change').draft,unc='\\\\localhost\\'+target[0]+'$'+target.slice(2);
|
||||
store.saveRule({...rule,adapterIds:[active.id],to:['2639266652@qq.com'],cc:[],attachPdf:false,archiveDirectory:unc,filenameDate:'receivedAt'},'admin');
|
||||
store.saveRestrictedTest({version:0,enabled:true,recipient:'2639266652@qq.com',archiveRoot:unc,channelId:'channel',ruleIds:['bs-change']},{username:'admin',role:'admin'});
|
||||
assert.equal(store.providersReady(),false);
|
||||
const saved=store.saveSettings({...store.settings(),channelId:'channel',enabled:true,processingEnabled:true},'admin');assert.equal(saved.enabled,true);
|
||||
let sends=0;const dispatcher=new OrderRuleDispatcher({store,mail:{exclusive:async()=>{sends++;}},settings:()=>({schedule:{times:['11:00','17:00'],timezone:'Asia/Shanghai',weekends:true}}),providersReady:()=>false});
|
||||
await dispatcher.tick();assert.equal(sends,0);assert.equal(dispatcher.ready(),false);await dispatcher.stop();
|
||||
});
|
||||
test('normal mode still requires actual provider readiness before enabling mail',t=>{
|
||||
const directory=fs.mkdtempSync(path.join(os.tmpdir(),'normal-intent-')),store=new RuleStore(directory);t.after(()=>{store.close();fs.rmSync(directory,{recursive:true,force:true});});
|
||||
assert.throws(()=>store.saveSettings({...store.settings(),channelId:'channel',enabled:true},'admin'),/尚未.*联调/);
|
||||
});
|
||||
@@ -0,0 +1,74 @@
|
||||
'use strict';
|
||||
const test=require('node:test'),assert=require('node:assert/strict');
|
||||
const {buildBatch}=require('../../src/modules/order-rules/batch.cjs');
|
||||
const {applyBodyTemplate}=require('../../src/modules/order-rules/template.cjs');
|
||||
const {ruleTemplate}=require('../../src/modules/mail/rule-template.cjs');
|
||||
const {OrderRuleDispatcher}=require('../../src/modules/order-rules/dispatcher.cjs');
|
||||
const cutoff='2026-10-23T03:00:00.000Z';
|
||||
const rule={id:'native',categoryId:'native',version:3,name:'订单通知',intro:'大家好',signature:'业务部',attachPdf:false,to:['2639266652@qq.com'],cc:[],bodyTemplateId:'template-1'};
|
||||
function order(){return {id:'o1',status:'pending',ruleSnapshot:structuredClone(rule),event:{orderNo:'O-1',receivedAt:'2026-10-23T02:00:00Z',productLine:'终端',brief:'前置来源\n订单号:O-1 客户简称:甲\n总数量:0\n订单号:O-2 客户简称:乙',titleOrders:[{orderNo:'O-1',text:'前置来源\n订单号:O-1 客户简称:甲\n总数量:0'},{orderNo:'O-2',text:'订单号:O-2 客户简称:乙'}]},archive:{archivedAt:'2026-10-23T02:30:00Z',files:[{name:'O-1.pdf',path:'C:\\archive\\O-1.pdf',size:100,sha256:'a'.repeat(64),kind:'pdf'},{name:'notice.txt',path:'C:\\archive\\notice.txt',size:10,sha256:'b'.repeat(64),kind:'notice'}]}};}
|
||||
const template={id:'template-1',version:5,status:'active',bindingVersion:3,subject:'{{类别名称}} {{订单号}}',text:'各位好:\n固定说明\n{{订单列表}}\n团队签名',html:'<p>各位好:</p><p>固定说明</p><div>{{订单列表}}</div><p>团队签名</p>',attachments:[]};
|
||||
test('native scheduled order list has one line per observed title order and archive directories outside list',()=>{
|
||||
const input=order(),raw=structuredClone(input),snapshot=buildBatch(rule,[input],cutoff),batch=applyBodyTemplate(snapshot,template,[input],20971520);
|
||||
assert.equal(batch.text,'各位好:\n固定说明\n订单号:O-1 客户简称:甲 总数量:0\n订单号:O-2 客户简称:乙\n团队签名\n\n存放地址:C:\\archive');
|
||||
assert.deepEqual(batch.orderNos,['O-1','O-2']);assert.deepEqual(batch.attachments,[]);assert.deepEqual(input,raw);
|
||||
assert.match(batch.html,/href="file:\/\/\/C:\/archive"/);assert.doesNotMatch(batch.text,/前置来源|\.pdf|\.txt/);
|
||||
assert.deepEqual(batch.template,{id:'template-1',version:5,bindingVersion:3});
|
||||
});
|
||||
test('legacy per-order text recovery keeps declared title order instead of primary order order',()=>{
|
||||
const input=order();input.event.titleOrders=[{orderNo:'O-2'},{orderNo:'O-1'}];
|
||||
const snapshot=buildBatch(rule,[input],cutoff);
|
||||
assert.deepEqual(snapshot.orderNos,['O-2','O-1']);assert.equal(snapshot.text.split('\n\n')[1],'订单号:O-2客户简称:乙\n订单号:O-1客户简称:甲总数量:0');
|
||||
});
|
||||
test('new native freeze rejects legacy attach-PDF intent and still requires archived PDF evidence',()=>{
|
||||
assert.throws(()=>buildBatch({...rule,attachPdf:true},[order()],cutoff),/附件|attachPdf/);
|
||||
const input=order();input.archive.files=input.archive.files.filter(f=>f.kind!=='pdf');
|
||||
assert.throws(()=>buildBatch(rule,[input],cutoff),/PDF/);
|
||||
});
|
||||
test('native template cannot silently discard configured attachments',()=>{
|
||||
const input=order(),snapshot=buildBatch(rule,[input],cutoff);
|
||||
assert.throws(()=>applyBodyTemplate(snapshot,{...template,attachments:[{filename:'x.pdf'}]},[input],20971520),/附件/);
|
||||
});
|
||||
test('template archive placeholder preserves one label and clickable link',()=>{
|
||||
const input=order(),snapshot=buildBatch(rule,[input],cutoff);
|
||||
const batch=applyBodyTemplate(snapshot,{...template,html:'<p>{{订单列表}}</p><p>存放地址:{{存放地址}}</p>'},[input],20971520);
|
||||
assert.equal((batch.html.match(/存放地址/g)||[]).length,1);assert.match(batch.html,/href="file:\/\/\/C:\/archive"/);
|
||||
});
|
||||
test('text-only template still renders archive links in HTML without changing greeting or signature',()=>{
|
||||
const input=order(),snapshot=buildBatch(rule,[input],cutoff);
|
||||
const batch=applyBodyTemplate(snapshot,{...template,html:''},[input],20971520);
|
||||
assert.match(batch.html,/各位好:/);assert.match(batch.html,/团队签名/);assert.match(batch.html,/href="file:\/\/\/C:\/archive"/);
|
||||
});
|
||||
test('text-only template preserves nested archive directory links without rewriting generated HTML',()=>{
|
||||
const input=order();input.archive.files.push({...input.archive.files[0],path:'C:\\archive\\sub\\O-2.pdf'});
|
||||
const snapshot=buildBatch(rule,[input],cutoff),batch=applyBodyTemplate(snapshot,{...template,html:''},[input],20971520);
|
||||
assert.match(batch.html,/href="file:\/\/\/C:\/archive">C:\\archive<\/a>/);
|
||||
assert.match(batch.html,/href="file:\/\/\/C:\/archive\/sub">C:\\archive\\sub<\/a>/);
|
||||
});
|
||||
test('direct category template records immutable rule binding version and fails unresolved binding',()=>{
|
||||
const resolved=ruleTemplate({template:()=>({...structuredClone(template),bindingVersion:91})},rule.categoryId,rule);
|
||||
assert.equal(resolved.bindingVersion,3);resolved.bindingVersion=99;assert.equal(rule.version,3);
|
||||
assert.throws(()=>ruleTemplate({template:()=>null},rule.categoryId,rule),/模板/);
|
||||
});
|
||||
test('one frozen category cannot mix body template bindings even with the same rule version',()=>{
|
||||
const one=order(),two=order();two.id='o2';two.ruleSnapshot.bodyTemplateId='other-template';
|
||||
assert.throws(()=>buildBatch(rule,[one,two],cutoff),/模板|版本/);
|
||||
});
|
||||
function dispatcherFixture(){
|
||||
const result={smtp:0,begun:0,reads:0,finished:[],messages:[]},config={enabled:true,channelId:'mail',restrictedTest:false};
|
||||
const store={settings:()=>config,snapshot:()=>({capabilities:{liveTodo:true,pdfExport:true,automaticArchive:true}}),discoveryBlockers:()=>[],batchIncomplete:()=>false,beginSending:()=>result.begun++,finishSending:(id,status,message)=>result.finished.push({id,status,message})};
|
||||
const mail={store:{channelSecret:()=>({id:'mail',version:1,email:'sender@example.test',smtp:{}}),guard:()=>{}},smtpFactory:()=>{result.smtp++;return {verify:async()=>{},sendMail:async message=>{result.messages.push(message);return {accepted:[...message.to,...message.cc],rejected:[]};},close:()=>{}};}};
|
||||
const dispatcher=new OrderRuleDispatcher({store,mail,settings:()=>({}),clock:()=>new Date(cutoff),providersReady:()=>true,attachmentReader:async()=>{result.reads++;return Buffer.from('x');}});
|
||||
const batch={id:'b1',status:'prepared',cutoff,to:['2639266652@qq.com'],cc:[],attachments:[],subject:'订单',text:'正文',html:'<p>正文</p>'};return {dispatcher,result,config,batch};
|
||||
}
|
||||
for(const mutate of [b=>b.to=['other@qq.com'],b=>b.to=['2639266652@qq.com','other@qq.com'],b=>b.cc=['copy@qq.com'],b=>b.attachments=[{name:'old.pdf',path:'C:\\archive\\old.pdf',size:1,sha256:'a'.repeat(64),kind:'pdf'}]])test('SMTP server policy blocks unsafe frozen envelope '+String(mutate),async()=>{
|
||||
const f=dispatcherFixture();mutate(f.batch);const frozen=structuredClone(f.batch);await f.dispatcher.dispatch(f.batch,f.config);
|
||||
assert.equal(f.result.smtp,0);assert.equal(f.result.begun,0);assert.equal(f.result.reads,0);assert.equal(f.result.finished[0].status,'failed');assert.match(f.result.finished[0].message,/QQ|禁止.*附件/);assert.deepEqual(f.batch,frozen);
|
||||
});
|
||||
test('SMTP dispatch accepts only QQ without Cc or attachments even when restricted config disabled',async()=>{
|
||||
const f=dispatcherFixture();await f.dispatcher.dispatch(f.batch,f.config);
|
||||
assert.equal(f.result.finished[0].status,'sent');assert.deepEqual(f.result.messages[0].to,['2639266652@qq.com']);assert.deepEqual(f.result.messages[0].cc,[]);assert.deepEqual(f.result.messages[0].attachments,[]);
|
||||
});
|
||||
for(const status of ['sent','unknown'])test('dispatch cannot replay immutable '+status+' batch',async()=>{
|
||||
const f=dispatcherFixture();f.batch.status=status;await f.dispatcher.dispatch(f.batch,f.config);assert.equal(f.result.smtp,0);assert.equal(f.result.begun,0);assert.deepEqual(f.result.finished,[]);
|
||||
});
|
||||
@@ -0,0 +1,13 @@
|
||||
'use strict';
|
||||
const test=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs/promises'),path=require('node:path');
|
||||
const {loadPlaywright,browserOptions}=require('../../src/platform/browser.cjs');
|
||||
async function setup(t,section,owner='OrderNotificationViews',mailFailure=false){
|
||||
const browser=await loadPlaywright().chromium.launch(browserOptions());t.after(()=>browser.close());const page=await browser.newPage();page.setDefaultTimeout(5000);await page.setContent('<main id="root"></main>');
|
||||
for(const file of ['order-notifications/shared.js','order-rules/view.js','order-notifications/view.js'])await page.addScriptTag({content:await fs.readFile(path.resolve('web/modules',file),'utf8')});
|
||||
await page.evaluate(async({section,owner,mailFailure})=>{window.calls=[];window.active=true;window.PageLifecycle={requestKey:()=> 'key',dirty:()=>false,onDispose:()=>{},afterSave:async reload=>reload(),guard:fn=>fn()};window.BusinessRecordViews={render:async(host,options,kind)=>{host.textContent='授权分页 '+kind;}};window.OrderExecutionViews={fields:async panel=>{panel.textContent='字段映射';}};const snapshot={rules:[],adapters:[],settings:{enabled:false,processingEnabled:false,version:1},counts:{orders:3,blocked:1,unknown:1,activeBatches:2},capabilities:{},window:{available:true,start:'2026-10-19T00:00:00Z',end:'2026-10-19T11:00:00Z'}};window[owner].configure(window.viewHelpers={api:async(url,body)=>{window.calls.push(url);if(body)return new Promise(r=>window.releaseAction=()=>r({version:2}));if(url==='/mail'&&mailFailure)throw Error('SMTP目录暂不可读');return url==='/mail'?{channels:[]}:snapshot;},esc:value=>String(value??'').replaceAll('&','&').replaceAll('<','<'),formatDate:v=>v||'—',user:{role:'admin'}});await window[owner].render(document.querySelector('#root'),()=>window.active,section);},{section,owner,mailFailure});return page;
|
||||
}
|
||||
test('order and batch sections delegate to bounded query views without loading full snapshots',async t=>{const page=await setup(t,'orders');assert.equal(await page.locator('main').innerText(),'授权分页 orders');assert.deepEqual(await page.evaluate(()=>calls),[]);await page.evaluate(()=>OrderNotificationViews.render(document.querySelector('#root'),()=>active,'pending'));assert.equal(await page.locator('main').innerText(),'授权分页 batches');assert.deepEqual(await page.evaluate(()=>calls),[]);});
|
||||
test('fields delegate their lifecycle without notification runtime reads',async t=>{const page=await setup(t,'fields','OrderRuleViews');await page.getByText('字段映射',{exact:true}).waitFor();assert.deepEqual(await page.evaluate(()=>calls),[]);});
|
||||
test('business homepage uses bounded summary and concrete remediation links',async t=>{const page=await setup(t,'workbench');assert.match(await page.locator('main').innerText(),/2026-10-19T11:00:00Z/);for(const hash of ['#rule-fields','#bpm','#storage','#notification-orders'])assert.ok(await page.locator('a[href="'+hash+'"]').count());assert.deepEqual(await page.evaluate(()=>calls),['/order-rules?view=summary']);});
|
||||
test('mailbox failure is explicit and cannot save an empty catalog',async t=>{const page=await setup(t,'settings','OrderNotificationViews',true);assert.match(await page.locator('main').innerText(),/邮箱目录读取失败/);await page.getByRole('button',{name:'保存设置'}).click();assert.deepEqual(await page.evaluate(()=>calls),['/order-rules?view=summary','/mail']);});
|
||||
test('late settings action after departure starts no readback or saved feedback',async t=>{const page=await setup(t,'settings');await page.getByRole('button',{name:'保存设置'}).click();await page.waitForFunction(()=>typeof releaseAction==='function');await page.evaluate(()=>{active=false;releaseAction();});await page.waitForFunction(()=>!document.querySelector('#order-rule-settings button').disabled);assert.deepEqual(await page.evaluate(()=>calls),['/order-rules?view=summary','/mail','/order-rules/settings']);assert.equal(await page.locator('form [role=alert]').innerText(),'');});
|
||||
@@ -0,0 +1,8 @@
|
||||
'use strict';
|
||||
const test=require('node:test'),assert=require('node:assert/strict'),XLSX=require('xlsx');
|
||||
const subject=()=>require('../../src/modules/order-rules/source-workbook.cjs');
|
||||
function workbook(){const rows=[['序号','服务器存档地址','订单评审流程','邮件命名','邮件正文','电子流状态','收件人']];for(let r=2;r<=16;r++)rows.push([r-1,'',r===2?'甲流程/乙流程':r===10?'“丙流程”+国内、宽带返工订单更改评审':'流程'+r,'【类别'+r+'】+订单号','',r===2?'订单专员(订单通知书)':r===12?'订单专员(激活)':r===15?'订单专员(订单通知书)-海外/订单专员(订单通知书)':r===16?'':'订单专员(订单通知书)','private@example.test']);const sheet=XLSX.utils.aoa_to_sheet(rows);delete sheet.F3;sheet['!merges']=[XLSX.utils.decode_range('F2:F3'),XLSX.utils.decode_range('F15:F16')];return {SheetNames:['订单通知书邮件信息'],Sheets:{订单通知书邮件信息:sheet}};}
|
||||
test('declared merges retain source anchors and exact node scopes without importing private cells',()=>{const parsed=subject().parseWorkbook(workbook(),{sourceSha256:'a'.repeat(64)});assert.equal(parsed.rules.length,15);assert.deepEqual(parsed.rules[0].processNames,['甲流程','乙流程']);assert.deepEqual(parsed.rules[1].nodeNames,['订单专员(订单通知书)']);assert.deepEqual(parsed.rules[10].nodeNames,['订单专员(激活)']);assert.deepEqual(parsed.rules[14].nodeNames,['订单专员(订单通知书)-海外','订单专员(订单通知书)']);assert.equal(parsed.rules[1].provenance.node.anchor,'F2');assert.equal(parsed.rules[1].provenance.node.cell,'F3');assert.equal(parsed.rules[1].provenance.node.merge,'F2:F3');assert.deepEqual(parsed.rules[8].processNames,['丙流程','国内、宽带返工订单更改评审']);assert.equal(JSON.stringify(parsed).includes('private@example.test'),false);assert.equal(JSON.stringify(parsed).includes('生效'),false);});
|
||||
test('an undeclared blank node cannot inherit the preceding row',()=>{const w=workbook();w.Sheets[w.SheetNames[0]]['!merges']=[];assert.throws(()=>subject().parseWorkbook(w),/F3/);});
|
||||
test('extra numbered categories after row 16 cannot be silently ignored',()=>{const w=workbook(),s=w.Sheets[w.SheetNames[0]];for(const [cell,value] of Object.entries({A17:16,C17:'新增订单评审',D17:'【新增订单通知书】+订单号',F17:'订单专员(订单通知书)'}))s[cell]={t:typeof value==='number'?'n':'s',v:value};s['!ref']='A1:G36';assert.throws(()=>subject().parseWorkbook(w),/17/);});
|
||||
test('the original workbook notes at C20 and C36 remain allowed',()=>{const w=workbook(),s=w.Sheets[w.SheetNames[0]];s.C20={t:'s',v:'摘要信息示例:'};s.C36={t:'s',v:'邮件发送:'};s['!ref']='A1:G36';assert.equal(subject().parseWorkbook(w).rules.length,15);});
|
||||
@@ -0,0 +1,129 @@
|
||||
'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 {RuleStore}=require('../../src/modules/order-rules/store.cjs');
|
||||
const {activateReferenceMapping}=require('../fixtures/activate-field-mapping.cjs');
|
||||
|
||||
function fixture(t,options={}){
|
||||
options={clock:()=>new Date('2026-10-19T02:00:00Z'),...options};
|
||||
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'order-rules-'));
|
||||
let store=new RuleStore(dir,options);
|
||||
t.after(()=>{store.close();fs.rmSync(dir,{recursive:true,force:true});});
|
||||
return {dir,get store(){return store;},reopen(){store.close();store=new RuleStore(dir,options);return store;}};
|
||||
}
|
||||
function configure(store,id='bs-change'){
|
||||
const {sample,captured}=activateReferenceMapping(store,id,{connectionId:'connection-1',instanceId:'instance-1',taskId:'task-1',revision:'1'});
|
||||
const current=store.snapshot().rules.find(r=>r.id===id);
|
||||
const rule=store.saveRule({...current,to:['2639266652@qq.com'],attachPdf:false,archiveDirectory:'\\\\server\\orders\\备损',filenameDate:'appDate'},'admin');
|
||||
assert.equal(store.capturedPreview(captured.id).valid,true);
|
||||
store.publish(id,{version:rule.version},'admin');
|
||||
return sample;
|
||||
}
|
||||
test('draft edits persist and stale saves fail without changing the published rule',t=>{
|
||||
const f=fixture(t),sample=configure(f.store),before=f.store.snapshot().rules.find(r=>r.id==='bs-change');
|
||||
const changed=f.store.saveRule({...before,intro:'新版正文'},'admin');
|
||||
assert.throws(()=>f.store.saveRule(before,'admin'),e=>e.status===409);
|
||||
const reopened=f.reopen(),rule=reopened.snapshot().rules.find(r=>r.id==='bs-change');
|
||||
assert.equal(rule.intro,'新版正文');assert.equal(rule.publishedVersion,before.version);assert.equal(rule.hasDraft,true);
|
||||
const order=reopened.ingest(sample,'admin');assert.notEqual(order.ruleSnapshot.intro,changed.intro);
|
||||
});
|
||||
test('preview does not create orders; rule edits do not create duplicate tasks; conflicting revision is rejected',t=>{
|
||||
const {store}=fixture(t),sample=configure(store);assert.equal(store.snapshot().orders.length,0);
|
||||
const one=store.ingest(sample,'admin');assert.equal(store.ingest(sample,'admin').id,one.id);
|
||||
assert.equal(store.snapshot().orders.length,1);
|
||||
assert.throws(()=>store.ingest({...sample,brief:'更改了原文但没改版本'},'admin'),e=>e.status===409);
|
||||
assert.throws(()=>store.ingest({...sample,demo:true},'admin'),e=>e.status===400);
|
||||
});
|
||||
test('unverified providers prevent automatic execution and HTTP-style status claims cannot fake archiving',t=>{
|
||||
const {store}=fixture(t),sample=configure(store),order=store.ingest(sample,'operator');
|
||||
assert.equal(order.status,'blocked');assert.match(order.error,/接入|联调|归档/);
|
||||
assert.throws(()=>store.saveSettings({...store.settings(),enabled:true,channelId:'x'},'admin'),e=>e.status===409);
|
||||
assert.throws(()=>store.recordArchive(order.id,{files:[],archivedAt:new Date().toISOString()},'operator'),e=>e.status===400||e.status===409);
|
||||
assert.equal(store.prepare('2026-10-19T03:00:00Z','admin').length,0);
|
||||
});
|
||||
test('all same-category orders before cutoff aggregate once; post-cutoff orders stay pending; restart keeps uncertain sends blocked',t=>{
|
||||
const {store,reopen}=fixture(t,{capabilities:{liveTodo:true,pdfExport:true,automaticArchive:true}}),sample=configure(store);
|
||||
for(let i=0;i<205;i++){
|
||||
const order=store.ingest({...sample,instanceId:'i'+i,taskId:'t'+i,receivedAt:'2026-10-19T01:00:00Z'},'system');
|
||||
store.recordArchive(order.id,{files:[{name:'order'+i+'.pdf',path:'C:\\archive\\order'+i+'.pdf',sha256:'a'.repeat(64),size:42,kind:'pdf'}],archivedAt:'2026-10-19T01:05:00Z'},'archive-executor');
|
||||
}
|
||||
const later=store.ingest({...sample,instanceId:'later',taskId:'later',receivedAt:'2026-10-19T10:00:00Z'},'system');
|
||||
store.recordArchive(later.id,{files:[{name:'later.pdf',path:'C:\\archive\\later.pdf',sha256:'b'.repeat(64),size:42,kind:'pdf'}],archivedAt:'2026-10-19T10:01:00Z'},'archive-executor');
|
||||
const batches=store.prepare('2026-10-19T03:00:00Z','admin');assert.equal(batches.length,1);assert.equal(batches[0].orderIds.length,205);
|
||||
assert.equal(store.prepare('2026-10-19T03:00:00Z','admin').length,0);
|
||||
assert.equal(store.snapshot().orders.find(o=>o.id===later.id).status,'pending');
|
||||
store.beginSending(batches[0].id);
|
||||
const recovered=reopen();assert.equal(recovered.snapshot().batches[0].status,'unknown');
|
||||
assert.equal(recovered.prepare('2026-10-19T03:00:00Z','admin').length,0);
|
||||
recovered.resolve(batches[0].id,{resolution:'sent',note:'已查询服务器确认完整接受'},'admin');
|
||||
assert.equal(recovered.snapshot().orders.filter(o=>o.status==='sent').length,205);
|
||||
});
|
||||
test('one incomplete order blocks the entire category, and publication demands a fresh sample trial',t=>{
|
||||
const {store}=fixture(t,{capabilities:{liveTodo:true,pdfExport:true,automaticArchive:true}}),sample=configure(store);
|
||||
store.ingest(sample,'system');assert.equal(store.prepare('2026-10-19T03:00:00Z','admin').length,0);
|
||||
const rule=store.snapshot().rules.find(r=>r.id==='bs-change'),draft=store.saveRule({...rule,intro:'新正文'},'admin');
|
||||
assert.throws(()=>store.publish(rule.id,{version:draft.version},'admin'),e=>e.status===409);
|
||||
});
|
||||
|
||||
test('semantic identity ignores JSON key order and numeric/string revision formatting',t=>{
|
||||
const {store}=fixture(t),sample=configure(store);
|
||||
const first=store.ingest({...sample,revision:0},'system');
|
||||
const reordered=Object.fromEntries(Object.entries({...sample,revision:'0'}).reverse());
|
||||
reordered.fields=Object.fromEntries(Object.entries(sample.fields).reverse());
|
||||
assert.equal(store.ingest(reordered,'system').id,first.id);assert.equal(store.snapshot().orders.length,1);
|
||||
});
|
||||
test('demo structure preview cannot authorize publishing a business rule',t=>{
|
||||
const {store}=fixture(t),rule=store.snapshot().rules.find(r=>r.id==='bs-change');
|
||||
const saved=store.saveRule({...rule,to:['2639266652@qq.com'],attachPdf:false,archiveDirectory:'\\\\server\\orders',filenameDate:'appDate'},'admin');
|
||||
const sample=store.snapshot().adapters.find(a=>a.id==='bs-change').sample;
|
||||
assert.equal(store.preview(sample).valid,true);
|
||||
assert.throws(()=>store.publish(saved.id,{version:saved.version},'admin'),e=>e.status===409);
|
||||
});
|
||||
test('pausing a rule prevents a prepared batch from entering SMTP sending',t=>{
|
||||
const {store}=fixture(t,{capabilities:{liveTodo:true,pdfExport:true,automaticArchive:true}}),sample=configure(store);
|
||||
const order=store.ingest(sample,'system');store.recordArchive(order.id,{files:[{name:'one.pdf',path:'C:\\archive\\one.pdf',sha256:'a'.repeat(64),size:42,kind:'pdf'}],archivedAt:'2026-10-19T01:05:00Z'},'archive-executor');
|
||||
const batch=store.prepare('2026-10-19T03:00:00Z','admin')[0],rule=store.snapshot().rules.find(r=>r.id==='bs-change');
|
||||
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 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 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');
|
||||
assert.equal(old.status,'ignored');
|
||||
assert.throws(()=>store.recordArchive(old.id,{files:[],archivedAt:'2026-10-20T02:00:00Z'},'archive-executor'),e=>e.status===409);
|
||||
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-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);
|
||||
const old=store.snapshot().rules.find(r=>r.id==='bs-change');store.pause(old.id,{version:old.version},'admin');
|
||||
store.saveRule({...old,processNames:['暂不使用的旧流程']},'admin');
|
||||
const candidate=store.snapshot().rules.find(r=>r.id==='trial-change');
|
||||
const adapter=store.adapters().find(a=>!a.reference&&a.processName===sample.processName&&a.processVersion===sample.processVersion);
|
||||
const replacement=store.saveRule({...candidate,processNames:['备损订单更改评审'],nodeNames:['订单专员(订单通知书)'],adapterIds:[adapter.id],to:['replacement@example.test'],archiveDirectory:'\\\\server\\orders',filenameDate:'appDate'},'admin');
|
||||
const captured=store.all('capture-samples').find(c=>c.sample.instanceId===sample.instanceId);
|
||||
assert.equal(store.capturedPreview(captured.id).ruleId,'trial-change');store.publish(replacement.id,{version:replacement.version},'admin');
|
||||
const order=store.ingest(sample,'system');assert.equal(order.categoryId,'trial-change');assert.equal(order.trace.valid,true);
|
||||
});
|
||||
test('paused ingestion retains classification and explicit recheck can recover against the current rule',t=>{
|
||||
const {store}=fixture(t,{capabilities:{liveTodo:true,pdfExport:true,automaticArchive:true}}),sample=configure(store);
|
||||
const rule=store.snapshot().rules.find(r=>r.id==='bs-change');store.pause(rule.id,{version:rule.version},'admin');
|
||||
const order=store.ingest(sample,'system');assert.equal(order.categoryId,'bs-change');assert.equal(order.status,'blocked');
|
||||
store.publish(rule.id,{version:rule.version},'admin');
|
||||
const checked=store.recheck(order.id,{note:'已核实规则恢复,重新识别'},'admin');
|
||||
assert.equal(checked.status,'identified');assert.equal(checked.ruleSnapshot.version,rule.version);
|
||||
assert.equal(store.snapshot().orders.length,1);
|
||||
assert.throws(()=>store.prepare('2026-10-19T12:00:00','admin'),e=>e.status===400);
|
||||
});
|
||||
@@ -0,0 +1,10 @@
|
||||
'use strict';
|
||||
const test=require('node:test'),assert=require('node:assert/strict'),{DatabaseSync}=require('node:sqlite');
|
||||
const {RuleStore}=require('../../src/modules/order-rules/store.cjs');
|
||||
test('summary snapshot never decrypts full order batch or audit records',()=>{
|
||||
const calls=[],store={all:kind=>{calls.push(kind);assert.ok(!['orders','batches','audit','business-issues'].includes(kind),'summary must not load '+kind);return [];},adapters:()=>[],settings:()=>({enabled:false}),capabilities:{},clock:()=>new Date('2026-10-21T01:00:00Z'),schedule:()=>({times:['11:00','17:00'],weekends:false}),calendar:()=>[]};
|
||||
const summary=RuleStore.prototype.snapshot.call(store,{includeRecords:false});assert.deepEqual(summary.orders,[]);assert.deepEqual(summary.batches,[]);assert.deepEqual(summary.audit,[]);assert.deepEqual(calls,['rules']);
|
||||
});
|
||||
test('query revision changes on updates to an existing SQLite row',()=>{
|
||||
const db=new DatabaseSync(':memory:');try{db.exec('CREATE TABLE sample(id INTEGER PRIMARY KEY,value TEXT); INSERT INTO sample VALUES(1,\'a\')');assert.equal(typeof RuleStore.prototype.queryRevision,'function');const first=RuleStore.prototype.queryRevision.call({db});db.exec("UPDATE sample SET value='b' WHERE id=1");assert.ok(RuleStore.prototype.queryRevision.call({db})>first);}finally{db.close();}
|
||||
});
|
||||
@@ -0,0 +1,132 @@
|
||||
'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 {activateReferenceMapping}=require('../fixtures/activate-field-mapping.cjs');
|
||||
const restricted=require('../../src/modules/order-rules/restricted-test.cjs');
|
||||
const admin={username:'admin',role:'admin'};
|
||||
function fixture(t,{testing=false}={}){
|
||||
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'task-admission-')),desktop=path.join(dir,'Desktop'),local=path.join(desktop,'run');fs.mkdirSync(local,{recursive:true});
|
||||
const root='\\\\localhost\\'+local[0]+'$'+local.slice(2);
|
||||
const store=new RuleStore(path.join(dir,'state'),{clock:()=>new Date('2026-10-23T02:00:00Z'),desktopRoot:desktop,capabilities:{liveTodo:true,pdfExport:true,automaticArchive:true}});
|
||||
t.after(()=>{store.close();fs.rmSync(dir,{recursive:true,force:true});});
|
||||
const {sample,captured,active}=activateReferenceMapping(store,'bs-change',{connectionId:'c1',instanceId:'i1',taskId:'t1',receivedAt:store.now()});
|
||||
const current=store.get('rules','bs-change').draft;
|
||||
store.saveRule({...current,adapterIds:[active.id],to:['test@qq.com'],cc:[],attachPdf:false,archiveDirectory:root+'\\bs-change',filenameDate:'receivedAt'},'admin');
|
||||
store.capturedPreview(captured.id);store.publish('bs-change',{version:store.get('rules','bs-change').draft.version},'admin');
|
||||
if(testing){store.saveRestrictedTest({version:0,enabled:true,recipient:'test@qq.com',archiveRoot:root,channelId:'test-channel',ruleIds:['bs-change']},admin);store.saveSettings({...store.settings(),channelId:'test-channel'},'admin');}
|
||||
return {store,sample,root};
|
||||
}
|
||||
function scan(store,rows){return restricted.recordCurrentScan(store,{connectionId:'c1',rows,startedAt:store.now(),finishedAt:store.now()});}
|
||||
test('business revision is optional and repeated source-task remains one record across accounts',t=>{
|
||||
const {store,sample}=fixture(t);delete sample.revision;
|
||||
assert.equal(store.previewUntrusted(sample).valid,true);
|
||||
const order=store.ingest(sample,'admin');
|
||||
assert.equal(store.ingest({...sample,connectionId:'c2'},'admin').id,order.id);
|
||||
assert.equal(Object.hasOwn(order.sample,'revision'),false);assert.equal(store.all('orders').length,1);
|
||||
});
|
||||
test('same source-task changed revision, instance, node or content conflicts; new task same order is independent',t=>{
|
||||
const {store,sample}=fixture(t),first=store.ingest(sample,'admin');
|
||||
for(const patch of [{revision:'actual-revision-2'},{instanceId:'another'},{nodeName:'BOM'},{title:'changed'}])assert.throws(()=>store.ingest({...sample,...patch},'admin'),{status:409});
|
||||
assert.notEqual(store.ingest({...sample,taskId:'new-notification'},'admin').id,first.id);assert.equal(store.all('orders').length,2);
|
||||
});
|
||||
test('portal native sources stay distinct while multiple legacy records require manual review',t=>{
|
||||
const {store,sample}=fixture(t),a=store.ingest({...sample,portalSource:'todo-v4'},'admin'),b=store.ingest({...sample,portalSource:'todo-v8'},'admin');assert.notEqual(a.id,b.id);
|
||||
store.put('orders',{...a,id:'old-a'});assert.throws(()=>store.ingest({...sample,portalSource:'todo-v4'},'admin'),/人工|多条/);assert.equal(store.all('orders').length,3);
|
||||
});
|
||||
test('legacy receipt ids and frozen evidence survive identity lookup without recreating success',t=>{
|
||||
const {store,sample}=fixture(t),old=store.ingest(sample,'admin');store.db.prepare('DELETE FROM records WHERE kind=? AND id=?').run('orders',old.id);
|
||||
const legacy={...old,id:'original-receipt-id',status:'sent',archive:{original:'frozen'},batchId:'frozen-mail'};delete legacy.taskKey;store.put('orders',legacy);
|
||||
assert.equal(store.ingest(sample,'admin').id,legacy.id);assert.deepEqual(store.get('orders',legacy.id),legacy);assert.equal(store.all('orders').length,1);
|
||||
assert.throws(()=>store.ingest({...sample,revision:'2'},'admin'),{status:409});
|
||||
});
|
||||
test('only fresh server-scanned exact frozen scopes can enroll current backlog with original time preserved',t=>{
|
||||
const {store,sample}=fixture(t,{testing:true}),old={...sample,receivedAt:'2026-10-20T01:00:00Z'};
|
||||
assert.throws(()=>restricted.admitCurrent(store,[{...old,admittedAt:store.now(),serverVerified:true}],admin),{status:409});
|
||||
scan(store,[old]);const entries=restricted.admitCurrent(store,[old],admin);assert.equal(entries.length,1);assert.equal(entries[0].originalReceivedAt,old.receivedAt);
|
||||
const order=store.ingest(old,'admin');assert.equal(order.status,'identified',order.error);assert.equal(order.event.receivedAt,old.receivedAt);assert.equal(restricted.orderTime(store,order),store.now());
|
||||
for(const patch of [{nodeName:'BOM'},{processVersion:'different'},{instanceId:'different'},{receivedAt:'2026-10-20T01:00:01Z'}])assert.throws(()=>restricted.assertEvent(store,{...old,...patch}),{status:409});
|
||||
assert.throws(()=>store.ingest({...old,taskId:'unenrolled-history',admittedAt:store.now()},'admin'),{status:409});
|
||||
});
|
||||
test('enrollment rejects historical evidence, unconfirmed BOM, processed receipts and stale scans',t=>{
|
||||
const {store,sample}=fixture(t,{testing:true});
|
||||
for(const patch of [{source:'history',configurationOnly:true},{nodeName:'BOM'}]){const row={...sample,...patch};scan(store,[row]);assert.throws(()=>restricted.admitCurrent(store,[row],admin),{status:409});}
|
||||
store.put('processed-task-receipts',{id:'original-success',source:'todo',taskId:sample.taskId,status:'sent',evidenceHash:'a'.repeat(64)});
|
||||
scan(store,[sample]);assert.throws(()=>restricted.admitCurrent(store,[sample],admin),{status:409});assert.throws(()=>store.ingest(sample,'admin'),{status:409});
|
||||
const row={...sample,taskId:'stale',receivedAt:'2026-10-20T01:00:00Z'};scan(store,[row]);store.clock=()=>new Date('2026-10-23T02:06:00Z');assert.throws(()=>restricted.admitCurrent(store,[row],admin),{status:409});
|
||||
});
|
||||
test('native coordinator discovers absent revision once and holds changed node or revision on original task',async t=>{
|
||||
const {store,sample}=fixture(t);delete sample.revision;let row={...sample},captures=0,exports=0;
|
||||
const connection={id:'c1',owner:'admin',status:'connected'},principal={user:admin,sessionId:'s'};
|
||||
const execution=new (require('../../src/modules/order-execution/coordinator.cjs').OrderExecutionCoordinator)({store,workspace:{getConnection:()=>connection,snapshot:()=>({connections:[connection]})},clock:store.clock,
|
||||
provider:{scan:async()=>[row],capabilities:()=>({liveTodo:true,pdfExport:true}),capture:async()=>{captures++;return {sample:{...row},snapshot:{processVersion:row.processVersion,fields:Object.entries(row.fields).map(([path,value])=>({path,value}))}};}},
|
||||
archive:{capabilities:()=>({automaticArchive:true,pdfExport:true}),probe:async()=>({automaticArchive:true,pdfExport:true}),archive:async()=>{exports++;return {archivedAt:store.now(),files:[{name:'one.pdf',path:'C:\\archive\\one.pdf',size:1,sha256:'a'.repeat(64),kind:'pdf'}]};}}
|
||||
});t.after(()=>execution.stop());
|
||||
await execution.scan({connectionId:'c1',idempotencyKey:'first'},principal);await execution.scan({connectionId:'c1',idempotencyKey:'again'},principal);
|
||||
const original=store.all('execution-tasks')[0];assert.equal(store.all('execution-tasks').length,1);assert.equal(exports,1);assert.equal(captures,1);
|
||||
row={...row,nodeName:'BOM',revision:'actual-2'};await execution.scan({connectionId:'c1',idempotencyKey:'node-conflict'},principal);
|
||||
const current=store.get('execution-tasks',original.id);assert.equal(current.conflict,true);assert.equal(current.conflictRow.revision,'actual-2');assert.equal(store.all('execution-tasks').length,1);assert.equal(exports,1);
|
||||
await assert.rejects(execution.resolve(current.id,{version:current.version,idempotencyKey:'no-new-archive',resolution:'adopt',note:'不能用修订重复已归档任务'},principal),{status:409});
|
||||
});
|
||||
test('admitted backlog stays queued until the next configured window, including a missed first cutoff',t=>{
|
||||
const {store,sample}=fixture(t,{testing:true}),old={...sample,receivedAt:'2026-10-20T01:00:00Z'};scan(store,[old]);restricted.admitCurrent(store,[old],admin);
|
||||
const order=store.ingest(old,'admin');
|
||||
store.recordArchive(order.id,{archivedAt:store.now(),files:[{name:'one.pdf',path:order.ruleSnapshot.archiveDirectory+'\\one.pdf',size:1,sha256:'a'.repeat(64),kind:'pdf'}]},'admin');
|
||||
assert.equal(store.prepare('2026-10-23T03:00:00Z','admin').length,0,'cannot freeze ahead of the configured cutoff');
|
||||
store.clock=()=>new Date('2026-10-23T03:02:00Z');scan(store,[old]);
|
||||
assert.equal(store.prepare('2026-10-23T03:00:00Z','admin').length,0,'cannot catch up immediately after a missed window');assert.equal(store.get('orders',order.id).status,'pending');
|
||||
store.clock=()=>new Date('2026-10-23T09:00:00Z');scan(store,[old]);const batches=store.prepare('2026-10-23T09:00:00Z','admin');assert.equal(batches.length,1);assert.deepEqual(batches[0].orderIds,[order.id]);assert.equal(store.get('orders',order.id).event.receivedAt,old.receivedAt);
|
||||
});
|
||||
test('legacy fabricated zero can reconcile missing revision without changing a successful receipt',t=>{
|
||||
const {store,sample}=fixture(t),old=store.ingest({...sample,revision:'0'},'admin');delete old.taskKey;old.id='legacy-success';old.status='sent';old.archive={original:'success'};
|
||||
store.db.prepare('DELETE FROM records WHERE kind=?').run('orders');store.put('orders',old);
|
||||
const incoming={...sample};delete incoming.revision;
|
||||
assert.equal(store.ingest(incoming,'admin').id,old.id);assert.deepEqual(store.get('orders',old.id),old);
|
||||
const realZero={...old,id:'real-zero',taskId:'real',sample:{...old.sample,taskId:'real',reportedRevision:'0'}};store.put('orders',realZero);
|
||||
assert.throws(()=>store.ingest({...incoming,taskId:'real'},'admin'),{status:409});
|
||||
});
|
||||
test('unconfirmed native nodes remain visible candidates and do not block confirmed categories',async t=>{
|
||||
const {store,sample}=fixture(t),connection={id:'c1',owner:'admin',status:'connected'},principal={user:admin,sessionId:'s'},row={...sample,nodeName:'BOM资料编制'};
|
||||
const execution=new (require('../../src/modules/order-execution/coordinator.cjs').OrderExecutionCoordinator)({store,workspace:{getConnection:()=>connection,snapshot:()=>({connections:[connection]})},clock:store.clock,provider:{scan:async()=>[row],capabilities:()=>({liveTodo:true,pdfExport:true})},archive:{capabilities:()=>({automaticArchive:true,pdfExport:true})}});t.after(()=>execution.stop());
|
||||
await execution.scan({connectionId:'c1',idempotencyKey:'unconfirmed'},principal);
|
||||
assert.equal(execution.snapshot(principal).candidates.length,1);assert.equal(execution.snapshot(principal).candidates[0].status,'candidate');assert.match(execution.snapshot(principal).candidates[0].reason,/不在.*通知范围/);assert.equal(store.all('execution-tasks').length,0);assert.equal(store.categoryIncomplete('bs-change',store.snapshot().window),false);
|
||||
});
|
||||
test('enrolled backlog must still be present unchanged in a fresh provider scan before freezing',t=>{
|
||||
const {store,sample}=fixture(t,{testing:true}),old={...sample,receivedAt:'2026-10-20T01:00:00Z'};scan(store,[old]);restricted.admitCurrent(store,[old],admin);
|
||||
const order=store.ingest(old,'admin');store.recordArchive(order.id,{archivedAt:store.now(),files:[{name:'one.pdf',path:order.ruleSnapshot.archiveDirectory+'\\one.pdf',size:1,sha256:'a'.repeat(64),kind:'pdf'}]},'admin');
|
||||
store.clock=()=>new Date('2026-10-23T03:00:00Z');scan(store,[]);assert.equal(store.prepare('2026-10-23T03:00:00Z','admin').length,0);assert.equal(store.get('orders',order.id).status,'pending');
|
||||
scan(store,[{...old,title:'changed after enrollment'}]);assert.equal(store.prepare('2026-10-23T03:00:00Z','admin').length,0);
|
||||
scan(store,[old]);assert.equal(store.prepare('2026-10-23T03:00:00Z','admin').length,1);
|
||||
});
|
||||
|
||||
test('proof-admitted backlog survives a later processing baseline and keeps its original received time',async t=>{
|
||||
const {store,sample,root}=fixture(t,{testing:true});
|
||||
const old={...sample,receivedAt:'2026-10-20T01:00:00Z'};
|
||||
scan(store,[old]);
|
||||
const entries=restricted.admitCurrent(store,[old],admin);
|
||||
assert.equal(entries.length,1);
|
||||
const admission=structuredClone(entries[0]);
|
||||
assert.equal(restricted.isAdmitted(store,old),true);
|
||||
store.clock=()=>new Date('2026-10-23T02:01:00Z');
|
||||
store.saveSettings({...store.settings(),processingEnabled:true},'admin');
|
||||
const unadmitted={...sample,taskId:'unadmitted',receivedAt:'2026-10-23T02:00:30Z',admittedAt:'2026-10-23T02:02:00Z',serverVerified:true};
|
||||
const historical={...unadmitted,taskId:'historical',receivedAt:'2026-10-20T01:00:00Z'};
|
||||
let archives=0;
|
||||
const connection={id:'c1',owner:'admin',status:'connected'},principal={user:admin,sessionId:'admitted-baseline'};
|
||||
const execution=new (require('../../src/modules/order-execution/coordinator.cjs').OrderExecutionCoordinator)({store,clock:store.clock,
|
||||
workspace:{getConnection:()=>connection,snapshot:()=>({connections:[connection]})},
|
||||
provider:{scan:async()=>[old,unadmitted,historical],capabilities:()=>({liveTodo:true,pdfExport:true}),capture:async(_connection,_principal,row)=>({sample:{...row},snapshot:{processVersion:row.processVersion,fields:Object.entries(row.fields).map(([path,value])=>({path,value}))}})},
|
||||
archive:{capabilities:()=>({automaticArchive:true,pdfExport:true}),archive:async()=>{archives++;return {archivedAt:store.now(),files:[{name:'one.pdf',path:root+'\\bs-change\\one.pdf',size:1,sha256:'a'.repeat(64),kind:'pdf'}]};}},
|
||||
});
|
||||
t.after(()=>execution.stop());
|
||||
await execution.scan({connectionId:'c1',idempotencyKey:'admitted-after-baseline'},principal);
|
||||
const task=store.all('execution-tasks')[0];
|
||||
assert.ok(task,'proof-admitted task must not be skipped by processingSince');
|
||||
assert.deepEqual(store.all('execution-tasks').map(item=>item.row.taskId),['t1']);
|
||||
const order=store.get('orders',task.orderId);
|
||||
assert.equal(order.status,'pending',order.error);
|
||||
assert.equal(order.event.receivedAt,old.receivedAt);
|
||||
assert.equal(restricted.orderTime(store,order),'2026-10-23T02:00:00.000Z');
|
||||
assert.equal(store.settings().processingSince,'2026-10-23T02:01:00.000Z');
|
||||
assert.deepEqual(restricted.state(store).currentBacklog,[admission]);
|
||||
assert.equal(archives,1);
|
||||
});
|
||||
@@ -0,0 +1,49 @@
|
||||
'use strict';
|
||||
const test=require('node:test'),assert=require('node:assert/strict');
|
||||
const {applyBodyTemplate}=require('../../src/modules/order-rules/template.cjs');
|
||||
const maxBytes=20971520;
|
||||
function order(id,receivedAt){
|
||||
return {id,event:{orderNo:id,brief:'订单号:'+id,productLine:'测试产品线',receivedAt},
|
||||
admittedAt:'2026-10-23T02:00:00Z',createdAt:'2026-10-23T02:00:00Z',
|
||||
sample:{receivedAt:'2026-10-25T00:00:00Z',fields:{businessDate:'2026-10-26'}},
|
||||
ruleSnapshot:{name:'订单通知',bodyTemplateId:'normal',huizhouTemplateId:'hui'},
|
||||
archive:{files:[{path:'\\\\synthetic\\orders\\'+id+'.pdf'}]}};
|
||||
}
|
||||
function fixture(mode,orders,parts={}){
|
||||
const snapshot={notificationMode:mode,cutoff:'2026-10-23T03:00:00Z',orderNos:orders.map(item=>item.event.orderNo),subject:'原标题',attachments:[]};
|
||||
const template={id:mode==='huizhou'?'hui':'normal',version:1,status:'active',notificationMode:mode,
|
||||
subject:'业务日期{{ 日期 }} {{订单号}}',text:'日期={{日期}}\n{{订单列表}}',html:'<p>日期={{日期}}</p>{{订单列表}}',attachments:[],...parts};
|
||||
return {snapshot,template};
|
||||
}
|
||||
for(const mode of ['normal','huizhou']){
|
||||
test(`${mode} date variable uses unique Shanghai event dates in order appearance, ignoring admission and cutoff`,()=>{
|
||||
const orders=[order('A','2026-10-20T16:30:00Z'),order('B','2026-10-20T23:30:00+08:00'),order('C','2026-10-21T01:00:00+08:00')];
|
||||
const {snapshot,template}=fixture(mode,orders),before=structuredClone({snapshot,orders});
|
||||
const batch=applyBodyTemplate(snapshot,template,orders,maxBytes);
|
||||
assert.equal(batch.subject,'业务日期2026-10-21、2026-10-20 A、B、C');
|
||||
assert.match(batch.text,/日期=2026-10-21、2026-10-20\n/);
|
||||
assert.match(batch.html,/<p>日期=2026-10-21、2026-10-20<\/p>/);
|
||||
assert.deepEqual({snapshot,orders},before);
|
||||
assert.equal(batch.cutoff,'2026-10-23T03:00:00Z');
|
||||
});
|
||||
for(const receivedAt of [undefined,null,'','invalid-time','2026-99-99T00:00:00Z',0]){
|
||||
test(`${mode} date variable blocks missing or invalid authoritative receivedAt ${JSON.stringify(receivedAt)}`,()=>{
|
||||
const orders=[order('valid','2026-10-20T01:00:00Z'),order('invalid',receivedAt)],{snapshot,template}=fixture(mode,orders);
|
||||
assert.throws(()=>applyBodyTemplate(snapshot,template,orders,maxBytes),error=>error.status===409&&/日期.*event\.receivedAt/.test(error.message));
|
||||
});
|
||||
}
|
||||
for(const part of ['subject','text','html'])test(`${mode} date validation also applies when only ${part} uses the date variable`,()=>{
|
||||
const orders=[order('missing',undefined)],{snapshot,template}=fixture(mode,orders,{subject:'通知 {{订单号}}',text:'{{订单列表}}',html:'{{订单列表}}',[part]:'{{日期}}'});
|
||||
assert.throws(()=>applyBodyTemplate(snapshot,template,orders,maxBytes),error=>error.status===409&&/日期.*event\.receivedAt/.test(error.message));
|
||||
});
|
||||
test(`${mode} missing event still reports the authoritative date field reason`,()=>{
|
||||
const orders=[order('missing-event',undefined)],{snapshot,template}=fixture(mode,orders);
|
||||
delete orders[0].event;
|
||||
assert.throws(()=>applyBodyTemplate(snapshot,template,orders,maxBytes),error=>error.status===409&&/日期.*event\.receivedAt/.test(error.message));
|
||||
});
|
||||
test(`${mode} templates without a date variable still render legacy orders lacking receivedAt`,()=>{
|
||||
const orders=[order('legacy',undefined)],{snapshot,template}=fixture(mode,orders,{subject:'通知 {{订单号}}',text:'{{订单列表}}',html:'{{订单列表}}'});
|
||||
const batch=applyBodyTemplate(snapshot,template,orders,maxBytes);
|
||||
assert.equal(batch.subject,'通知 legacy');assert.match(batch.text,/订单号:legacy/);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
'use strict';
|
||||
const test=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs'),path=require('node:path'),os=require('node:os');
|
||||
const {RuleStore}=require('../../src/modules/order-rules/store.cjs');
|
||||
const {activateFieldMapping}=require('../fixtures/activate-field-mapping.cjs');
|
||||
const subject=()=>require('../../src/modules/order-rules/test-preparation.cjs');
|
||||
const admin={username:'admin',role:'admin'};
|
||||
function fixture(t){const dir=fs.mkdtempSync(path.join(os.tmpdir(),'prepare-source-')),desktop=path.join(dir,'Desktop'),root=path.join(desktop,'run');fs.mkdirSync(root,{recursive:true});const unc='\\\\localhost\\'+root[0]+'$'+root.slice(2),store=new RuleStore(path.join(dir,'rules'),{desktopRoot:desktop});t.after(()=>{store.close();fs.rmSync(dir,{recursive:true,force:true});});const source={sourceSha256:'a'.repeat(64),worksheet:'订单通知书邮件信息',rules:store.all('rules').map(({draft:r})=>({id:r.id,name:r.name,sourceRow:r.sourceRow,processNames:r.processNames,nodeNames:r.id==='processing-notice'?['订单专员(激活)']:r.id==='overseas-change'?['订单专员(订单通知书)']:r.nodeNames,provenance:{node:{cell:'F'+r.sourceRow}}}))};for(const row of source.rules){const sample={connectionId:'c',source:'history',configurationOnly:true,instanceId:row.id,taskId:row.id,revision:1,processName:row.processNames[0],processVersion:'test-1',nodeName:'历史',receivedAt:'2026-10-22T01:00:00Z',serialNum:'SERIAL-1',title:'订单号:123456',fields:{order:'123456'}};const captured=store.recordCapture({sample,snapshot:{processVersion:'test-1',fields:[{path:'order',value:'123456',label:'订单号'}]},taskId:sample.taskId});const adapter=activateFieldMapping(store,{sampleId:captured.id,processName:sample.processName,processVersion:'test-1',fields:{orderNo:'order'}},admin);const r=store.get('rules',row.id).draft;store.saveRule({...r,adapterIds:[adapter.id],archiveDirectory:unc+'\\'+r.id,filenameDate:'receivedAt'},'admin');}const mail={categoryTemplate:()=>null,template:()=>{throw Error('missing');}};return {store,source,mail,unc};}
|
||||
test('dry run is read-only, retains native identities, excludes aliases and describes local templates',t=>{const f=fixture(t),before=f.store.queryRevision();const plan=subject().buildPreparationPlan({store:f.store,mailStore:f.mail,source:f.source,runId:'run-1',channelId:'channel',archiveRoot:f.unc});assert.equal(f.store.queryRevision(),before);assert.equal(plan.rules.length,15);assert.equal(plan.blockers.length,0);for(const item of plan.rules){assert.equal(item.draft.name,item.previousName);assert.equal(item.draft.productLine,item.previousName);assert.deepEqual(item.draft.to,['2639266652@qq.com']);assert.deepEqual(item.draft.cc,[]);assert.equal(item.draft.attachPdf,false);assert.equal(item.template.action,'create');assert.match(item.template.text,/\{\{订单列表\}\}[\s\S]*\{\{存放地址\}\}/);}assert.deepEqual(plan.rules.find(r=>r.id==='overseas-change').draft.nodeNames,['订单专员(订单通知书)']);assert.ok(plan.uncovered.some(p=>p.processName==='海外运营订单更改评审')===false);assert.ok(plan.uncovered.some(p=>p.processName==='海外返工订单更改评审'));assert.equal(plan.productLineSource,'test-label:rule.name');});
|
||||
test('an existing active explicit or category template is retained',t=>{const f=fixture(t);f.mail.categoryTemplate=()=>({id:'active-template',channelId:'channel',status:'active',notificationMode:'normal',attachments:[]});const plan=subject().buildPreparationPlan({store:f.store,mailStore:f.mail,source:f.source,channelId:'channel',archiveRoot:f.unc});assert.ok(plan.rules.every(r=>r.template.action==='reuse'&&r.template.id==='active-template'));});
|
||||
test('an active template with an inline PDF cannot bypass the no-PDF test rule',t=>{const f=fixture(t);f.mail.categoryTemplate=()=>({id:'pdf-template',channelId:'channel',status:'active',notificationMode:'normal',attachments:[{inline:true,filename:'source.pdf',contentType:'application/pdf'}]});const plan=subject().buildPreparationPlan({store:f.store,mailStore:f.mail,source:f.source,channelId:'channel',archiveRoot:f.unc});assert.ok(plan.rules.every(r=>r.template.action==='create'));});
|
||||
test('inline PNG templates also require an attachment-free replacement accepted by runtime',t=>{const f=fixture(t);f.mail.categoryTemplate=()=>({id:'image-template',channelId:'channel',status:'active',notificationMode:'normal',attachments:[{inline:true,filename:'logo.png',contentType:'image/png'}]});const plan=subject().buildPreparationPlan({store:f.store,mailStore:f.mail,source:f.source,channelId:'channel',archiveRoot:f.unc});assert.ok(plan.rules.every(r=>r.template.action==='create'));});
|
||||
test('rule DB rollback keeps old run, orders, drafts and settings when replacement fails',t=>{const f=fixture(t),previous={id:'old-run',version:1,enabled:true,rules:[],recipient:'2639266652@qq.com',archiveRoot:f.unc,channelId:'channel'};f.store.put('restricted-test',{id:'main',value:previous});f.store.put('orders',{id:'unsent',status:'pending',ruleSnapshot:{testRunId:'old-run'},archive:{files:[{path:'old'}]}});const plan=subject().buildPreparationPlan({store:f.store,mailStore:f.mail,source:f.source,runId:'run-2',channelId:'channel',archiveRoot:f.unc});const before=f.store.all('rules'),settings=f.store.settings();assert.throws(()=>subject().applyPreparationPlan({store:f.store,mailStore:f.mail,plan,actor:admin,prepareTemplate:()=>({id:'active-template'}),saveRun:()=>{throw Error('replacement failed');}}),/replacement failed/);assert.deepEqual(f.store.get('restricted-test','main').value,previous);assert.deepEqual(f.store.all('rules'),before);assert.deepEqual(f.store.settings(),settings);assert.equal(f.store.all('restricted-test-history').length,0);assert.equal(f.store.get('orders','unsent').status,'pending');});
|
||||
test('missing category adapter stays blocked instead of expanding source flow aliases',t=>{const f=fixture(t),record=f.store.get('rules','bs-change');f.store.put('rules',{...record,draft:{...record.draft,adapterIds:[]}});const plan=subject().buildPreparationPlan({store:f.store,mailStore:f.mail,source:f.source,channelId:'channel',archiveRoot:f.unc});assert.ok(plan.blockers.some(b=>b.includes('bs-change')));assert.throws(()=>subject().applyPreparationPlan({store:f.store,mailStore:f.mail,plan,actor:admin}),/blocked/i);});
|
||||
test('renamed native category still matches its source identity and keeps the test label',t=>{const f=fixture(t),record=f.store.get('rules','bs-change');f.store.put('rules',{...record,draft:{...record.draft,name:'现有测试类别名'}});delete f.source.rules.find(r=>r.id==='bs-change').id;const plan=subject().buildPreparationPlan({store:f.store,mailStore:f.mail,source:f.source,channelId:'channel',archiveRoot:f.unc});assert.equal(plan.blockers.length,0);assert.equal(plan.rules.find(r=>r.id==='bs-change').draft.productLine,'现有测试类别名');});
|
||||
test('source-incompatible directory is blocked during preview, before any local template is created',t=>{const f=fixture(t),record=f.store.get('rules','bs-change');f.store.put('rules',{...record,draft:{...record.draft,archiveDirectory:'\\\\nas\\formal'}});const plan=subject().buildPreparationPlan({store:f.store,mailStore:f.mail,source:f.source,channelId:'channel',archiveRoot:f.unc});assert.ok(plan.blockers.some(b=>b.includes('bs-change')));});
|
||||
test('native local template preparation preserves all IMAP receipts and cursor without a send operation',t=>{const {MailStore}=require('../../src/modules/mail/store.cjs'),dir=fs.mkdtempSync(path.join(os.tmpdir(),'prepare-mail-'));fs.mkdirSync(path.join(dir,'secrets'),{recursive:true});const mail=new MailStore(dir);t.after(()=>{mail.close();fs.rmSync(dir,{recursive:true,force:true});});const endpoint={host:'localhost',port:993,security:'tls',user:'sender@example.test',password:'local-test-only'},channel=mail.saveChannel({name:'test',email:'sender@example.test',enabled:false,senders:['sender@example.test'],smtp:{...endpoint,port:465},imap:endpoint});mail.db.prepare('UPDATE channels SET cursor=? WHERE id=?').run('{"epoch":"original","uid":901}',channel.id);for(let i=1;i<=501;i++)mail.db.prepare('INSERT INTO receipts(channel_id,epoch,uid,status,detail,at) VALUES(?,?,?,?,?,?)').run(channel.id,'old',i,'skipped','retained','2026-10-22');const before=mail.receipts(),cursor=mail.row(channel.id).cursor;const item={id:'bs-change',template:{action:'create',scope:'test-run-bs-change',subject:'【测试】',text:'大家好\n{{订单列表}}\n\n存放地址:\n{{存放地址}}'}},plan={channelId:channel.id,runId:'run',rules:[item]};const prepared=subject().prepareNativeTemplate(mail,item,plan,admin);assert.equal(prepared.status,'active');assert.equal(prepared.scope,'test-run-bs-change');assert.equal(mail.row(channel.id).cursor,cursor);assert.deepEqual(mail.receipts(),before);assert.equal(mail.db.prepare('SELECT COUNT(*) AS n FROM receipts').get().n,501);assert.deepEqual(mail.sends(),[]);});
|
||||
test('CLI preview readers do not create state, directories, keys or recovery mutations',t=>{const {openStores,parseArgs}=require('../../scripts/prepare-scheduled-test.cjs');const dir=fs.mkdtempSync(path.join(os.tmpdir(),'prepare-readonly-'));t.after(()=>fs.rmSync(dir,{recursive:true,force:true}));assert.throws(()=>openStores(dir));assert.deepEqual(fs.readdirSync(dir),[]);assert.throws(()=>parseArgs(['--apply','--source-file','source.xls']),/BACKUP_REQUIRED/);assert.deepEqual(parseArgs(['--source-file','source.xls']),{apply:false,sourceFile:'source.xls'});});
|
||||
function treeBytes(root){const result={};function visit(dir,prefix=''){for(const name of fs.readdirSync(dir).sort()){const file=path.join(dir,name),relative=prefix+name;if(fs.statSync(file).isDirectory()){result[relative+'/']='directory';visit(file,relative+'/');}else result[relative]=require('node:crypto').createHash('sha256').update(fs.readFileSync(file)).digest('hex');}}visit(root);return result;}
|
||||
function rawWalState(t){const {DatabaseSync}=require('node:sqlite'),root=fs.mkdtempSync(path.join(os.tmpdir(),'prepare-wal-')),state=path.join(root,'state');t.after(()=>fs.rmSync(root,{recursive:true,force:true}));for(const [directory,name] of [['order-rules','rules.sqlite'],['mail','mail.sqlite']]){const target=path.join(state,directory);fs.mkdirSync(target,{recursive:true});const writer=path.join(root,directory+'.sqlite'),db=new DatabaseSync(writer);try{db.exec("PRAGMA journal_mode=WAL; CREATE TABLE marker(value TEXT); INSERT INTO marker VALUES('committed-in-wal')");fs.copyFileSync(writer,path.join(target,name));fs.copyFileSync(writer+'-wal',path.join(target,name+'-wal'));}finally{db.close();}}return {root,state};}
|
||||
test('preview of real WAL databases without SHM preserves every original byte and file',t=>{const {openStores}=require('../../scripts/prepare-scheduled-test.cjs'),f=rawWalState(t),before=treeBytes(f.state);let opened;try{opened=openStores(f.state);assert.equal(opened.store.db.prepare('SELECT value FROM marker').get().value,'committed-in-wal');assert.equal(opened.mailStore.db.prepare('SELECT value FROM marker').get().value,'committed-in-wal');assert.deepEqual(treeBytes(f.state),before);}finally{opened?.close();}assert.deepEqual(treeBytes(f.state),before);});
|
||||
function backupManifest(state,backup,{vaults=[]}={}){const {inventory,sha,verifyBackup}=require('../../src/platform/backup/manifest.cjs');for(const directory of ['state','pdf','keys'])fs.mkdirSync(path.join(backup,directory),{recursive:true});const manifest={format:1,appVersion:'test',source:{stateDir:state,outputDir:require('../../src/platform/backup/snapshot.cjs').defaults(state).outputDir},vaults,...inventory(backup)},bytes=Buffer.from(JSON.stringify(manifest));fs.writeFileSync(path.join(backup,'manifest.json'),bytes);fs.writeFileSync(path.join(backup,'manifest.sha256'),sha(bytes));assert.doesNotThrow(()=>verifyBackup(backup));return manifest;}
|
||||
test('an internally hashed backup omitting existing account state cannot authorize preparation',t=>{const {assertBackupCurrent}=require('../../scripts/prepare-scheduled-test.cjs'),f=rawWalState(t),backup=path.join(f.root,'backup');fs.mkdirSync(path.join(f.state,'accounts'));fs.writeFileSync(path.join(f.state,'accounts','account.json'),'retained-account');fs.mkdirSync(backup);fs.cpSync(f.state,path.join(backup,'state'),{recursive:true,filter:source=>!source.includes(path.sep+'accounts')});const manifest=backupManifest(f.state,backup);assert.throws(()=>assertBackupCurrent(manifest,f.state,backup),/BACKUP_(?:INCOMPLETE|KEY|MANIFEST)/);});
|
||||
test('a complete file listing without the existing encrypted vault key is not restorable',t=>{const {assertBackupCurrent}=require('../../scripts/prepare-scheduled-test.cjs'),{DatabaseSync}=require('node:sqlite'),{BpmVault}=require('../../src/platform/security/vault.cjs'),f=rawWalState(t),vaultDir=path.join(f.state,'order-rules','secrets'),vault=new BpmVault({stateDir:vaultDir}),db=new DatabaseSync(path.join(f.state,'order-rules','rules.sqlite'));try{db.exec('CREATE TABLE records(payload BLOB)');db.prepare('INSERT INTO records VALUES(?)').run(vault.encode('test',{safe:true}));}finally{db.close();vault.destroy();}const backup=path.join(f.root,'backup');fs.mkdirSync(backup);fs.cpSync(f.state,path.join(backup,'state'),{recursive:true});const manifest=backupManifest(f.state,backup);assert.throws(()=>assertBackupCurrent(manifest,f.state,backup),/BACKUP_(?:INCOMPLETE|KEY|MANIFEST)/);});
|
||||
test('a complete current backup with its vault key passes native validation without changing either tree',t=>{const {assertBackupCurrent}=require('../../scripts/prepare-scheduled-test.cjs'),{DatabaseSync}=require('node:sqlite'),{BpmVault}=require('../../src/platform/security/vault.cjs'),f=rawWalState(t),vaultDir=path.join(f.state,'order-rules','secrets'),vault=new BpmVault({stateDir:vaultDir}),db=new DatabaseSync(path.join(f.state,'order-rules','rules.sqlite'));try{db.exec('CREATE TABLE records(payload BLOB)');db.prepare('INSERT INTO records VALUES(?)').run(vault.encode('test',{safe:true}));}finally{db.close();vault.destroy();}fs.mkdirSync(path.join(f.state,'accounts'));fs.writeFileSync(path.join(f.state,'accounts','account.json'),'retained-account');const backup=path.join(f.root,'backup');fs.mkdirSync(backup);fs.cpSync(f.state,path.join(backup,'state'),{recursive:true});const vaults=[];if(process.platform==='win32'){const key=require('../../src/platform/backup/keys.cjs').keyPath(vaultDir),keyFile='keys/'+path.basename(key);fs.mkdirSync(path.join(backup,'keys'));fs.copyFileSync(key,path.join(backup,keyFile));vaults.push({path:'order-rules/secrets',keyFile});}const manifest=backupManifest(f.state,backup,{vaults}),sourceBefore=treeBytes(f.state),backupBefore=treeBytes(backup);assert.doesNotThrow(()=>assertBackupCurrent(manifest,f.state,backup));assert.deepEqual(treeBytes(f.state),sourceBefore);assert.deepEqual(treeBytes(backup),backupBefore);});
|
||||
test('official backup of unchanged committed WAL passes while a later committed row is stale',async t=>{const {assertBackupCurrent}=require('../../scripts/prepare-scheduled-test.cjs'),{createBackup}=require('../../src/platform/backup/snapshot.cjs'),{DatabaseSync}=require('node:sqlite'),f=rawWalState(t),destination=path.join(f.root,'official-backup'),outputDir=path.join(f.state,'restored-pdf');fs.writeFileSync(path.join(f.state,'restore-config.json'),JSON.stringify({outputDir:'restored-pdf'}));assert.ok(fs.statSync(path.join(f.state,'order-rules','rules.sqlite-wal')).size>0);const sourceBefore=treeBytes(f.state),manifest=await createBackup({stateDir:f.state,outputDir,destination}),backupBefore=treeBytes(destination);assert.deepEqual(treeBytes(f.state),sourceBefore);assert.doesNotThrow(()=>assertBackupCurrent(manifest,f.state,destination));assert.deepEqual(treeBytes(f.state),sourceBefore);assert.deepEqual(treeBytes(destination),backupBefore);const writer=new DatabaseSync(path.join(f.state,'order-rules','rules.sqlite'));try{writer.exec("INSERT INTO marker VALUES('committed-after-backup')");const changedBefore=treeBytes(f.state);assert.throws(()=>assertBackupCurrent(manifest,f.state,destination),/BACKUP_STALE/);assert.deepEqual(treeBytes(f.state),changedBefore);assert.deepEqual(treeBytes(destination),backupBefore);}finally{writer.close();}});
|
||||
test('replacement freezes 15 source rules, preserves old records and holds only unfrozen previous-run orders',t=>{const f=fixture(t),previous={id:'old-run',version:1,enabled:true,rules:[],recipient:'2639266652@qq.com',archiveRoot:f.unc,channelId:'channel'};f.store.put('restricted-test',{id:'main',value:previous});for(const status of ['pending','sent','sending','unknown'])f.store.put('orders',{id:status,status,ruleSnapshot:{testRunId:'old-run'},archive:{files:[{path:'original-'+status}]}});const batched={id:'frozen',status:'pending',batchId:'frozen-batch',ruleSnapshot:{testRunId:'old-run'}};f.store.put('orders',batched);f.store.put('batches',{id:'frozen-batch',status:'prepared',orderIds:['frozen']});const batches=f.store.all('batches'),sensitive=['sent','sending','unknown'].map(id=>f.store.get('orders',id));const plan=subject().buildPreparationPlan({store:f.store,mailStore:f.mail,source:f.source,runId:'new-run',channelId:'channel',archiveRoot:f.unc});const result=subject().applyPreparationPlan({store:f.store,mailStore:f.mail,plan,actor:admin,prepareTemplate:()=>({id:'active-template'})});assert.equal(result.run.ruleCount,15);assert.equal(result.settings.enabled,false);assert.equal(result.settings.processingEnabled,false);assert.deepEqual(f.store.get('restricted-test-history','old-run:1').value,previous);assert.deepEqual(f.store.all('batches'),batches);assert.deepEqual(['sent','sending','unknown'].map(id=>f.store.get('orders',id)),sensitive);assert.deepEqual(f.store.get('orders','frozen'),batched);const held=f.store.get('orders','pending');assert.equal(held.status,'blocked');assert.equal(held.ruleSnapshot.testRunId,'old-run');assert.deepEqual(held.archive,{files:[{path:'original-pending'}]});assert.ok(held.preparationHold);for(const rule of f.store.get('restricted-test','main').value.rules){assert.equal(rule.productLine,rule.name);assert.equal(rule.bodyTemplateId,'active-template');assert.equal(rule.nodeNames.includes('生效'),false);assert.deepEqual(rule.to,['2639266652@qq.com']);assert.deepEqual(rule.cc,[]);assert.equal(rule.attachPdf,false);}});
|
||||
@@ -0,0 +1,9 @@
|
||||
'use strict';
|
||||
const test=require('node:test'),assert=require('node:assert/strict'),{extractTitle}=require('../../src/modules/order-rules/title.cjs');
|
||||
test('order identifiers stop before unknown business text while summary keeps that text',()=>{
|
||||
for(const [tail,id]of [['123456 客户名称:测试公司','123456'],['123456|翻单| 总数:20000|','123456'],['123456产品线:测试平台方案:X','123456'],['123456参考订单:654321','123456'],['HA123456机芯号:ABC','HA123456']]){
|
||||
const r=extractTitle('订单号:'+tail);assert.equal(r.orders[0].orderNo,id);assert.equal(r.issues.length,0);assert.ok(r.brief.includes(tail));
|
||||
}
|
||||
const result=extractTitle('订单号:123456 原订单号:654321\n订单号:HA123456客户简称:测试');
|
||||
assert.deepEqual(result.orders.map(o=>o.orderNo),['123456','HA123456']);assert.match(result.brief,/654321/);
|
||||
});
|
||||
@@ -0,0 +1,100 @@
|
||||
'use strict';
|
||||
const {test}=require('node:test');
|
||||
const assert=require('node:assert/strict');
|
||||
const fs=require('node:fs/promises');
|
||||
const os=require('node:os');
|
||||
const path=require('node:path');
|
||||
const {Store}=require('../../src/modules/dashboard/store.cjs');
|
||||
const {createDashboard}=require('../../src/app/dashboard.cjs');
|
||||
const {RuleStore}=require('../../src/modules/order-rules/store.cjs');
|
||||
const {loadPlaywright,browserOptions}=require('../../src/platform/browser.cjs');
|
||||
const {startTestDashboard,login}=require('../fixtures/dashboard-runtime.cjs');
|
||||
|
||||
test('category editor saves/reloads drafts, previews readable evidence without ingesting, and gates execution',{timeout:90000},async t=>{
|
||||
const dir=await fs.mkdtemp(path.join(os.tmpdir(),'order-rules-web-')),store=new Store(path.join(dir,'users'));
|
||||
store.bootstrap('admin','Test-password-123');
|
||||
const server=createDashboard({store,outputDir:dir});await new Promise(r=>server.listen(0,'127.0.0.1',r));
|
||||
let browser;t.after(async()=>{await browser?.close();server.closeAllConnections();await new Promise(r=>server.close(r));await fs.rm(dir,{recursive:true,force:true});});
|
||||
const sample={connectionId:'sample',source:'todo',instanceId:'i1',taskId:'t1',revision:'1',processName:'订单流程',nodeName:'通知',fields:{'订单.数量':0}};
|
||||
const data={rules:[{id:'category-1',version:1,status:'draft',name:'示例类别',categoryId:'category-1',processNames:['订单流程'],nodeNames:['通知'],adapterIds:['a1'],archiveDirectory:'',filenameDate:'appDate',subjectPrefix:'通知',intro:'正文',signature:'团队',to:[],cc:[],attachPdf:true}],adapters:[{id:'a1',label:'订单表单',verified:true,processName:'订单流程',fields:{quantity:'订单.数量'},sample}],orders:[],batches:[],settings:{version:1,enabled:false,processingEnabled:false,processingSince:null,channelId:'',maxMessageBytes:20971520},audit:[],capabilities:{liveTodo:false,pdfExport:false,automaticArchive:false}};
|
||||
data.window={start:'2026-10-20T00:00:00+08:00',end:'2026-10-20T11:00:00+08:00',label:'工作日第一时段',available:true};
|
||||
const writes=[];browser=await loadPlaywright().chromium.launch(browserOptions());const page=await browser.newPage({viewport:{width:1440,height:1000}});page.setDefaultTimeout(7000);const errors=[];page.on('pageerror',e=>errors.push(e.message));await page.clock.install();
|
||||
await page.route('**/api/mail',route=>route.fulfill({json:{channels:[],templates:[],receipts:[],sends:[]}}));
|
||||
await page.route('**/api/order-rules**',async route=>{
|
||||
const req=route.request(),url=new URL(req.url());let result;
|
||||
if(req.method()==='GET'){
|
||||
if(url.pathname.endsWith('/fields'))result={samples:[{id:'real-1',provenance:'server-provider',processName:'订单流程',sample:{...sample,receivedAt:'2026-10-19T09:00:00+08:00'}}]};
|
||||
else if(['/api/order-rules/orders','/api/order-rules/batches'].includes(url.pathname)){
|
||||
const items=url.pathname.endsWith('/orders')?data.orders:data.batches;
|
||||
result={items,total:items.length,page:1,pageSize:25,totalPages:1,from:items.length?1:0,to:items.length,revision:String(items.length)};
|
||||
}else if(url.pathname==='/api/order-rules'){
|
||||
assert.equal(url.searchParams.get('view'),'summary','business views must request the bounded summary');
|
||||
const {orders,batches,audit,...summary}=data;
|
||||
result={...summary,issues:[],templateUsage:[],counts:{orders:orders.length,blocked:0,unknown:0,activeBatches:batches.length}};
|
||||
}else throw Error('Unexpected fixture GET '+url.pathname);
|
||||
}else{
|
||||
const body=req.postDataJSON();writes.push({path:url.pathname,body});
|
||||
if(url.pathname.endsWith('/rules')){data.rules[0]={...data.rules[0],...body,version:data.rules[0].version+1};result=data.rules[0];}
|
||||
else if(url.pathname.endsWith('/trial'))result={valid:true,ruleId:'category-1',checks:[{label:'数量',ok:true,detail:'零数量合法'}],issues:[],explanation:'按类别汇总一封邮件',fieldTrace:[{key:'quantity',label:'数量',path:'订单.数量',value:0}],event:{orderNo:'SAMPLE-1',quantity:0}};
|
||||
else if(url.pathname.endsWith('/publish'))return route.fulfill({status:409,json:{error:'实时待办接入待联调,暂不可发布'}});
|
||||
else if(url.pathname.endsWith('/settings')){
|
||||
if(body.enabled)return route.fulfill({status:409,json:{error:'隔离校验:邮箱及归档条件未就绪,邮件不能启用'}});
|
||||
data.settings={...data.settings,...body,version:data.settings.version+1,processingSince:body.processingEnabled?'2026-10-20T02:00:00Z':data.settings.processingSince};result=data.settings;
|
||||
}else if(url.pathname.endsWith('/prepare'))result={prepared:true};
|
||||
else throw Error('Unexpected fixture POST '+url.pathname);
|
||||
}
|
||||
await route.fulfill({json:result});
|
||||
});
|
||||
await page.goto('http://127.0.0.1:'+server.address().port+'/#order-rules');await page.getByLabel('账号',{exact:true}).waitFor();assert.equal(await page.getByRole('button',{name:'进入演示空间',exact:true}).count(),0);await page.getByLabel('账号',{exact:true}).fill('admin');await page.getByLabel('密码',{exact:true}).fill('Test-password-123');await page.getByRole('button',{name:'登录',exact:true}).click();
|
||||
await openRuleRoute(page,'order-rules');await page.getByLabel('规则名称',{exact:true}).fill('订单类别更新');await page.getByLabel('收件人',{exact:true}).fill('recipient@example.test');await page.getByRole('button',{name:'保存草稿',exact:true}).click();await page.getByText('规则草稿已保存。',{exact:true}).waitFor();
|
||||
assert.equal(data.rules[0].name,'订单类别更新');assert.deepEqual(data.rules[0].to,['recipient@example.test']);assert.deepEqual(writes.find(w=>w.path.endsWith('/rules')).body.processNames,['订单流程']);
|
||||
await page.reload();await openRuleRoute(page,'order-rules');assert.equal(await page.getByLabel('规则名称',{exact:true}).inputValue(),'订单类别更新');
|
||||
await page.getByRole('button',{name:'检查识别结果',exact:true}).click();await page.locator('#order-rule-preview-result').getByText('识别通过',{exact:true}).waitFor();assert.doesNotMatch(await page.locator('#order-rule-preview-result').innerText(),/订单.数量/);assert.match(await page.locator('#order-rule-preview-result').innerText(),/0/);assert.equal(data.orders.length,0);assert.equal(writes.some(x=>x.path.endsWith('/events')),false);assert.equal(writes.find(x=>x.path.endsWith('/trial')).body.sampleId,'real-1');assert.equal(await page.locator('#order-rule-sample').count(),0);
|
||||
await page.getByRole('button',{name:'发布此版本',exact:true}).click();await page.getByText('实时待办接入待联调,暂不可发布',{exact:true}).waitFor();
|
||||
await openRuleRoute(page,'notification-settings');
|
||||
const processing=page.getByLabel('自动处理订单(采集、生成 PDF、归档)',{exact:true}),mail=page.getByLabel('自动发送分类邮件',{exact:true});
|
||||
assert.equal(await processing.isEnabled(),true);assert.equal(await mail.isChecked(),false);
|
||||
await processing.check();await page.getByRole('button',{name:'保存设置',exact:true}).click();await page.getByText('设置已保存。',{exact:true}).waitFor();
|
||||
const settingsWrite=writes.find(w=>w.path.endsWith('/settings'));assert.equal(settingsWrite.body.processingEnabled,true);assert.equal(settingsWrite.body.enabled,false);assert.equal(data.settings.enabled,false);
|
||||
await mail.check();await page.getByRole('button',{name:'保存设置',exact:true}).click();await page.getByText('隔离校验:邮箱及归档条件未就绪,邮件不能启用',{exact:true}).waitFor();assert.equal(data.settings.processingEnabled,true);assert.equal(data.settings.enabled,false);await mail.uncheck();
|
||||
data.orders=[{id:'old',orderNo:'HISTORICAL-ORDER',categoryId:'category-1',status:'pending',receivedAt:'2026-10-19T09:00:00+08:00'},{id:'current',orderNo:'CURRENT-ORDER',categoryId:'category-1',status:'pending',receivedAt:'2026-10-20T09:00:00+08:00'},{id:'future',orderNo:'FUTURE-ORDER',categoryId:'category-1',status:'pending',receivedAt:'2026-10-20T15:00:00+08:00'}];
|
||||
await openRuleRoute(page,'notification-orders');await page.getByText('HISTORICAL-ORDER',{exact:true}).waitFor();await page.getByText('CURRENT-ORDER',{exact:true}).waitFor();await page.getByText('FUTURE-ORDER',{exact:true}).waitFor();assert.equal(await page.locator('[data-rule-recheck]').count(),0,'retired inline recheck is not restored');
|
||||
data.batches=[{id:'old-batch',categoryId:'category-1',subject:'旧窗口仍未终结批次',status:'prepared',windowStart:'2026-10-19T00:00:00+08:00',windowEnd:'2026-10-19T11:00:00+08:00',orderCount:0}];
|
||||
await openRuleRoute(page,'notification-batches');await page.getByText('旧窗口仍未终结批次',{exact:true}).waitFor();
|
||||
assert.equal(await page.getByLabel('本批截止时间(北京时间)',{exact:true}).count(),0);await page.getByRole('button',{name:'整理本时段批次',exact:true}).click();await page.getByText('批次整理已完成,请核对受阻原因与冻结结果。',{exact:true}).waitFor();assert.deepEqual(writes.find(x=>x.path.endsWith('/prepare')).body,{cutoff:data.window.end});
|
||||
data.window.available=false;await page.reload();await page.getByText('未在配置发送时点的整理期限内。',{exact:true}).waitFor();assert.equal(await page.getByRole('button',{name:'整理本时段批次',exact:true}).isDisabled(),true);
|
||||
data.batches.push({id:'fresh-batch',categoryId:'category-1',subject:'后台新增批次',status:'prepared',windowStart:data.window.start,windowEnd:data.window.end,orderCount:0});
|
||||
await page.clock.fastForward(11000);await page.getByText('记录有更新。',{exact:true}).waitFor();assert.equal(await page.getByText('后台新增批次',{exact:true}).count(),0,'polling must not replace the displayed page');
|
||||
await page.locator('#content .card-header').getByRole('button',{name:'刷新记录',exact:true}).click();await page.getByText('后台新增批次',{exact:true}).waitFor();await page.getByText('旧窗口仍未终结批次',{exact:true}).waitFor();
|
||||
await openRuleRoute(page,'order-rules');await page.getByLabel('规则名称',{exact:true}).fill('保留尚未保存的规则');await page.clock.fastForward(15001);assert.equal(await page.getByLabel('规则名称',{exact:true}).inputValue(),'保留尚未保存的规则');
|
||||
await page.setViewportSize({width:390,height:844});assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true);assert.deepEqual(errors,[]);
|
||||
});
|
||||
|
||||
test('ordinary admin login opens all category rules without a demo entry',{timeout:60000},async t=>{
|
||||
const dir=await fs.mkdtemp(path.join(os.tmpdir(),'order-rules-preview-web-'));const runtime=await startTestDashboard({stateDir:dir});let browser;t.after(async()=>{await browser?.close();runtime.server.closeAllConnections();await runtime.close();await fs.rm(dir,{recursive:true,force:true});});browser=await loadPlaywright().chromium.launch(browserOptions());const page=await browser.newPage();await page.goto('http://127.0.0.1:'+runtime.server.address().port+'/#order-rules');assert.equal(await page.getByRole('button',{name:'进入演示空间',exact:true}).count(),0);await login(page);await openRuleRoute(page,'order-rules');await page.getByText('Excel 分类 · 15',{exact:true}).waitFor();assert.equal(runtime.orderRules.snapshot().orders.length,0);assert.equal(await page.getByLabel('规则名称',{exact:true}).isEnabled(),true);
|
||||
});
|
||||
|
||||
test('real catalog workflow publishes a saved and sampled draft while roles and production gates remain enforced',{timeout:90000},async t=>{
|
||||
const dir=await fs.mkdtemp(path.join(os.tmpdir(),'order-rules-real-web-')),store=new Store(path.join(dir,'users'));store.bootstrap('admin','Test-password-123');
|
||||
for(const role of ['operator','viewer'])store.addUser({username:role,password:'Test-password-123',role},'admin');
|
||||
const orderRules=new RuleStore(path.join(dir,'rules')),server=createDashboard({store,orderRules,outputDir:dir});await new Promise(r=>server.listen(0,'127.0.0.1',r));let browser;
|
||||
t.after(async()=>{await browser?.close();server.closeAllConnections();await new Promise(r=>server.close(r));orderRules.close();await fs.rm(dir,{recursive:true,force:true});});
|
||||
browser=await loadPlaywright().chromium.launch(browserOptions());const base='http://127.0.0.1:'+server.address().port;
|
||||
async function open(role){const page=await browser.newPage({viewport:{width:1440,height:1000}});page.setDefaultTimeout(7000);await page.goto(base+'/#order-rules');await page.getByLabel('账号',{exact:true}).fill(role);await page.getByLabel('密码',{exact:true}).fill('Test-password-123');await page.getByRole('button',{name:'登录',exact:true}).click();await openRuleRoute(page,'order-rules');return page;}
|
||||
const initial=orderRules.get('rules','bs-change').draft;orderRules.saveRule({...initial,archiveDirectory:'\\\\fixture-server\\orders\\changes'},'admin');const page=await open('admin');await page.locator('[data-rule-id="bs-change"]').click();await page.getByLabel('规则名称',{exact:true}).fill('备损更改通知测试');await page.getByLabel('文件名日期依据',{exact:true}).selectOption('appDate');await page.getByLabel('收件人',{exact:true}).fill('recipient@example.test');await page.getByRole('button',{name:'保存草稿',exact:true}).click();await page.getByText('规则草稿已保存。',{exact:true}).waitFor();
|
||||
await page.reload();await openRuleRoute(page,'order-rules');await page.locator('[data-rule-id="bs-change"]').click();assert.equal(await page.getByLabel('规则名称',{exact:true}).inputValue(),'备损更改通知测试');
|
||||
assert.equal(await page.locator('#order-rule-preview').isDisabled(),true);await page.getByRole('button',{name:'发布此版本',exact:true}).click();await page.getByText('发布前必须选择服务端真实采集样本完成试运行。',{exact:true}).waitFor();
|
||||
const {captured}=require('../fixtures/activate-field-mapping.cjs').activateReferenceMapping(orderRules);
|
||||
await page.reload();await openRuleRoute(page,'order-rules');await page.locator('[data-rule-id="bs-change"]').click();
|
||||
const trial=await page.request.post(base+'/api/order-rules/preview',{headers:{Origin:base},data:{sampleId:captured.id}});assert.equal(trial.status(),200);assert.equal((await trial.json()).valid,true);
|
||||
await page.getByRole('button',{name:'发布此版本',exact:true}).click();await page.getByText('规则版本已发布。自动执行仍由全局设置与接入状态控制。',{exact:true}).waitFor();
|
||||
assert.equal(orderRules.snapshot().rules.find(r=>r.id==='bs-change').status,'enabled');assert.equal(orderRules.snapshot().settings.enabled,false);assert.equal(orderRules.snapshot().orders.length,0);
|
||||
await page.setViewportSize({width:390,height:844});assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true);
|
||||
await fs.mkdir(path.resolve('output/verification'),{recursive:true});await page.screenshot({path:path.resolve('output/verification/order-rules-mobile.png'),fullPage:true});await page.setViewportSize({width:1440,height:1000});await page.screenshot({path:path.resolve('output/verification/order-rules-desktop.png'),fullPage:true});
|
||||
const operator=await open('operator');assert.equal(await operator.getByLabel('规则名称',{exact:true}).isDisabled(),true);assert.equal(await operator.getByRole('button',{name:'保存草稿',exact:true}).count(),0);assert.equal(await operator.getByRole('button',{name:'检查识别结果',exact:true}).count(),1);
|
||||
const viewer=await open('viewer');assert.equal(await viewer.getByLabel('规则名称',{exact:true}).isDisabled(),true);assert.equal(await viewer.getByRole('button',{name:'检查识别结果',exact:true}).count(),0);
|
||||
});
|
||||
|
||||
async function openRuleRoute(page,hash){
|
||||
await page.evaluate(hash=>{const link=document.createElement('a');link.href='#'+hash;document.body.append(link);link.click();link.remove();},hash);
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
'use strict';
|
||||
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 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-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);
|
||||
});
|
||||
test('Monday first mail covers last workday final cutoff through Monday morning, never older history',()=>{
|
||||
const window=windowForCutoff('2026-10-19T03:00:00Z',schedule);
|
||||
assert.equal(window.start,'2026-10-16T09:00:00.000Z');assert.equal(window.end,'2026-10-19T03:00:00.000Z');
|
||||
assert.equal(inWindow('2026-10-16T08:59:59Z',window),false);assert.equal(inWindow('2026-10-17T10:00:00Z',window),true);
|
||||
});
|
||||
test('business calendar determines previous actual working day across a rest period',()=>{
|
||||
const window=windowForCutoff('2026-10-19T03:00:00Z',schedule,[{date:'2026-10-16',kind:'restday',send:false,scan:false}]);
|
||||
assert.equal(window.start,'2026-10-15T09:00:00.000Z');
|
||||
assert.throws(()=>windowForCutoff('2026-10-18T03:00:00Z',schedule),e=>e.status===400);
|
||||
assert.throws(()=>windowForCutoff('2026-10-20T04:00:00Z',schedule),e=>e.status===400);
|
||||
});
|
||||
test('future preview cannot freeze a mail before its cutoff; missed slots do not reopen old windows',()=>{
|
||||
const next=upcomingWindow(new Date('2026-10-20T02:00:00Z'),schedule);
|
||||
assert.equal(next.end,'2026-10-20T03:00:00.000Z');assert.equal(next.available,false);
|
||||
assert.equal(upcomingWindow(new Date('2026-10-20T03:00:30Z'),schedule).available,true);
|
||||
const missed=upcomingWindow(new Date('2026-10-20T03:02:00Z'),schedule);
|
||||
assert.equal(missed.start,'2026-10-20T03:00:00.000Z');assert.equal(missed.available,false);
|
||||
});
|
||||
@@ -0,0 +1,69 @@
|
||||
'use strict';
|
||||
const {activateFieldMapping,activateReferenceMapping}=require('../fixtures/activate-field-mapping.cjs');
|
||||
const test=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs/promises'),os=require('node:os'),path=require('node:path');
|
||||
const {startTestDashboard,login}=require('../fixtures/dashboard-runtime.cjs');
|
||||
const {loadPlaywright,browserOptions}=require('../../src/platform/browser.cjs');
|
||||
async function setup(t){
|
||||
const dir=await fs.mkdtemp(path.join(os.tmpdir(),'rule-workbench-ui-')),runtime=await startTestDashboard({stateDir:dir}),browser=await loadPlaywright().chromium.launch(browserOptions());
|
||||
t.after(async()=>{await browser.close();await runtime.close();await fs.rm(dir,{recursive:true,force:true});});
|
||||
const {captured}=activateReferenceMapping(runtime.orderRules);
|
||||
const initial=runtime.orderRules.get('rules','bs-change').draft;runtime.orderRules.saveRule({...initial,archiveDirectory:'\\\\fixture-server\\orders'},'admin');
|
||||
const page=await browser.newPage({viewport:{width:1440,height:1000}});page.setDefaultTimeout(7000);await page.route('**/api/order-rules/fields',route=>route.fulfill({json:runtime.orderRules.fields()}));
|
||||
await page.goto('http://127.0.0.1:'+runtime.server.address().port+'/#order-rules');await login(page);await page.locator('[data-rule-id="bs-change"]').click();return{page,runtime,captured,browser};
|
||||
}
|
||||
test('workbench searches categories, pairs rows and trials unsaved input before saved real evidence',{timeout:90000},async t=>{
|
||||
const {page,runtime,captured}=await setup(t);
|
||||
assert.match(await page.locator('#rule-field-coverage').innerText(),/识别接口已变化.*重新验证/);
|
||||
assert.equal(await page.locator('#rule-category-list').evaluate(list=>{const row=list.querySelector('[aria-current]'),a=row.getBoundingClientRect(),b=list.getBoundingClientRect();return a.top>=b.top&&a.bottom<=b.bottom;}),true);
|
||||
await page.getByLabel('搜索分类',{exact:true}).fill('备损');assert.equal(await page.locator('[data-rule-id]').count(),2);
|
||||
await page.getByRole('heading',{name:'适用通知',exact:true}).waitFor();
|
||||
await page.getByRole('button',{name:'添加流程节点',exact:true}).click();assert.equal(await page.locator('[data-scope-row]').count(),2);
|
||||
await page.getByLabel('第2行适用流程',{exact:true}).selectOption('试产订单更改评审');await page.getByLabel('第2行触发节点',{exact:true}).selectOption({index:1});
|
||||
await page.getByRole('button',{name:'删除第2行',exact:true}).click();assert.equal(await page.locator('[data-scope-row]').count(),1);
|
||||
await page.getByLabel('文件名日期依据',{exact:true}).selectOption('receivedAt');await page.getByLabel('收件人',{exact:true}).fill('orders@example.test');await page.getByLabel('邮件主题前缀',{exact:true}).fill('【未保存预览】');
|
||||
await page.getByLabel('已采集的 BPM 订单',{exact:true}).selectOption('capture:'+captured.id);await page.getByRole('button',{name:'检查识别结果',exact:true}).click();
|
||||
await page.locator('#order-rule-preview-result').getByText('这是尚未保存的配置结果;保存后请再次检查。',{exact:true}).waitFor();assert.match(await page.locator('#order-rule-preview-result').innerText(),/未保存预览/);assert.match(await page.locator('#order-rule-preview-result').innerText(),/fixture-server/);assert.equal(runtime.orderRules.get('rules','bs-change').trialVersion,null);assert.equal(runtime.orderRules.all('orders').length,0);
|
||||
await page.getByRole('link',{name:'字段映射',exact:true}).first().click();await page.getByRole('button',{name:'留在此页',exact:true}).click();assert.match(page.url(),/#order-rules$/);
|
||||
await page.getByRole('button',{name:'保存草稿',exact:true}).click();await page.getByText('规则草稿已保存。',{exact:true}).waitFor();assert.equal(runtime.orderRules.get('rules','bs-change').draft.scopes.length,1);
|
||||
await page.getByLabel('已采集的 BPM 订单',{exact:true}).selectOption('capture:'+captured.id);await page.getByRole('button',{name:'检查识别结果',exact:true}).click();await page.locator('#order-rule-preview-result').getByText('已保存规则通过真实订单检查,可以继续核对并发布。',{exact:true}).waitFor();
|
||||
await page.getByRole('button',{name:'发布此版本',exact:true}).click();await page.getByText('规则版本已发布。自动执行仍由全局设置与接入状态控制。',{exact:true}).waitFor();assert.equal(runtime.orderRules.settings().enabled,false);
|
||||
await page.getByLabel('分类状态',{exact:true}).selectOption('published');assert.equal(await page.locator('[data-rule-id]').count(),1);
|
||||
await fs.mkdir('output/verification',{recursive:true});await page.screenshot({path:'output/verification/rule-workbench-isolated-desktop.png',fullPage:true});await page.setViewportSize({width:390,height:844});assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true);await page.screenshot({path:'output/verification/rule-workbench-isolated-mobile.png',fullPage:true});
|
||||
});
|
||||
test('editing while a trial is pending invalidates its output and failed saves preserve input',{timeout:60000},async t=>{
|
||||
const {page}=await setup(t);let release;const pending=new Promise(r=>release=r);
|
||||
await page.route('**/api/order-rules/rules/bs-change/trial',async route=>{await pending;await route.fulfill({json:{valid:true,ruleId:'bs-change',checks:[],issues:[],explanation:'迟到旧结果'}});});
|
||||
await page.getByRole('button',{name:'检查识别结果',exact:true}).click();await page.getByLabel('规则名称',{exact:true}).fill('新输入不能被旧结果覆盖');release();await page.waitForFunction(()=>!document.querySelector('#order-rule-preview').disabled);
|
||||
assert.doesNotMatch(await page.locator('#order-rule-preview-result').innerText(),/迟到旧结果/);
|
||||
await page.route('**/api/order-rules/rules',route=>route.fulfill({status:409,json:{error:'规则版本冲突,请刷新核对'}}));await page.getByRole('button',{name:'保存草稿',exact:true}).click();await page.getByText('规则版本冲突,请刷新核对',{exact:true}).waitFor();assert.equal(await page.getByLabel('规则名称',{exact:true}).inputValue(),'新输入不能被旧结果覆盖');
|
||||
});
|
||||
|
||||
test('saved state remains the clean baseline when the following list refresh fails',{timeout:60000},async t=>{
|
||||
const {page,runtime}=await setup(t);await page.getByLabel('规则名称',{exact:true}).fill('已保存但刷新失败');
|
||||
await page.route('**/api/order-rules?view=summary',route=>route.fulfill({status:503,json:{error:'列表暂不可用'}}));
|
||||
await page.getByRole('button',{name:'保存草稿',exact:true}).click();await page.getByText(/规则草稿已保存。 刷新失败/).waitFor();
|
||||
assert.equal(runtime.orderRules.get('rules','bs-change').draft.name,'已保存但刷新失败');assert.equal(await page.getByLabel('规则名称',{exact:true}).inputValue(),'已保存但刷新失败');
|
||||
await page.getByLabel('规则名称',{exact:true}).dispatchEvent('input');
|
||||
assert.equal(await page.locator('#order-rule-dirty').innerText(),'');await page.getByRole('link',{name:'字段映射',exact:true}).first().click();assert.equal(await page.getByRole('dialog',{name:'未保存的修改'}).count(),0);
|
||||
});
|
||||
|
||||
test('publishing locks other rule mutations and pause after Save and Continue uses the refreshed draft',{timeout:60000},async t=>{
|
||||
const {page,runtime,captured}=await setup(t);let release,arrive;const gate=new Promise(r=>release=r),arrived=new Promise(r=>arrive=r);
|
||||
await page.route('**/api/order-rules/rules/bs-change/publish',async route=>{arrive();await gate;await route.fulfill({status:409,json:{error:'隔离发布校验阻塞'}});});
|
||||
await page.getByRole('button',{name:'发布此版本',exact:true}).click();await arrived;const locked=await page.getByLabel('规则名称',{exact:true}).isDisabled(),saveLocked=await page.getByRole('button',{name:'保存草稿',exact:true}).isDisabled();release();await page.getByText('隔离发布校验阻塞',{exact:true}).waitFor();assert.equal(locked,true);assert.equal(saveLocked,true);await page.unroute('**/api/order-rules/rules/bs-change/publish');
|
||||
const old=runtime.orderRules.get('rules','bs-change').draft,saved=runtime.orderRules.saveRule({...old,to:['orders@example.test'],archiveDirectory:'\\\\fixture-server\\orders',filenameDate:'receivedAt'},'admin');runtime.orderRules.trial(saved.id,{version:saved.version,sampleId:captured.id});runtime.orderRules.publish(saved.id,{version:saved.version},'admin');
|
||||
await page.getByRole('button',{name:'刷新规则与字段',exact:true}).click();await page.getByLabel('规则名称',{exact:true}).fill('保存后暂停的草稿');await page.locator('[data-rule-toggle="bs-change"]').click();await page.getByRole('button',{name:'保存并继续',exact:true}).click();await page.getByText('此规则已暂停。',{exact:true}).waitFor();assert.equal(runtime.orderRules.get('rules',saved.id).published.status,'paused');assert.equal(runtime.orderRules.get('rules',saved.id).draft.name,'保存后暂停的草稿');
|
||||
await page.locator('[data-rule-toggle="bs-change"]').click();await page.getByText('已启用已发布版本,未发布草稿保持不变。',{exact:true}).waitFor();assert.equal(runtime.orderRules.get('rules',saved.id).published.name,saved.name);assert.equal(runtime.orderRules.get('rules',saved.id).draft.name,'保存后暂停的草稿');
|
||||
});
|
||||
test('rule search is not a dirty edit and operators/viewers keep their role boundaries',{timeout:90000},async t=>{
|
||||
const {page,runtime,browser}=await setup(t);await page.getByLabel('搜索分类',{exact:true}).fill('不存在类别');assert.equal(await page.locator('[data-rule-id]').count(),0);await page.getByRole('link',{name:'字段映射',exact:true}).first().click();assert.equal(await page.getByRole('dialog',{name:'未保存的修改'}).count(),0);
|
||||
const base=new URL(page.url()).origin;
|
||||
for(const role of ['operator','viewer']){runtime.store.addUser({username:role,password:'Test-password-123',role},'admin');const context=await browser.newContext(),member=await context.newPage();await member.goto(base+'/#order-rules');await member.getByLabel('账号',{exact:true}).fill(role);await member.getByLabel('密码',{exact:true}).fill('Test-password-123');await member.getByRole('button',{name:'登录',exact:true}).click();await member.getByLabel('规则名称',{exact:true}).waitFor();assert.equal(await member.getByLabel('规则名称',{exact:true}).isDisabled(),true);assert.equal(await member.getByRole('button',{name:'保存草稿',exact:true}).count(),0);assert.equal(await member.getByRole('button',{name:'检查识别结果',exact:true}).count(),role==='operator'?1:0);await context.close();}
|
||||
});
|
||||
|
||||
test('captured field evidence follows the adapter selected in the current draft rather than registry order',{timeout:60000},async t=>{
|
||||
const {page,runtime}=await setup(t),original=require('../../src/modules/order-rules/catalog.cjs').adapters.find(a=>a.id==='bs-change').sample,real={...original,demo:false,title:'订单号:ALT-2',fields:{...original.fields,'Alternate.Order':'ALT-2','Alternate.Brief':'新字段摘要'}};
|
||||
const capture=runtime.orderRules.recordCapture({taskId:'alternate-fields',sample:real,snapshot:{processVersion:real.processVersion,fields:Object.entries(real.fields).map(([path,value])=>({path,value}))}}),adapter=activateFieldMapping(runtime.orderRules,{sampleId:capture.id,processName:real.processName,processVersion:real.processVersion,version:1,fields:{orderNo:'Alternate.Order',brief:'Alternate.Brief'}},{username:'admin',role:'admin'});
|
||||
const old=runtime.orderRules.get('rules','bs-change').draft;runtime.orderRules.saveRule({...old,adapterIds:[adapter.id]},'admin');await page.getByRole('button',{name:'刷新规则与字段',exact:true}).click();await page.waitForFunction(()=>!document.querySelector('#order-rule-refresh').disabled);await page.getByLabel('已采集的 BPM 订单',{exact:true}).selectOption('capture:'+capture.id);
|
||||
await page.getByRole('button',{name:'检查识别结果',exact:true}).click();await page.locator('#order-rule-preview-result').getByText('ALT-2',{exact:true}).waitFor();assert.doesNotMatch(await page.locator('#order-rule-preview-result').innerText(),/Alternate\.Order/);assert.equal(await page.locator('[data-adapter-choice]').count(),0);
|
||||
});
|
||||
@@ -0,0 +1,48 @@
|
||||
'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 {previewMatch}=require('../../src/modules/order-rules/matching.cjs');
|
||||
const {seedRules,adapters}=require('../../src/modules/order-rules/catalog.cjs');
|
||||
const {activateReferenceMapping}=require('../fixtures/activate-field-mapping.cjs');
|
||||
function setup(t){const dir=fs.mkdtempSync(path.join(os.tmpdir(),'rule-workbench-')),store=new RuleStore(dir,{clock:()=>new Date('2026-10-19T02:00:00Z')});t.after(()=>{store.close();fs.rmSync(dir,{recursive:true,force:true});});const {sample,captured}=activateReferenceMapping(store),old=store.get('rules','bs-change').draft;return{store,old,sample,captured};}
|
||||
test('paired scopes never match the cross product while legacy arrays retain their meaning',()=>{
|
||||
const rules=seedRules(),rule=rules.find(r=>r.id==='bs-change'),sample=adapters.find(a=>a.id==='bs-change').sample;
|
||||
rule.processNames.push('另一个流程');rule.nodeNames.push('另一个节点');rule.scopes=[{processName:sample.processName,nodeName:sample.nodeName},{processName:'另一个流程',nodeName:'另一个节点'}];
|
||||
assert.equal(previewMatch(rules,adapters,{...sample,nodeName:'另一个节点'}).ruleId,null);
|
||||
assert.equal(previewMatch(rules,adapters,sample).ruleId,rule.id);
|
||||
delete rule.scopes;assert.equal(previewMatch(rules,adapters,{...sample,nodeName:'另一个节点'}).ruleId,rule.id);
|
||||
});
|
||||
test('saving paired scopes validates rows and persists derived legacy fields without rewriting publications',t=>{
|
||||
const {store,old,sample}=setup(t),scopes=[{processName:sample.processName,nodeName:sample.nodeName},{processName:'另一流程',nodeName:'另一节点'}];
|
||||
const saved=store.saveRule({...old,scopes},'admin');assert.deepEqual(saved.scopes,scopes);assert.deepEqual(saved.processNames,[sample.processName,'另一流程']);assert.deepEqual(saved.nodeNames,[sample.nodeName,'另一节点']);
|
||||
assert.equal(store.get('rules',old.id).published,null);
|
||||
for(const scopes of [null,[{processName:sample.processName,nodeName:''}],[{processName:sample.processName,nodeName:sample.nodeName,script:'bad'}]])assert.throws(()=>store.saveRule({...saved,scopes},'admin'),/范围|节点|配对/);
|
||||
});
|
||||
test('unsaved draft trial previews the actual proposed output without writing rule, trial or order evidence',t=>{
|
||||
const {store,old,sample,captured}=setup(t),draft={...old,subjectPrefix:'【草稿预览】',to:['orders@example.test'],archiveDirectory:'\\\\server\\orders',filenameDate:'receivedAt'};
|
||||
const before=store.get('rules',old.id),result=store.trial(old.id,{version:old.version,draft,sampleId:captured.id});
|
||||
assert.equal(result.valid,true);assert.equal(result.trial.saved,false);assert.equal(result.trial.publishEvidence,false);assert.equal(result.effects.simulation,true);assert.match(result.effects.mail.subject,/草稿预览/);assert.match(result.effects.filename,/\.pdf$/);assert.match(result.effects.path,/server\\orders/);assert.equal(result.effects.archiveVerified,false);
|
||||
assert.deepEqual(store.get('rules',old.id),before);assert.equal(store.all('orders').length,0);assert.equal(store.all('batches').length,0);assert.equal(store.settings().enabled,false);
|
||||
assert.throws(()=>store.publish(old.id,{version:old.version},'admin'),/真实结构样本|收件人|目录/);
|
||||
});
|
||||
test('only current persisted draft plus immutable captured sample can establish publish evidence',t=>{
|
||||
const {store,old,captured,sample}=setup(t),saved=store.saveRule({...old,to:['orders@example.test'],archiveDirectory:'\\\\server\\orders',filenameDate:'appDate',scopes:[{processName:sample.processName,nodeName:sample.nodeName}]},'admin');
|
||||
const untrusted=store.trial(old.id,{version:saved.version,sample});assert.equal(untrusted.trial.publishEvidence,false);assert.equal(store.get('rules',old.id).trialSampleId,null);
|
||||
const real=store.trial(old.id,{version:saved.version,draft:saved,sampleId:captured.id});assert.equal(real.trial.saved,true);assert.equal(real.trial.publishEvidence,true);assert.equal(store.get('rules',old.id).trialSampleId,captured.id);
|
||||
store.publish(old.id,{version:saved.version},'admin');const published=store.get('rules',old.id).published;
|
||||
const edited=store.saveRule({...saved,intro:'后续草稿'},'admin');assert.throws(()=>store.trial(old.id,{version:saved.version,sampleId:captured.id}),e=>e.status===409);assert.equal(store.get('rules',old.id).published.intro,published.intro);assert.equal(store.get('rules',old.id).trialVersion,null);assert.equal(edited.version,saved.version+1);
|
||||
});
|
||||
test('trial reports selected-category mismatch and does not grant evidence to another category',t=>{
|
||||
const {store,old,captured}=setup(t),other=store.get('rules','trial-change').draft;
|
||||
const result=store.trial(other.id,{version:other.version,sampleId:captured.id});assert.equal(result.valid,false);assert.match(result.issues.join(';'),/当前类别/);assert.equal(result.effects,null);assert.equal(store.get('rules',old.id).trialSampleId,null);
|
||||
});
|
||||
|
||||
test('publication overlap uses paired rows and permits disjoint pairs sharing both columns',t=>{
|
||||
const {store,old,sample}=setup(t),secondMapping=activateReferenceMapping(store,'overseas-change'),other=store.get('rules','overseas-change').draft,second=secondMapping.sample;
|
||||
const scopes=[{processName:sample.processName,nodeName:'节点甲'},{processName:second.processName,nodeName:'节点乙'}];
|
||||
const configure=(rule,rows)=>store.saveRule({...rule,scopes:rows,adapterIds:store.adapters().filter(adapter=>!adapter.reference).map(adapter=>adapter.id),to:['orders@example.test'],archiveDirectory:'\\\\server\\orders',filenameDate:'receivedAt'},'admin');
|
||||
const a=configure(old,scopes),b=configure(other,[{processName:sample.processName,nodeName:'节点乙'},{processName:second.processName,nodeName:'节点甲'}]);
|
||||
const check=(rule,nodeName)=>{const real={...sample,nodeName,demo:false},capture=store.recordCapture({taskId:rule.id,sample:real,snapshot:{processVersion:real.processVersion,fields:Object.entries(real.fields).map(([path,value])=>({path,value}))}});assert.equal(store.trial(rule.id,{version:rule.version,sampleId:capture.id}).valid,true);};
|
||||
check(a,'节点甲');store.publish(a.id,{version:a.version},'admin');check(b,'节点乙');assert.equal(store.publish(b.id,{version:b.version},'admin').status,'enabled');
|
||||
const overlapping=configure(b,scopes);assert.throws(()=>store.publish(b.id,{version:overlapping.version},'admin'),/冲突/);
|
||||
});
|
||||
Reference in new issue
Block a user