93 lines
13 KiB
JavaScript
93 lines
13 KiB
JavaScript
'use strict';
|
|
const test=require('node:test');const assert=require('node:assert/strict');const fs=require('node:fs');const os=require('node:os');const path=require('node:path');
|
|
const {OrderWorkflow}=require('../src/order-workflow.cjs');const {OrderWorkflowStore}=require('../src/order-workflow-store.cjs');
|
|
const {OrderPipeline}=require('../src/order-pipeline.cjs');
|
|
const vault=()=>({encode:(id,value)=>Buffer.from(JSON.stringify(value)),decode:(id,value)=>JSON.parse(Buffer.from(value).toString()),destroy(){}});
|
|
const a={connectionId:'c',source:'portal-v4',taskId:'t',processName:'P',activityName:'N',subject:'原文\n第二行',arrivedAt:'2026-10-22T01:00:00Z',detailUrl:'https://bpm.skyworthdigital.com/YZSoft/Forms/XForm/PV1.aspx?tid=1&pid=2'};
|
|
const d={readOnly:true,tid:'1',pid:'2',businessVersion:'revision-1',processName:'P',nodeName:'N',processVersion:'V1',fields:{no:'000123',sn:'sn',p:'p',m:'m',s:'s',c:'c'},processSteps:[{name:'N',status:'处理中'}]};
|
|
const rule={id:'r',enabled:true,processName:'P',nodeName:'N',productLine:'Line',templateId:'tpl',recipientGroupId:'Line',adapters:{V1:{orderNo:'no',serialNo:'sn',productCode:'p',modelFull:'m',modelShort:'s',customer:'c',brief:{source:'arrival',path:'subject'}}}};
|
|
function fixture(t,{archiveFails=false}={}){
|
|
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'order-pipeline-')),store=new OrderWorkflowStore(dir,{vault:vault()});t.after(()=>{store.close();fs.rmSync(dir,{recursive:true,force:true});});const workflow=new OrderWorkflow({store});const saved=workflow.saveRule(rule),check=workflow.checkRule('r',{arrival:a,detail:d,provenance:'bpm-readonly'});workflow.publishRule('r',{version:saved.version,checkId:check.checkId});
|
|
const calls={detail:0,pdf:0,archive:0,mail:0};const jobsList=[];
|
|
const deps={workflow,store,scanStore:{getArrival:()=>structuredClone(a),recent:()=>[structuredClone(a)]},workspace:{getConnection:()=>({id:'c',status:'connected',owner:'owner'}),record(){}},manager:{captureOrderDetail:async()=>{calls.detail++;return {detail:d,snapshot:{html:'<form><p>PDF</p></form>',styles:[]},capturedAt:'2026-10-22T01:01:00Z'};}},jobs:{jobs:()=>jobsList,recordJob:job=>{const old=jobsList.findIndex(j=>j.jobId===job.jobId);if(old>=0)jobsList.splice(old,1);jobsList.push(job);return job;}},storage:{archive:async()=>{calls.archive++;if(archiveFails&&calls.archive===1)throw Error('SMB offline');return {id:'archive',relativePath:'000123/x.pdf',bytes:7,sha256:'a'.repeat(64)};},store:{settings:()=>({serverId:'server'}),archives:()=>[]}},render:async()=>{calls.pdf++;return {path:path.join(dir,'x.pdf'),filename:'x.pdf',bytes:7};},outputDir:dir,mail:{store:{templates:()=>[{id:'tpl',status:'active',version:1}],template:()=>({id:'tpl',status:'active',version:1,subject:'{{产品线}}',text:'{{订单列表}}',attachments:[]}),channels:()=>[]}},settings:()=>({groups:[{productLine:'Line',to:['2639266652@qq.com'],cc:[]}],schedule:{times:['11:00','17:00'],weekends:true,timezone:'Asia/Shanghai',missed:'next_window'}})};
|
|
const pipeline=new OrderPipeline(deps);return {pipeline,store,workflow,calls};
|
|
}
|
|
test('pipeline remains inert by default and server-owned sample checks cannot send or export',async t=>{
|
|
const f=fixture(t);await f.pipeline.tick();assert.equal(f.calls.detail,0);assert.equal(f.calls.pdf,0);assert.equal(f.pipeline.config().enabled,false);assert.equal(f.pipeline.config().sendEnabled,false);
|
|
await f.pipeline.checkRule('r',{connectionId:'c',source:'portal-v4',taskId:'t'},{user:{username:'owner',role:'admin'},sessionId:'test'});assert.equal(f.calls.detail,1);assert.equal(f.calls.pdf,0);
|
|
});
|
|
test('archive failure creates no notification and retry reuses successful PDF',async t=>{
|
|
const f=fixture(t,{archiveFails:true});await f.pipeline.process(a,{user:{username:'owner',role:'admin'},sessionId:'test'});let order=f.workflow.listOrders()[0];assert.equal(order.status,'archive_error');assert.equal(order.notification,undefined);assert.equal(f.calls.pdf,1);
|
|
await f.pipeline.retry(order.versionKey,{user:{username:'owner',role:'operator'},sessionId:'test'});order=f.workflow.get(order.versionKey);assert.equal(order.status,'notification_pending');assert.equal(f.calls.pdf,1);assert.equal(f.calls.detail,1);assert.equal(f.calls.archive,2);
|
|
});
|
|
test('an authoritative BPM task proceeds without fabricating a missing business revision',async t=>{
|
|
const f=fixture(t);f.pipeline.manager.captureOrderDetail=async()=>({detail:{...d,businessVersion:undefined},snapshot:{html:'<form>真实采集快照</form>',styles:[]}});await f.pipeline.process(a,{user:{username:'owner',role:'admin'},sessionId:'test'});assert.equal(f.workflow.listOrders().length,1);assert.equal(f.workflow.listOrders()[0].businessVersion,null);assert.equal(f.workflow.listOrders()[0].status,'notification_pending');assert.equal(f.calls.pdf,1);
|
|
});
|
|
test('sample URL cannot splice another order into a stored arrival even if flow and node match',async t=>{
|
|
const f=fixture(t);await assert.rejects(()=>f.pipeline.checkRule('r',{connectionId:'c',source:'portal-v4',taskId:'t',detailUrl:a.detailUrl.replace('tid=1','tid=77')},{user:{username:'owner',role:'admin'},sessionId:'s'}),/关联|不一致/);assert.equal(f.calls.detail,0);
|
|
f.pipeline.scanStore.getArrival=()=>({...a,detailUrl:undefined});await assert.rejects(()=>f.pipeline.checkRule('r',{connectionId:'c',source:'portal-v4',taskId:'t',detailUrl:a.detailUrl},{user:{username:'owner',role:'admin'},sessionId:'s'}),/关联|重新扫描/);assert.equal(f.calls.detail,0);
|
|
});
|
|
test('PDF and SMB running state is durable before external calls',async t=>{
|
|
const f=fixture(t);f.pipeline.render=async()=>{assert.equal(f.store.orders()[0].status,'pdf_pending');return {path:'x.pdf',filename:'x.pdf',bytes:7};};f.pipeline.storage.archive=async()=>{assert.equal(f.store.orders()[0].status,'archive_pending');return {id:'a',relativePath:'000123/x.pdf',bytes:7,sha256:'a'.repeat(64)};};
|
|
await f.pipeline.process(a,{user:{username:'owner',role:'admin'},sessionId:'s'});assert.equal(f.workflow.listOrders()[0].status,'notification_pending');
|
|
});
|
|
test('a failed detail candidate can recover after login repair without inventing an order',async t=>{
|
|
const f=fixture(t),capture=f.pipeline.manager.captureOrderDetail;f.pipeline.manager.captureOrderDetail=async()=>{throw Object.assign(Error('需要续登'),{status:401});};await f.pipeline.process(a,{user:{username:'owner',role:'admin'},sessionId:'s'});const candidate=f.pipeline.arrivals()[0];assert.equal(candidate.status,'blocked');
|
|
f.pipeline.manager.captureOrderDetail=capture;await f.pipeline.retryArrival(candidate.id,{user:{username:'owner',role:'operator'},sessionId:'s'});assert.equal(f.workflow.listOrders()[0].status,'notification_pending');
|
|
});
|
|
test('recovery reconstructs an arrival link after a crash between order insert and candidate update',async t=>{
|
|
const f=fixture(t),order=f.workflow.identify({arrival:a,detail:d}).order;f.workflow.start(order.versionKey);f.workflow.markDetailReady(order.versionKey);f.workflow.update(order.versionKey,draft=>{draft.status='interrupted';});
|
|
await f.pipeline.retry(order.versionKey,{user:{username:'owner',role:'admin'},sessionId:'s'});assert.equal(f.workflow.get(order.versionKey).status,'notification_pending');assert.equal(f.calls.pdf,1);assert.equal(f.pipeline.arrivals()[0].orderVersionKey,order.versionKey);
|
|
});
|
|
|
|
test('recovery retains a persisted legacy key while verifying unchanged task fields',async t=>{
|
|
const f=fixture(t),order=f.workflow.identify({arrival:a,detail:d}).order;
|
|
f.workflow.orders.delete(order.versionKey);order.versionKey='legacy-version-key';order.status='interrupted';f.workflow.orders.set(order.versionKey,order);f.store.putOrder(order);
|
|
await f.pipeline.retry(order.versionKey,{user:{username:'owner',role:'admin'},sessionId:'s'});
|
|
assert.equal(f.workflow.get('legacy-version-key').status,'notification_pending');assert.equal(f.calls.pdf,1);assert.equal(f.workflow.listOrders().length,1);
|
|
});
|
|
|
|
test('retry refuses ambiguous legacy tasks even when PDF and archive are already successful',async t=>{
|
|
const f=fixture(t);await f.pipeline.process(a,{user:{username:'owner',role:'admin'},sessionId:'s'});
|
|
const first=f.workflow.listOrders()[0];f.workflow.update(first.versionKey,draft=>{draft.status='notification_error';});
|
|
const duplicate={...structuredClone(first),versionKey:'legacy-second-key'};f.workflow.orders.set(duplicate.versionKey,duplicate);
|
|
await assert.rejects(()=>f.pipeline.retry(first.versionKey,{user:{username:'owner',role:'admin'},sessionId:'s'}),error=>error.code==='TASK_IDENTITY_CONFLICT');
|
|
assert.equal(f.workflow.get(first.versionKey).status,'notification_error');assert.equal(f.calls.pdf,1);assert.equal(f.calls.archive,1);
|
|
});
|
|
test('test recipient guard rejects either a production To or Cc and cannot be disabled by config',t=>{
|
|
const {pipeline}=fixture(t);assert.throws(()=>pipeline.assertRecipients({to:['someone@company.example'],cc:[]}));assert.throws(()=>pipeline.assertRecipients({to:['2639266652@qq.com'],cc:['someone@company.example']}));pipeline.assertRecipients({to:['2639266652@qq.com'],cc:[]});
|
|
assert.throws(()=>pipeline.saveConfig({...pipeline.config(),allowedRecipients:['someone@company.example']}));
|
|
});
|
|
test('reading real notification tasks persists source evidence without exporting or sending',async t=>{
|
|
const f=fixture(t),{BpmScanStore}=require('../src/bpm-scan-store.cjs'),scan=new BpmScanStore(path.join(f.store.dir,'scan'));try{
|
|
f.pipeline.scanStore=scan;f.pipeline.manager.scanOrderTasks=async()=>[{...a,source:'todo-v4',arrivalDay:'2026-10-22',recordKind:'notification-task',tid:'1',pid:'2',processInstanceId:'2',processVersion:'V1'}];
|
|
const result=await f.pipeline.scanSource('c',{user:{username:'owner',role:'operator'},sessionId:'s'});assert.equal(result.added,1);assert.equal(scan.getArrival('c','todo-v4','t').recordKind,'notification-task');assert.equal(f.calls.pdf,0);assert.equal(f.calls.mail,0);
|
|
}finally{scan.close();}
|
|
});
|
|
async function sendingFixture(t,result){
|
|
const f=fixture(t);f.pipeline.clock=()=>new Date('2026-10-22T03:00:00Z');await f.pipeline.process(a,{user:{username:'owner',role:'admin'},sessionId:'test'});
|
|
f.store.setMeta('config',{...f.pipeline.config(),enabled:true,sendEnabled:true,channelId:'mail',since:'2026-10-22T00:00:00Z'});
|
|
f.store.setMeta('schedule',{signature:JSON.stringify([f.pipeline.settings().schedule,[]]),next:'2026-10-22T03:00:00Z'});
|
|
f.pipeline.mail.exclusive=async(id,work)=>work();f.pipeline.mail.store.channelSecret=()=>({id:'mail',version:1,email:'sender@example.test',name:'sender',smtp:{}});f.pipeline.mail.store.guard=()=>{};
|
|
f.pipeline.mail.smtpFactory=()=>({verify:async()=>{},sendMail:async message=>{f.calls.mail++;assert.deepEqual(message.to,['2639266652@qq.com']);assert.deepEqual(message.attachments,[]);assert.match(message.text,/订单号:000123 原文 第二行/);return typeof result==='function'?result(message):result;},close(){}});
|
|
return f;
|
|
}
|
|
test('scheduled sender freezes category template then records accepted result without PDF attachment',async t=>{
|
|
const f=await sendingFixture(t,{accepted:['2639266652@qq.com'],rejected:[]});await f.pipeline.sendDue();assert.equal(f.calls.mail,1);assert.equal(f.workflow.listBatches()[0].status,'sent');assert.equal(f.workflow.listBatches()[0].templateVersion,1);await f.pipeline.sendDue();assert.equal(f.calls.mail,1);
|
|
});
|
|
test('partial rejection and send exceptions become unknown and never auto resend',async t=>{
|
|
for(const result of [{accepted:[],rejected:['2639266652@qq.com']},()=>{throw Error('SMTP lost');}]){
|
|
const f=await sendingFixture(t,result);await f.pipeline.sendDue();assert.equal(f.workflow.listBatches()[0].status,'unknown');f.store.setMeta('schedule',{signature:JSON.stringify([f.pipeline.settings().schedule,[]]),next:'2026-10-22T03:00:00Z'});await f.pipeline.sendDue();assert.equal(f.calls.mail,1);
|
|
}
|
|
});
|
|
test('missed next-window keeps pending notifications rather than sending immediately on restart',async t=>{
|
|
const f=await sendingFixture(t,{accepted:['2639266652@qq.com'],rejected:[]});f.pipeline.clock=()=>new Date('2026-10-22T04:00:00Z');await f.pipeline.sendDue();assert.equal(f.calls.mail,0);assert.equal(f.workflow.listOrders()[0].status,'notification_pending');assert.equal(f.store.meta('schedule').next,'2026-10-22T09:00:00.000Z');
|
|
});
|
|
test('busy mailbox does not consume the due order notification window',async t=>{
|
|
const f=await sendingFixture(t,{accepted:['2639266652@qq.com'],rejected:[]});const exclusive=f.pipeline.mail.exclusive;f.pipeline.mail.exclusive=async()=>{throw Object.assign(Error('busy'),{status:409});};await f.pipeline.sendDue();assert.equal(f.store.meta('schedule').next,'2026-10-22T03:00:00Z');assert.equal(f.calls.mail,0);
|
|
f.pipeline.mail.exclusive=exclusive;await f.pipeline.sendDue();assert.equal(f.calls.mail,1);
|
|
});
|
|
test('skip handles all elapsed send slots across a multi-day shutdown',async t=>{
|
|
const f=await sendingFixture(t,{accepted:['2639266652@qq.com'],rejected:[]});f.pipeline.settings=()=>({groups:[{productLine:'Line',to:['2639266652@qq.com'],cc:[]}],schedule:{times:['11:00','17:00'],weekends:true,timezone:'Asia/Shanghai',missed:'skip'}});f.pipeline.clock=()=>new Date('2026-10-23T04:00:00Z');f.store.setMeta('schedule',{signature:JSON.stringify([f.pipeline.settings().schedule,[]]),next:'2026-10-21T03:00:00Z'});await f.pipeline.sendDue();assert.equal(f.calls.mail,0);assert.equal(f.workflow.listOrders()[0].status,'skipped');
|
|
});
|