feat: add guarded order workflow state

This commit is contained in:
abaishu0730 committed 2026-10-22 11:34:59 +08:00
1 parent 9854d2d5c2
commit 6e795a99b7
8 files changed
+250 -5

No files matched your search

+3 -1
View File
@@ -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') {
+29
View File
@@ -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};
+17
View File
@@ -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};
+83
View File
@@ -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};
+8 -4
View File
@@ -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));