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

41 lines
8.4 KiB
JavaScript

'use strict';
const test=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs'),os=require('node:os'),path=require('node:path'),crypto=require('node:crypto');
const {RuleStore}=require('../../src/modules/order-rules/store.cjs'),{activateReferenceMapping}=require('../fixtures/activate-field-mapping.cjs');
const actor={username:'admin',role:'admin'};
function fixture(t){const dir=fs.mkdtempSync(path.join(os.tmpdir(),'collecting-batches-'));let now=new Date('2026-10-26T01:00:00Z');const s=new RuleStore(dir,{clock:()=>now,capabilities:{liveTodo:true,pdfExport:true,automaticArchive:true}});t.after(()=>{s.close();assert.equal(path.dirname(fs.realpathSync(dir)).toLowerCase(),fs.realpathSync(os.tmpdir()).toLowerCase());fs.rmSync(dir,{recursive:true,force:true});});const e=activateReferenceMapping(s).sample,old=s.get('rules','bs-change').draft,rule=s.saveRule({...old,archiveDirectory:'\\\\fixture\\orders',to:['2639266652@qq.com'],cc:[],filenameDate:'receivedAt',bodyTemplateId:''},'admin');s.put('rules',{...s.get('rules',rule.id),published:{...rule,status:'enabled'}});s.saveSettings({...s.settings(),channelId:'fixture-channel',processingEnabled:true,enabled:true},'admin');
const add=(id,time='2026-10-26T00:30:00Z')=>{const o=s.ingest({...e,taskId:id,instanceId:'instance-'+id,receivedAt:time,title:'订单号:'+id+'机芯号:CORE',fields:{...e.fields,[require('../../src/modules/order-rules/catalog.cjs').adapters.find(a=>a.id==='bs-change').fields.orderNo]:id}},'fixture');assert.equal(o.status,'identified',o.error);const bytes=Buffer.from('%PDF-1.7 fixture');s.recordArchive(o.id,{archivedAt:now.toISOString(),files:[{name:id+'.pdf',path:'C:\\fixture\\'+id+'.pdf',size:bytes.length,sha256:crypto.createHash('sha256').update(bytes).digest('hex'),kind:'pdf'}]},'fixture');return s.get('orders',o.id);};return {s,dir,rule,add,setNow:value=>now=new Date(value)};}
test('matched current-window orders collect by category, stay dynamic and freeze edited HTML once',t=>{
const f=fixture(t),c=require('../../src/modules/order-rules/collecting-batches.cjs'),a=f.add('ONE'),initial=c.list(f.s);assert.equal(initial.length,1);assert.equal(f.s.all('batches').length,0);assert.equal(initial[0].status,'collecting');assert.equal(initial[0].orderIds[0],a.id);
const draft=c.save(f.s,initial[0].id,{version:0,context:initial[0].context,subject:'本批 {{订单号}}',format:'html',body:'<p>自定义说明</p><div>{{订单明细}}</div><p>{{存放地址}}</p>'},actor);assert.equal(draft.version,1);
const b=f.add('TWO'),next=c.get(f.s,initial[0].id);assert.equal(next.orderIds.length,2);assert.match(next.text,/自定义说明/);assert.match(next.text,/ONE/);assert.match(next.text,/TWO/);assert.equal(next.orderIds[1],b.id);assert.equal(f.s.get('rules','bs-change').draft.intro,f.rule.intro);
assert.throws(()=>c.save(f.s,next.id,{version:0,context:next.context,subject:'冲突',format:'text',body:'{{订单明细}}\n{{存放地址}}'},actor),e=>e.status===409);
f.setNow('2026-10-26T03:00:00Z');assert.throws(()=>c.save(f.s,next.id,{version:1,context:next.context,subject:'太晚',format:'text',body:'{{订单明细}}\n{{存放地址}}'},actor),e=>e.status===409);
const [frozen]=f.s.prepare('2026-10-26T03:00:00Z','fixture');assert(frozen);assert.match(frozen.text,/自定义说明/);assert.equal(frozen.contentEdit.version,1);assert.deepEqual(frozen.orderIds,[a.id,b.id]);assert.deepEqual(frozen.attachments,[]);assert.equal(c.list(f.s).length,0);
});
test('unknown candidates and historical windows do not collect; editing validates variables and operator scope',t=>{
const f=fixture(t),c=require('../../src/modules/order-rules/collecting-batches.cjs');f.add('CURRENT');const group=c.list(f.s)[0];f.s.put('orders',{id:'unmatched',status:'blocked',event:{receivedAt:'2026-10-26T00:00:00Z'}});assert.equal(c.list(f.s).length,1);
for(const body of ['没有订单区','{{订单明细}}','{{不存在}}\n{{订单明细}}\n{{存放地址}}'])assert.throws(()=>c.save(f.s,group.id,{version:0,context:group.context,subject:'标题',format:'text',body},actor));assert.equal(f.s.all('batch-content-drafts').length,0);
assert.throws(()=>c.save(f.s,group.id,{version:0,context:group.context,subject:'标题',format:'text',body:'{{订单明细}}\n{{存放地址}}'},{username:'viewer',role:'viewer'}),e=>e.status===403);
f.setNow('2026-10-26T04:00:00Z');assert.equal(c.list(f.s).length,0);assert.equal(f.s.all('batches').length,0);
});
test('query links both directions, preserves edits on disk and rechecks template context before freeze',t=>{
const f=fixture(t),c=require('../../src/modules/order-rules/collecting-batches.cjs'),q=require('../../src/modules/order-rules/query.cjs'),a=f.add('DISK');let template={id:'sample-template',version:1,subject:'通知',text:'{{订单明细}}\n{{存放地址}}',html:'',attachments:[]};f.s.templateResolver=()=>template;
const context={orderRules:f.s},group=c.list(f.s)[0];assert.equal(q.queryBatches(context,{},actor).items[0].id,group.id);assert.equal(q.queryOrders(context,{},actor).items[0].collectingBatches[0].id,group.id);assert.equal(q.orderDetail(context,a.id,actor).batches[0].id,group.id);assert.equal(q.batchDetail(context,group.id,actor).orders[0].id,a.id);
c.save(f.s,group.id,{version:0,context:group.context,subject:'持久编辑',format:'text',body:'持久说明\n{{订单明细}}\n{{存放地址}}'},actor);const db=new RuleStore(f.dir,{clock:()=>new Date('2026-10-26T01:00:00Z')});try{assert.equal(db.all('batch-content-drafts')[0].subject,'持久编辑');}finally{db.close();}
template={...template,version:2};assert.match(c.get(f.s,group.id).error,/已变化/);f.setNow('2026-10-26T03:00:00Z');assert.equal(f.s.prepare('2026-10-26T03:00:00Z','fixture').length,0);assert.match(f.s.all('window-results')[0].error,/已变化/);
});
test('different categories stay separate and missing templates do not hide the entire batch page',t=>{
const f=fixture(t),c=require('../../src/modules/order-rules/collecting-batches.cjs'),a=f.add('CATEGORY-A'),other=structuredClone(a);other.id='second-category-order';other.event.processName='第二流程';other.ruleSnapshot={...other.ruleSnapshot,id:'second-category',categoryId:'second-category',name:'另一分类',scopes:[{processName:'第二流程',nodeName:other.event.nodeName}]};other.categoryId='second-category';f.s.put('orders',other);
assert.equal(c.list(f.s).length,2);f.s.templateResolver=(category)=>{if(category==='second-category')throw Object.assign(Error('隔离模板已停用'),{status:409});return null;};const groups=c.list(f.s);assert.equal(groups.length,2);assert.match(groups.find(b=>b.categoryId==='second-category').error,/模板已停用/);assert(groups.find(b=>b.categoryId==='bs-change').text);
});
test('content can be saved while a member is still preparing its archive without bypassing send prerequisites',t=>{
const f=fixture(t),c=require('../../src/modules/order-rules/collecting-batches.cjs'),a=f.add('ARCHIVING');a.status='preparing';a.archive=null;f.s.put('orders',a);const group=c.list(f.s)[0];assert(group.error);
const saved=c.save(f.s,group.id,{version:0,context:group.context,subject:'提前编辑',format:'text',body:'提前说明\n{{订单明细}}\n{{存放地址}}'},actor);assert.equal(saved.version,1);assert(saved.error);assert.equal(f.s.all('batch-content-drafts').length,1);
f.setNow('2026-10-26T03:00:00Z');assert.equal(f.s.prepare('2026-10-26T03:00:00Z','fixture').length,0);assert.equal(f.s.all('batches').length,0);
});
test('manually admitted backlog uses the same current-window eligibility as the freeze operation',t=>{
const f=fixture(t),c=require('../../src/modules/order-rules/collecting-batches.cjs'),a=f.add('ADMITTED'),row=a.sample,keys=['source','portalSource','taskId','instanceId','revision','processName','nodeName','processVersion','receivedAt'],snapshot=Object.fromEntries(keys.filter(k=>Object.hasOwn(row,k)).map(k=>[k,row[k]])),snapshotHash=crypto.createHash('sha256').update(JSON.stringify(Object.fromEntries(Object.keys(snapshot).sort().map(k=>[k,snapshot[k]])))).digest('hex');
f.s.put('restricted-test',{id:'main',value:{id:'admitted-run',enabled:true,rules:[],currentBacklog:[{snapshot,snapshotHash,testRunId:'admitted-run',admittedAt:'2026-10-26T01:00:00Z'}]}});f.setNow('2026-10-26T08:00:00Z');
const window=require('../../src/modules/order-rules/window.cjs').upcomingWindow(f.s.clock(),f.s.schedule(),f.s.calendar());assert.equal(require('../../src/modules/order-rules/restricted-test.cjs').orderInWindow(f.s,a,window),true);assert.equal(c.list(f.s)[0]?.orderIds[0],a.id);
});