diff --git a/src/dashboard.cjs b/src/dashboard.cjs index d17bbc0..9e1844f 100644 --- a/src/dashboard.cjs +++ b/src/dashboard.cjs @@ -6,6 +6,7 @@ const {mailApi}=require('./mail-api.cjs'); const {bpmScanApi}=require('./bpm-scan-api.cjs'); const {storageApi}=require('./storage-api.cjs'); const {notificationApi}=require('./notification-api.cjs'); +const {orderWorkflowApi}=require('./order-workflow-api.cjs'); const {assistantApi}=require('./assistant-api.cjs'); const {respondToPing}=require('./service-ping.cjs'); const {previewAsset,PREVIEW_CSP}=require('./storage-preview-assets.cjs'); @@ -13,7 +14,7 @@ const {SessionStore,SESSION_MS}=require('./dashboard-sessions.cjs'); const isLoopback=address=>['127.0.0.1','::1','::ffff:127.0.0.1'].includes(address); const publicJob=({path:ignored,...job})=>({...job,downloadable:job.status==='success'}); -function createDashboard({store,outputDir,workspace,previewUserId,bpmSessions,mail,scanner,storage,notifications,assistant,health,watchdog,trustedProxy=false}) { +function createDashboard({store,outputDir,workspace,previewUserId,bpmSessions,mail,scanner,storage,notifications,workflow,assistant,health,watchdog,trustedProxy=false}) { const sessions=new SessionStore(path.dirname(store.file));const failures=new Map(); const sessionCookieName=previewUserId?'order_preview_session':'order_session'; const sessionCookiePattern=new RegExp('(?:^|;\\s*)'+sessionCookieName+'=([a-f0-9]{64})(?:;|$)'); @@ -103,6 +104,7 @@ function createDashboard({store,outputDir,workspace,previewUserId,bpmSessions,ma if(await bpmScanApi({scanner,workspace,user,sessionId:token,url,route,method:request.method,body,reply}))return; if(await storageApi({storage,workspace,user,url,route,method:request.method,body,request,response,reply,trustedProxy}))return; if(await notificationApi({notifications,workspace,user,route,method:request.method,body,reply}))return; + if(await orderWorkflowApi({workflow,user,route,method:request.method,body,reply}))return; if(await assistantApi({assistant,workspace,user,sessionId:token,route,method:request.method,body,request,reply,trustedProxy}))return; if(workspaceApi({workspace,store,user,route,method:request.method,body,reply,bpmSessions}))return; if(route==='/api/overview' && request.method==='GET') { diff --git a/src/order-workflow-api.cjs b/src/order-workflow-api.cjs new file mode 100644 index 0000000..d2cf179 --- /dev/null +++ b/src/order-workflow-api.cjs @@ -0,0 +1,29 @@ +'use strict'; +const fail=(message,status=400)=>{throw Object.assign(new Error(message),{status});}; +const keys=(body,allowed)=>{if(!body||typeof body!=='object'||Object.keys(body).some(key=>!allowed.includes(key)))fail('订单流程参数无效。');}; +async function orderWorkflowApi({workflow,user,route,method,body,reply}){ + if(!route.startsWith('/api/order-workflow'))return false; + if(!workflow)fail('订单流程服务未启动。',503); + if(route==='/api/order-workflow'&&method==='GET'){reply(200,{orders:workflow.listOrders(),batches:workflow.listBatches()});return true;} + if(user?.role==='viewer')fail('只读成员不能操作订单流程。',403); + if(method!=='POST')fail('没有找到此订单流程操作。',404); + if(route==='/api/order-workflow/identify'){ + keys(body,['provenance','arrival','detail','mapping','rule']);if(body.provenance!=='bpm-readonly')fail('订单详情必须来自授权 BPM 只读采集。',409); + const result=workflow.identify(body);reply(200,result);return true; + } + const step=/^\/api\/order-workflow\/orders\/([^/]+)\/(start|detail-ready|pdf-success|pdf-error|archive-success|archive-error|notification)$/.exec(route); + if(step){const id=decodeURIComponent(step[1]);const action=step[2];let result; + if(action==='start'){keys(body,[]);result=workflow.start(id);} + else if(action==='detail-ready'){keys(body,['evidence']);result=workflow.markDetailReady(id,body.evidence||{});} + else if(action==='pdf-success'){keys(body,['jobId']);result=workflow.markPdfSuccess(id,{jobId:body.jobId});} + else if(action==='pdf-error'){keys(body,['message']);result=workflow.markPdfError(id,body.message);} + else if(action==='archive-success'){keys(body,['archiveId','path']);result=workflow.markArchiveSuccess(id,{archiveId:body.archiveId,path:body.path});} + else if(action==='archive-error'){keys(body,['message']);result=workflow.markArchiveError(id,body.message);} + else {keys(body,['productLine','brief','subject','occurredAt']);result=workflow.createNotification(id,body);} + reply(200,result);return true; + } + const batch=/^\/api\/order-workflow\/batches\/([^/]+)\/(freeze|unknown|retry)$/.exec(route); + if(batch){const id=decodeURIComponent(batch[1]);if(batch[2]==='freeze'){keys(body,['cutoff','mode','groups']);reply(200,workflow.freezeBatch(body.cutoff,{mode:body.mode,groups:body.groups}));return true;}if(batch[2]==='unknown'){keys(body,['message']);reply(200,workflow.markBatchUnknown(id,body.message));return true;}if(!workflow.canAutoRetry(id))fail('结果不明批次必须先人工核验,不能自动重发。',409);reply(200,{ok:true});return true;} + fail('没有找到此订单流程操作。',404); +} +module.exports={orderWorkflowApi}; diff --git a/src/order-workflow-store.cjs b/src/order-workflow-store.cjs new file mode 100644 index 0000000..c7d8eb8 --- /dev/null +++ b/src/order-workflow-store.cjs @@ -0,0 +1,17 @@ +'use strict'; +const fs=require('node:fs');const path=require('node:path');const {DatabaseSync}=require('node:sqlite');const {BpmVault}=require('./bpm-vault.cjs'); +const fail=(message,status=409)=>Object.assign(new Error(message),{status}); +class OrderWorkflowStore{ + constructor(dir){this.dir=path.resolve(dir);fs.mkdirSync(this.dir,{recursive:true});this.vault=new BpmVault({stateDir:path.join(this.dir,'secrets')});this.db=new DatabaseSync(path.join(this.dir,'workflow.sqlite'));this.db.exec(`PRAGMA journal_mode=WAL; PRAGMA busy_timeout=5000; PRAGMA secure_delete=ON; + CREATE TABLE IF NOT EXISTS orders(version_key TEXT PRIMARY KEY,order_no TEXT NOT NULL,status TEXT NOT NULL,payload BLOB NOT NULL,updated_at TEXT NOT NULL); + CREATE TABLE IF NOT EXISTS batches(id TEXT PRIMARY KEY,status TEXT NOT NULL,payload BLOB NOT NULL,updated_at TEXT NOT NULL);`);for(const row of this.db.prepare("SELECT id,payload FROM batches WHERE status='sending'").all()){const batch=this.vault.decode('batch:'+row.id,row.payload);batch.status='unknown';batch.error='服务重启,发送结果需要核实。';this.putBatch(batch);}} + now(){return new Date().toISOString();} + putOrder(order){if(!order||typeof order.versionKey!=='string'||!order.versionKey)throw fail('订单版本键无效。',400);const value=structuredClone({...order,updatedAt:order.updatedAt||this.now()});this.db.prepare('INSERT INTO orders(version_key,order_no,status,payload,updated_at) VALUES(?,?,?,?,?) ON CONFLICT(version_key) DO UPDATE SET order_no=excluded.order_no,status=excluded.status,payload=excluded.payload,updated_at=excluded.updated_at').run(value.versionKey,String(value.orderNo||''),String(value.status||'unknown'),this.vault.encode('order:'+value.versionKey,value),value.updatedAt);return value;} + getOrder(versionKey){const row=this.db.prepare('SELECT version_key,payload FROM orders WHERE version_key=?').get(versionKey);return row?this.vault.decode('order:'+row.version_key,row.payload):null;} + orders(){return this.db.prepare('SELECT version_key,payload FROM orders ORDER BY updated_at DESC').all().map(row=>this.vault.decode('order:'+row.version_key,row.payload));} + putBatch(batch){if(!batch||typeof batch.id!=='string'||!batch.id)throw fail('批次标识无效。',400);const value=structuredClone({...batch,updatedAt:batch.updatedAt||this.now()});this.db.prepare('INSERT INTO batches(id,status,payload,updated_at) VALUES(?,?,?,?) ON CONFLICT(id) DO UPDATE SET status=excluded.status,payload=excluded.payload,updated_at=excluded.updated_at').run(value.id,String(value.status||'unknown'),this.vault.encode('batch:'+value.id,value),value.updatedAt);return value;} + getBatch(id){const row=this.db.prepare('SELECT id,payload FROM batches WHERE id=?').get(id);return row?this.vault.decode('batch:'+row.id,row.payload):null;} + batches(){return this.db.prepare('SELECT id,payload FROM batches ORDER BY updated_at DESC').all().map(row=>this.vault.decode('batch:'+row.id,row.payload));} + close(){this.db.close();this.vault.destroy();} +} +module.exports={OrderWorkflowStore}; diff --git a/src/order-workflow.cjs b/src/order-workflow.cjs new file mode 100644 index 0000000..868cf05 --- /dev/null +++ b/src/order-workflow.cjs @@ -0,0 +1,83 @@ +'use strict'; + +const crypto=require('node:crypto'); + +class OrderWorkflowError extends Error{ + constructor(code,message){super(message);this.name='OrderWorkflowError';this.code=code;this.status=409;} +} + +const clone=value=>structuredClone(value); +const hash=value=>crypto.createHash('sha256').update(String(value)).digest('hex'); +const present=value=>value!==undefined&&value!==null&&(typeof value!=='string'||value.trim()!==''); + +function readCandidate(fields,path){ + const paths=Array.isArray(path)?path:[path]; + if(!paths.length||paths.some(p=>typeof p!=='string'||!p.trim()))throw new OrderWorkflowError('MISSING_FIELD','字段映射路径不能为空。'); + const values=paths.map(item=>({path:item,value:fields?.[item]})).filter(item=>present(item.value)); + if(!values.length)throw new OrderWorkflowError('MISSING_FIELD','缺少字段:'+paths.join('、')); + const distinct=new Map(values.map(item=>[JSON.stringify(item.value),item])); + if(distinct.size>1)throw new OrderWorkflowError('AMBIGUOUS_FIELD','字段存在多个不同候选值:'+paths.join('、')); + return values[0]; +} + +function exactRule(arrival,detail,rule){ + if(!rule||rule.enabled!==true)throw new OrderWorkflowError('RULE_BLOCKED','订单规则未启用。'); + if(rule.processName!==arrival.processName||rule.processName!==detail.processName&&detail.processName!==undefined)throw new OrderWorkflowError('PROCESS_CONFLICT','流程名称与已确认规则不一致。'); + if(rule.processVersion&&String(rule.processVersion)!==String(detail.processVersion))throw new OrderWorkflowError('FORM_VERSION_CONFLICT','表单版本与已确认规则不一致。'); + if(rule.nodeName&&rule.nodeName!==detail.nodeName)throw new OrderWorkflowError('NODE_CONFLICT','当前节点与已确认规则不一致。'); +} + +class OrderWorkflow{ + constructor({clock=()=>new Date(),schedule={times:['11:00','17:00'],timezone:'Asia/Shanghai'},store=null}={}){this.clock=clock;this.schedule=schedule;this.store=store;this.orders=new Map((store?.orders?.()||[]).map(order=>[order.versionKey,order]));this.batches=new Map((store?.batches?.()||[]).map(batch=>[batch.id,batch]));} + persistOrder(order){this.store?.putOrder?.(order);} + persistBatch(batch){this.store?.putBatch?.(batch);} + identify({arrival,detail,mapping,rule}){ + if(!arrival?.source||!arrival.taskId)throw new OrderWorkflowError('SOURCE_ID_MISSING','缺少 BPM 来源和任务号。'); + if(!detail||typeof detail.fields!=='object')throw new OrderWorkflowError('DETAIL_MISSING','缺少订单详情字段。'); + exactRule(arrival,detail,rule); + const orderNo=readCandidate(detail.fields,mapping.orderNo),serialNo=readCandidate(detail.fields,mapping.serialNo); + const productCode=readCandidate(detail.fields,mapping.productCode),modelFull=readCandidate(detail.fields,mapping.modelFull); + const modelShort=readCandidate(detail.fields,mapping.modelShort),customer=readCandidate(detail.fields,mapping.customer); + const brief=readCandidate(detail.fields,mapping.brief); + const productLine=Object.hasOwn(mapping,'productLine')?readCandidate(detail.fields,mapping.productLine):rule.productLinePath?readCandidate(detail.fields,rule.productLinePath):null; + if(!detail.processInstanceId)throw new OrderWorkflowError('VERSION_MISSING','缺少流程实例或业务版本标识。'); + const version=String(detail.businessVersion||detail.processInstanceId); + const versionKey=hash([arrival.source,arrival.taskId,detail.processInstanceId,version].join('\0')); + const order={ + id:hash([arrival.source,orderNo.value].join('\0')),versionKey,orderNo: String(orderNo.value).trim(),version, + source:arrival.source,taskId:String(arrival.taskId),processName:arrival.processName,processVersion:String(detail.processVersion||''), + nodeName:detail.nodeName||arrival.activityName||'',serialNo:String(serialNo.value),productCode:String(productCode.value), + modelFull:String(modelFull.value),modelShort:String(modelShort.value),customer:String(customer.value), + productLine:productLine?String(productLine.value):null,brief:String(brief.value),subject:String(detail.subject||arrival.subject||''), + businessTime:detail.businessTime||null,sourceRevision:detail.sourceRevision||detail.processInstanceId, + sources:{orderNo,serialNo,productCode,modelFull,modelShort,customer,brief,...(productLine?{productLine}:{})}, + ruleId:rule.id,status:'identified',createdAt:this.clock().toISOString(),updatedAt:this.clock().toISOString(), + }; + const existing=this.orders.get(versionKey);if(existing)return {status:'duplicate',order:clone(existing)}; + this.orders.set(versionKey,order);this.persistOrder(order);return {status:'matched',order:clone(order)}; + } + get(versionKey){const order=this.orders.get(versionKey);return order?clone(order):null;} + listOrders(){return [...this.orders.values()].map(clone);} + update(versionKey,work){const order=this.orders.get(versionKey);if(!order)throw new OrderWorkflowError('ORDER_NOT_FOUND','订单版本不存在。');const result=work(order);order.updatedAt=this.clock().toISOString();this.persistOrder(order);return result||clone(order);} + transition(versionKey,from,to){return this.update(versionKey,order=>{if(order.status!==from)throw new OrderWorkflowError('INVALID_STATE',`订单状态 ${order.status} 不能转为 ${to}。`);order.status=to;});} + start(versionKey){return this.update(versionKey,order=>{if(!['identified','detail_error','pdf_error','archive_error'].includes(order.status))throw new OrderWorkflowError('INVALID_STATE','当前订单不能开始处理。');order.status='detail_capturing';});} + markDetailReady(versionKey,detailEvidence={}){return this.update(versionKey,order=>{if(order.status!=='detail_capturing')throw new OrderWorkflowError('INVALID_STATE','详情尚未处于采集状态。');order.detailEvidence=clone(detailEvidence);order.status='detail_ready';});} + markPdfSuccess(versionKey,pdf){return this.update(versionKey,order=>{if(order.status!=='detail_ready')throw new OrderWorkflowError('INVALID_STATE','详情未准备好,不能记录 PDF。');if(!pdf?.jobId)throw new OrderWorkflowError('PDF_EVIDENCE_MISSING','缺少 PDF 任务证据。');order.pdf=clone(pdf);order.status='pdf_success';});} + markPdfError(versionKey,message){return this.update(versionKey,order=>{if(!['detail_ready','pdf_pending','detail_capturing'].includes(order.status))throw new OrderWorkflowError('INVALID_STATE','当前状态不能记录 PDF 失败。');order.error=String(message);order.status='pdf_error';});} + markArchiveSuccess(versionKey,archive){return this.update(versionKey,order=>{if(order.status!=='pdf_success')throw new OrderWorkflowError('INVALID_STATE','PDF 未成功,不能记录归档。');if(!archive?.archiveId)throw new OrderWorkflowError('ARCHIVE_EVIDENCE_MISSING','缺少 SMB 归档回执。');order.archive=clone(archive);order.status='archived';});} + markArchiveError(versionKey,message){return this.update(versionKey,order=>{if(order.status!=='pdf_success')throw new OrderWorkflowError('INVALID_STATE','当前状态不能记录归档失败。');order.error=String(message);order.status='archive_error';});} + createNotification(versionKey,input){return this.update(versionKey,order=>{if(order.status!=='archived')throw new OrderWorkflowError('ARCHIVE_REQUIRED','归档未成功,不能创建通知事件。');for(const key of ['productLine','brief','subject','occurredAt'])if(!present(input?.[key]))throw new OrderWorkflowError('NOTIFICATION_FIELD_MISSING','通知字段未确认:'+key);order.notification={...clone(input),orderVersionKey:versionKey,createdAt:this.clock().toISOString(),status:'pending'};order.status='notification_pending';});} + freezeBatch(cutoff,{mode='product_line',groups={}}={}){ + const candidates=[...this.orders.values()].filter(order=>order.status==='notification_pending'&&order.notification?.status==='pending'); + const grouped=new Map();for(const order of candidates){const key=mode==='order'?order.versionKey:order.notification.productLine;const group=groups[order.notification.productLine];if(!group?.to?.length){order.notification.status='blocked';order.notification.error='产业/产品线没有已确认的收件组。';order.status='blocked';continue;}if(!grouped.has(key))grouped.set(key,{group,orders:[]});grouped.get(key).orders.push(order);} + const [key,selected]=grouped.entries().next().value||[];if(!selected)throw new OrderWorkflowError('EMPTY_BATCH','当前发送窗口没有待发通知。'); + const batch={id:crypto.randomUUID(),status:'prepared',cutoff,mode,productLine:key,to:[...selected.group.to],cc:[...(selected.group.cc||[])],orderVersionKeys:selected.orders.map(order=>order.versionKey),subject:selected.orders.map(order=>order.notification.subject).join('、'),text:selected.orders.map(order=>order.notification.brief).join('\n\n'),attachments:[]}; + this.batches.set(batch.id,batch);this.persistBatch(batch);for(const order of selected.orders){order.notification.status='reserved';order.notification.batchId=batch.id;order.status='batched';this.persistOrder(order);}return clone(batch); + } + getBatch(id){const batch=this.batches.get(id);return batch?clone(batch):null;} + listBatches(){return [...this.batches.values()].map(clone);} + markBatchUnknown(id,message){const batch=this.batches.get(id);if(!batch)throw new OrderWorkflowError('BATCH_NOT_FOUND','批次不存在。');batch.status='unknown';batch.error=String(message);this.persistBatch(batch);return clone(batch);} + canAutoRetry(id){const batch=this.batches.get(id);return !!batch&&batch.status==='failed';} +} + +module.exports={OrderWorkflow,OrderWorkflowError}; diff --git a/src/server.cjs b/src/server.cjs index a983072..24e5d3d 100644 --- a/src/server.cjs +++ b/src/server.cjs @@ -21,6 +21,8 @@ const { respondToPing } = require('./service-ping.cjs'); const { StorageStore } = require('./storage-store.cjs'); const { StorageService } = require('./storage-service.cjs'); const { NotificationStore, NotificationService } = require('./notifications.cjs'); +const { OrderWorkflowStore } = require('./order-workflow-store.cjs'); +const { OrderWorkflow } = require('./order-workflow.cjs'); function createServer(options) { let busy = false; @@ -116,23 +118,24 @@ async function main(options = {}) { const custodian=new BpmCustodian({workspace,manager:bpmSessions}); let server; let dashboard; - let mailStore,mail,scanStore,scanner,storageStore,storage,notificationStore,notifications,assistantStore,assistant,health; + let mailStore,mail,scanStore,scanner,storageStore,storage,notificationStore,notifications,workflowStore,workflow,assistantStore,assistant,health; try { mailStore=new MailStore(path.join(stateDir,'mail'));mail=new MailService({store:mailStore}); mailStore.migrateLegacy(store.settings().templates); scanStore=new BpmScanStore(path.join(stateDir,'bpm-scan'));scanner=new BpmScanner({store:scanStore,workspace,manager:bpmSessions,settings:()=>store.settings()}); storageStore=new StorageStore(path.join(stateDir,'storage'));storage=new StorageService({store:storageStore,jobs:store,outputDir}); notificationStore=new NotificationStore(path.join(stateDir,'notifications'));notifications=new NotificationService({store:notificationStore,mail,settings:()=>store.settings(),calendar:()=>workspace.meta('calendar').overrides}); + workflowStore=new OrderWorkflowStore(path.join(stateDir,'order-workflow'));workflow=new OrderWorkflow({store:workflowStore,schedule:store.settings().schedule}); assistantStore=new AssistantStore(path.join(stateDir,'assistant'));assistantStore.recover();assistant=new AssistantService({store:assistantStore,runtime:new ZcodeRuntime({stateDir:path.join(stateDir,'assistant','runtime')}),dashboard:store,workspace,scanner,storage}); health=new RuntimeHealth({stateDir,startedAt,instanceId:watchdog.instanceId,workspace,scanner,storage,mail}); await bpmSessions.migrateAccounts(workspace.snapshot().connections); workspace.markSessionChecksPending(); server=await startService({token,port,outputDir,scale:config.scale,installedExtension,extensionSourceDir:path.join(root,'extension'),store,storage,watchdog}); - dashboard=createDashboard({store,workspace,outputDir,bpmSessions,mail,scanner,storage,notifications,assistant,health,watchdog,trustedProxy:dashboardConfig.trustedProxy===true}); + dashboard=createDashboard({store,workspace,outputDir,bpmSessions,mail,scanner,storage,notifications,workflow,assistant,health,watchdog,trustedProxy:dashboardConfig.trustedProxy===true}); await new Promise((resolve,reject)=>{dashboard.once('error',reject);dashboard.listen(dashboardPort,dashboardHost,resolve);});store.recoverJobs();mailStore.recoverSends();custodian.start();mail.start();scanner.start();notifications.start(); health.start(); } - catch(error){health?.close();if(server?.listening)await new Promise(resolve=>server.close(resolve));if(dashboard?.listening)await new Promise(resolve=>dashboard.close(resolve));await assistant?.stop();assistantStore?.close();await notifications?.stop();notificationStore?.close();await storage?.stop();storageStore?.close();await scanner?.stop();scanStore?.close();await mail?.stop();mailStore?.close();await bpmSessions.shutdown();workspace.close();throw error;} + catch(error){health?.close();if(server?.listening)await new Promise(resolve=>server.close(resolve));if(dashboard?.listening)await new Promise(resolve=>dashboard.close(resolve));await assistant?.stop();assistantStore?.close();await notifications?.stop();notificationStore?.close();workflowStore?.close();await storage?.stop();storageStore?.close();await scanner?.stop();scanStore?.close();await mail?.stop();mailStore?.close();await bpmSessions.shutdown();workspace.close();throw error;} if(!options.quiet){ console.log('订单通知中心已启动。\nWeb 工作台支持业务日历、异常待办与转交、BPM 连接管理。\n在 Chrome 订单页仍可点击扩展中的“导出当前订单”。'); console.log(`首次使用:Chrome 扩展管理 → 开发者模式 → 加载已解压的扩展程序\n选择目录:${installedExtension}\n输出目录:${outputDir}\n本地服务:http://127.0.0.1:${port}`); @@ -149,9 +152,10 @@ async function main(options = {}) { scanStore.close(); storageStore.close(); notificationStore.close(); + workflowStore.close(); assistantStore.close(); })(); - return {server,dashboard,workspace,bpmSessions,custodian,mail,scanner,storage,notifications,assistant,health,stop}; + return {server,dashboard,workspace,bpmSessions,custodian,mail,scanner,storage,notifications,workflow,assistant,health,stop}; } if (require.main === module) main().then(app=>{ const stop=()=>app.stop().then(()=>process.exit(0),()=>process.exit(1)); diff --git a/tests/order-workflow-api.test.cjs b/tests/order-workflow-api.test.cjs new file mode 100644 index 0000000..63ea754 --- /dev/null +++ b/tests/order-workflow-api.test.cjs @@ -0,0 +1,15 @@ +'use strict'; +const test=require('node:test');const assert=require('node:assert/strict'); +const {orderWorkflowApi}=require('../src/order-workflow-api.cjs'); +function call({user={username:'operator',role:'operator'},route,method='POST',body}){let result;return {run:()=>orderWorkflowApi({workflow:{orders:()=>[],batches:()=>[],identify:()=>({status:'matched',order:{versionKey:'v1',status:'identified'}}),start:()=>{},markDetailReady:()=>{},markPdfSuccess:()=>{},markArchiveSuccess:()=>{},createNotification:()=>{},freezeBatch:()=>({id:'b1',status:'prepared'}),get:()=>({versionKey:'v1',status:'identified'}),getBatch:()=>({id:'b1',status:'unknown'}),markBatchUnknown:()=>({id:'b1',status:'unknown'}),canAutoRetry:()=>false},user,route,method,body,reply:(status,value)=>{result={status,value};}}),get:()=>result};} +test('workflow API keeps BPM source provenance explicit and prevents viewer writes',async()=>{ + const input={provenance:'bpm-readonly',arrival:{source:'portal-v4',taskId:'task'},detail:{fields:{},processInstanceId:'i'},mapping:{},rule:{}}; + const denied=call({user:{username:'viewer',role:'viewer'},route:'/api/order-workflow/identify',body:input});await assert.rejects(denied.run(),e=>e.status===403); + const accepted=call({route:'/api/order-workflow/identify',body:input});await accepted.run();assert.equal(accepted.get().status,200);assert.equal(accepted.get().value.status,'matched'); + const forged=call({route:'/api/order-workflow/identify',body:{...input,provenance:'client'} });await assert.rejects(forged.run(),e=>e.status===409); +}); +test('workflow API exposes independent step actions and blocks automatic retry of unknown batch',async()=>{ + const step=call({route:'/api/order-workflow/orders/v1/start',body:{}});await step.run();assert.equal(step.get().status,200); + const unknown=call({route:'/api/order-workflow/batches/b1/unknown',body:{message:'SMTP connection lost'}});await unknown.run();assert.equal(unknown.get().value.status,'unknown'); + const retry=call({route:'/api/order-workflow/batches/b1/retry',body:{}});await assert.rejects(retry.run(),e=>e.status===409); +}); diff --git a/tests/order-workflow-store.test.cjs b/tests/order-workflow-store.test.cjs new file mode 100644 index 0000000..3f413c6 --- /dev/null +++ b/tests/order-workflow-store.test.cjs @@ -0,0 +1,13 @@ +'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 {OrderWorkflowStore}=require('../src/order-workflow-store.cjs'); +test('workflow store persists order versions, step evidence and batches across restart',t=>{ + const dir=fs.mkdtempSync(path.join(os.tmpdir(),'order-workflow-store-'));let store=new OrderWorkflowStore(dir);t.after(()=>{store.close();fs.rmSync(dir,{recursive:true,force:true});}); + store.putOrder({versionKey:'v1',orderNo:'ORD-1',status:'archive_error',steps:{detail:{status:'success'},pdf:{status:'success'},archive:{status:'error',error:'SMB unavailable'}}}); + store.putBatch({id:'b1',status:'unknown',orderVersionKeys:['v1'],to:['test@example.test'],cc:[]}); + store.close();store=new OrderWorkflowStore(dir);assert.equal(store.getOrder('v1').status,'archive_error');assert.equal(store.getOrder('v1').steps.archive.error,'SMB unavailable');assert.equal(store.getBatch('b1').status,'unknown');assert.deepEqual(store.getBatch('b1').orderVersionKeys,['v1']); +}); +test('workflow store restart converts sending batch to unknown without replaying it',t=>{ + const dir=fs.mkdtempSync(path.join(os.tmpdir(),'order-workflow-restart-'));let store=new OrderWorkflowStore(dir);t.after(()=>{store.close();fs.rmSync(dir,{recursive:true,force:true});}); + store.putBatch({id:'b1',status:'sending',orderVersionKeys:['v1'],to:['test@example.test'],cc:[]});store.close();store=new OrderWorkflowStore(dir);assert.equal(store.getBatch('b1').status,'unknown');assert.equal(store.getBatch('b1').error,'服务重启,发送结果需要核实。'); +}); diff --git a/tests/order-workflow.test.cjs b/tests/order-workflow.test.cjs new file mode 100644 index 0000000..1716e52 --- /dev/null +++ b/tests/order-workflow.test.cjs @@ -0,0 +1,82 @@ +'use strict'; +const test=require('node:test'); +const assert=require('node:assert/strict'); +const {OrderWorkflow,OrderWorkflowError}=require('../src/order-workflow.cjs'); + +const baseArrival={ + source:'portal-v4',taskId:'task-315288',processName:'海外运营订单更改评审',activityName:'订单专员(订单通知书)', + arrivedAt:'2026-10-15T08:33:58.000Z',arrivalDay:'2026-10-15',subject:'脱敏订单标题', +}; +const baseDetail={ + processInstanceId:'instance-315288',processVersion:'V7',nodeName:'订单专员(订单通知书)', + fields:{ + 'OFR_WY_Applicant.OrderNum':'ORD-REDACTED', + 'OFR_WY_Applicant.SN':'SERIAL-REDACTED', + 'OFR_WY_BInfo.ProductNum':'PRODUCT-REDACTED', + 'OFR_WY_BInfo.ProductModel':'MODEL-FULL-REDACTED', + 'OFR_WY_BInfo.ProductModelNEW':'MODEL-SHORT-REDACTED', + 'OFR_WY_BInfo.CustomerName':'CUSTOMER-REDACTED', + 'OFR_WY_Applicant.OrderChangeContent':'内部备机数量发生更改', + }, + brief:'内部备机数量发生更改',subject:'海外运营订单更改通知书',businessTime:'2026-10-10T05:55:54.000Z', +}; +const mapping={ + orderNo:'OFR_WY_Applicant.OrderNum',serialNo:'OFR_WY_Applicant.SN',productCode:'OFR_WY_BInfo.ProductNum', + modelFull:'OFR_WY_BInfo.ProductModel',modelShort:'OFR_WY_BInfo.ProductModelNEW',customer:'OFR_WY_BInfo.CustomerName', + brief:'OFR_WY_Applicant.OrderChangeContent', +}; +const rule={id:'overseas-change-v7',processName:'海外运营订单更改评审',processVersion:'V7',nodeName:'订单专员(订单通知书)', + productLinePath:'OFR_WY_BInfo.ProductNum',notificationType:'change',enabled:true}; + +test('real-order mapping requires explicit paths and keeps source evidence',()=>{ + const workflow=new OrderWorkflow({clock:()=>new Date('2026-10-22T01:00:00Z')}); + const result=workflow.identify({arrival:baseArrival,detail:baseDetail,mapping,rule}); + assert.equal(result.status,'matched'); + assert.equal(result.order.orderNo,'ORD-REDACTED'); + assert.equal(result.order.version,'instance-315288'); + assert.equal(result.order.productLine,'PRODUCT-REDACTED'); + assert.equal(result.order.brief,baseDetail.brief); + assert.equal(result.order.sources.orderNo.path,mapping.orderNo); + assert.equal(result.order.sources.brief.path,mapping.brief); +}); + +test('missing or conflicting explicit fields block identification without guessing',()=>{ + const workflow=new OrderWorkflow(); + const missing={...baseDetail,fields:{...baseDetail.fields}};delete missing.fields[mapping.orderNo]; + assert.throws(()=>workflow.identify({arrival:baseArrival,detail:missing,mapping,rule}),e=>e.code==='MISSING_FIELD'); + const conflicting={...baseDetail,fields:{...baseDetail.fields,otherOrder:'DIFFERENT'}}; + assert.throws(()=>workflow.identify({arrival:baseArrival,detail:conflicting,mapping:{...mapping,orderNo:['OFR_WY_Applicant.OrderNum','otherOrder']},rule}),e=>e.code==='AMBIGUOUS_FIELD'); + assert.throws(()=>workflow.identify({arrival:baseArrival,detail:baseDetail,mapping:{...mapping,productLine:''},rule}),e=>e.code==='MISSING_FIELD'); +}); + +test('order version is idempotent and changed BPM revision creates a new version',()=>{ + const workflow=new OrderWorkflow(); + const first=workflow.identify({arrival:baseArrival,detail:baseDetail,mapping,rule}).order; + const same=workflow.identify({arrival:{...baseArrival,subject:'different list title'},detail:baseDetail,mapping,rule}).order; + assert.equal(first.versionKey,same.versionKey); + const changed=workflow.identify({arrival:{...baseArrival,taskId:'task-315288-r2'},detail:{...baseDetail,processInstanceId:'instance-315288-r2'},mapping,rule}).order; + assert.notEqual(first.versionKey,changed.versionKey); + assert.equal(first.orderNo,changed.orderNo); +}); + +test('state transitions keep PDF archive and notification independent and block mail when archive fails',()=>{ + const workflow=new OrderWorkflow(); + const order=workflow.identify({arrival:baseArrival,detail:baseDetail,mapping,rule}).order; + workflow.start(order.versionKey);workflow.markDetailReady(order.versionKey);workflow.markPdfSuccess(order.versionKey,{jobId:'pdf-1'});workflow.markArchiveSuccess(order.versionKey,{archiveId:'archive-1',path:'\\\\210\\orders\\ORD-REDACTED\\file.pdf'}); + workflow.createNotification(order.versionKey,{productLine:order.productLine,brief:order.brief,subject:order.subject,occurredAt:order.businessTime}); + assert.equal(workflow.get(order.versionKey).status,'notification_pending'); + const failed=workflow.identify({arrival:{...baseArrival,taskId:'task-failed'},detail:{...baseDetail,processInstanceId:'instance-failed'},mapping,rule}).order; + workflow.start(failed.versionKey);workflow.markDetailReady(failed.versionKey);workflow.markPdfSuccess(failed.versionKey,{jobId:'pdf-2'});workflow.markArchiveError(failed.versionKey,'SMB unavailable'); + assert.throws(()=>workflow.createNotification(failed.versionKey,{productLine:failed.productLine,brief:failed.brief,subject:failed.subject,occurredAt:failed.businessTime}),e=>e.code==='ARCHIVE_REQUIRED'); + assert.equal(workflow.get(failed.versionKey).status,'archive_error'); +}); + +test('batches group only confirmed product lines and unknown sends never auto-retry',()=>{ + const workflow=new OrderWorkflow({schedule:{times:['11:00','17:00'],timezone:'Asia/Shanghai'}}); + const order=workflow.identify({arrival:baseArrival,detail:baseDetail,mapping,rule}).order;workflow.start(order.versionKey);workflow.markDetailReady(order.versionKey);workflow.markPdfSuccess(order.versionKey,{jobId:'pdf'});workflow.markArchiveSuccess(order.versionKey,{archiveId:'a'});workflow.createNotification(order.versionKey,{productLine:'PRODUCT-REDACTED',brief:'正文',subject:'标题',occurredAt:'2026-10-22T00:30:00.000Z'}); + const missing=workflow.identify({arrival:{...baseArrival,taskId:'task-2'},detail:{...baseDetail,processInstanceId:'instance-2'},mapping,rule}).order;workflow.start(missing.versionKey);workflow.markDetailReady(missing.versionKey);workflow.markPdfSuccess(missing.versionKey,{jobId:'pdf2'});workflow.markArchiveSuccess(missing.versionKey,{archiveId:'a2'});workflow.createNotification(missing.versionKey,{productLine:'UNMAPPED',brief:'正文2',subject:'标题2',occurredAt:'2026-10-22T00:30:00.000Z'}); + const batch=workflow.freezeBatch('2026-10-22T03:00:00.000Z',{mode:'product_line',groups:{'PRODUCT-REDACTED':{to:['test@example.test'],cc:[]}}}); + assert.equal(batch.status,'prepared');assert.deepEqual(batch.to,['test@example.test']);assert.equal(batch.orderVersionKeys.length,1); + assert.equal(workflow.get(missing.versionKey).status,'blocked');assert.throws(()=>workflow.freezeBatch('2026-10-22T03:00:00.000Z',{mode:'product_line',groups:{},}),e=>e.code==='EMPTY_BATCH'); + workflow.markBatchUnknown(batch.id,'SMTP connection lost');assert.equal(workflow.getBatch(batch.id).status,'unknown');assert.equal(workflow.canAutoRetry(batch.id),false); +});