feat: process BPM notification tasks with verified readonly forms

This commit is contained in:
abaishu0730 committed 2026-10-22 18:33:52 +08:00
1 parent 94fc985553
commit a9d050d87a
28 files changed
+879 -34

No files matched your search

+13 -8
View File
@@ -54,6 +54,7 @@ class OrderWorkflow{
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]));this.ruleMap=new Map((store?.rules?.()||[]).map(rule=>[rule.id,rule]));
}
persistOrder(order){this.store?.putOrder?.(order);}persistBatch(batch){this.store?.putBatch?.(batch);}
assertUniqueTask(order){if([...this.orders.values()].filter(saved=>saved.source===order.source&&saved.taskId===String(order.taskId)).length>1)throw new OrderWorkflowError('TASK_IDENTITY_CONFLICT','同一 BPM 通知任务存在多个旧版本记录,必须人工核对,不能重复归档或通知。');}
saveRule(rule){
if(!rule||typeof rule.id!=='string'||!rule.id||typeof rule.processName!=='string'||!rule.processName.trim()||typeof rule.nodeName!=='string'||!rule.nodeName.trim()||typeof rule.productLine!=='string'||!rule.productLine.trim()||typeof rule.templateId!=='string'||!rule.templateId.trim()||!rule.adapters||typeof rule.adapters!=='object'||Array.isArray(rule.adapters))throw new OrderWorkflowError('RULE_INVALID','分类规则缺少流程、节点、产品线、模板或版本适配器。');
for(const [version,mapping] of Object.entries(rule.adapters))if(!version.trim()||!mapping||typeof mapping!=='object'||Array.isArray(mapping))throw new OrderWorkflowError('RULE_INVALID','字段适配器版本无效。');
@@ -84,20 +85,23 @@ class OrderWorkflow{
identify(input){
let {arrival,detail,mapping,rule}=input||{};if(!arrival?.source||!present(arrival.taskId))throw new OrderWorkflowError('SOURCE_ID_MISSING','缺少 BPM 来源和任务号。');if(!detail||typeof detail.fields!=='object'||Array.isArray(detail.fields))throw new OrderWorkflowError('DETAIL_MISSING','缺少订单详情字段。');
if(!rule){const resolved=this.resolveRule(arrival,detail);rule=resolved.rule;mapping=resolved.mapping;}else if(!mapping&&rule.adapters?.[String(detail.processVersion||'')])mapping=rule.adapters[String(detail.processVersion)];if(!mapping)throw new OrderWorkflowError('ADAPTER_MISSING','当前表单版本没有字段适配器。');exactRule(arrival,detail,rule);
const mappedVersion=mapping.businessVersion?readCandidate({arrival,detail},mapping.businessVersion,'业务版本'):null;
let mappedVersion=null;if(mapping.businessVersion){try{mappedVersion=readCandidate({arrival,detail},mapping.businessVersion,'业务版本');}catch(error){if(error.code!=='MISSING_FIELD')throw error;}}
const businessVersion=mappedVersion?.value??detail.businessVersion;
if(!present(detail.tid)||!present(detail.pid)||!present(businessVersion)||![detail.tid,detail.pid,businessVersion].every(value=>['string','number'].includes(typeof value)))throw new OrderWorkflowError('VERSION_MISSING','缺少 tid、pid 或明确的业务版本标识。');if(!present(detail.processVersion))throw new OrderWorkflowError('FORM_VERSION_MISSING','缺少表单版本。');
if(!present(detail.tid)||!present(detail.pid)||![detail.tid,detail.pid].every(value=>['string','number'].includes(typeof value)))throw new OrderWorkflowError('VERSION_MISSING','缺少 tid 或 pid 详情标识。');
if(present(businessVersion)&&!['string','number'].includes(typeof businessVersion))throw new OrderWorkflowError('VERSION_MISSING','上游业务版本字段必须是明确文本或数值。');
if(!present(detail.processVersion))throw new OrderWorkflowError('FORM_VERSION_MISSING','缺少表单版本。');
const source={arrival,detail},orderNo=readCandidate(source,mapping.orderNo,'订单号'),serialNo=readCandidate(source,mapping.serialNo,'流水号'),productCode=readCandidate(source,mapping.productCode,'产品编号'),modelFull=readCandidate(source,mapping.modelFull,'完整型号'),modelShort=readCandidate(source,mapping.modelShort,'短型号'),customer=readCandidate(source,mapping.customer,'客户'),brief=readCandidate(source,mapping.brief,'简要说明');
if(!present(rule.productLine))throw new OrderWorkflowError('RULE_INVALID','分类规则必须指定产品线。');
const productLine={path:'rule.productLine',value:rule.productLine},version=String(businessVersion),currentOrderNo=text(orderNo.value),tid=String(detail.tid),pid=String(detail.pid),versionKey=hash(JSON.stringify([tid,pid,currentOrderNo,version]));
const productLine={path:'rule.productLine',value:rule.productLine},reportedVersion=present(businessVersion)?String(businessVersion):null,version=reportedVersion||'bpm-task:'+arrival.source+'/'+arrival.taskId,currentOrderNo=text(orderNo.value),tid=String(detail.tid),pid=String(detail.pid),versionKey=hash(JSON.stringify([arrival.source,String(arrival.taskId)]));
const businessTime=detail.businessTime||arrival.arrivedAt||arrival.receivedAt||null,businessTimeSource=detail.businessTime?'detail.businessTime':businessTime?'list.receivedAt':null;if(!businessTime)throw new OrderWorkflowError('BUSINESS_TIME_MISSING','缺少业务时间和列表收到时间。');const now=this.clock().toISOString();
const order={id:hash([arrival.source,currentOrderNo].join('\0')),versionKey,version,businessVersion:version,tid,pid,orderNo:currentOrderNo,source:arrival.source,taskId:String(arrival.taskId),processName:arrival.processName,processVersion:String(detail.processVersion),nodeName:detail.nodeName||arrival.activityName||'',serialNo:text(serialNo.value),productCode:text(productCode.value),modelFull:text(modelFull.value),modelShort:text(modelShort.value),customer:text(customer.value),productLine:productLine.value,brief:String(brief.value),subject:String(detail.subject||arrival.subject||''),businessTime,businessTimeSource,sourceRevision:detail.sourceRevision||version,sources:{orderNo,serialNo,productCode,modelFull,modelShort,customer,brief,productLine},ruleId:rule.id,templateId:rule.templateId||null,status:'identified',steps:{discovery:{status:'success',source:'bpm-readonly'},detail:{status:'pending'},pdf:{status:'pending'},archive:{status:'pending'},notification:{status:'pending'}},createdAt:now,updatedAt:now};
order.ruleSnapshot=clone(rule);order.detailSnapshot=clone(detail);order.arrival=clone(arrival);order.sources.businessVersion=mappedVersion||{path:'detail.businessVersion',value:version};
const existing=this.orders.get(versionKey);if(existing){if(existing.ruleId!==order.ruleId||existing.brief!==order.brief||JSON.stringify(existing.sources)!==JSON.stringify(order.sources)||JSON.stringify(existing.detailSnapshot?.fields)!==JSON.stringify(detail.fields))throw new OrderWorkflowError('VERSION_CONTENT_CONFLICT','同一订单版本的分类或字段证据已变化,请人工确认业务版本。');return {status:'duplicate',order:clone(existing)};}this.persistOrder(order);this.orders.set(versionKey,order);return {status:'matched',order:clone(order)};
const order={id:hash([arrival.source,currentOrderNo].join('\0')),versionKey,version,businessVersion:reportedVersion,versionSource:reportedVersion?'bpm.businessVersion':'bpm.taskId',tid,pid,orderNo:currentOrderNo,source:arrival.source,taskId:String(arrival.taskId),processName:arrival.processName,processVersion:String(detail.processVersion),nodeName:detail.nodeName||arrival.activityName||'',serialNo:text(serialNo.value),productCode:text(productCode.value),modelFull:text(modelFull.value),modelShort:text(modelShort.value),customer:text(customer.value),productLine:productLine.value,brief:String(brief.value),subject:String(detail.subject||arrival.subject||''),businessTime,businessTimeSource,sourceRevision:detail.sourceRevision||version,sources:{orderNo,serialNo,productCode,modelFull,modelShort,customer,brief,productLine},ruleId:rule.id,templateId:rule.templateId||null,status:'identified',steps:{discovery:{status:'success',source:'bpm-readonly'},detail:{status:'pending'},pdf:{status:'pending'},archive:{status:'pending'},notification:{status:'pending'}},createdAt:now,updatedAt:now};
order.ruleSnapshot=clone(rule);order.detailSnapshot=clone(detail);order.arrival=clone(arrival);order.sources.businessVersion=mappedVersion||{path:reportedVersion?'detail.businessVersion':'not-provided',value:reportedVersion};
this.assertUniqueTask(order);const existing=this.orders.get(versionKey)||[...this.orders.values()].find(saved=>saved.source===arrival.source&&saved.taskId===String(arrival.taskId));
if(existing){if(existing.tid!==order.tid||existing.pid!==order.pid||existing.orderNo!==order.orderNo||existing.ruleId!==order.ruleId||existing.brief!==order.brief||JSON.stringify(existing.sources)!==JSON.stringify(order.sources)||JSON.stringify(existing.detailSnapshot?.fields)!==JSON.stringify(detail.fields))throw new OrderWorkflowError('VERSION_CONTENT_CONFLICT','同一 BPM 通知任务的分类或字段证据已变化,保留原处理结果并等待核对。');return {status:'duplicate',order:clone(existing)};}this.persistOrder(order);this.orders.set(versionKey,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 saved=this.orders.get(versionKey);if(!saved)throw new OrderWorkflowError('ORDER_NOT_FOUND','订单版本不存在。');const order=clone(saved);order.steps||={};work(order);order.updatedAt=this.clock().toISOString();this.persistOrder(order);this.orders.set(versionKey,order);return clone(order);}
start(versionKey){return this.update(versionKey,order=>{if(!['identified','detail_error','pdf_error','archive_error','interrupted'].includes(order.status))throw new OrderWorkflowError('INVALID_STATE','当前订单不能开始处理。');if(order.steps.pdf?.status==='success'){order.status='pdf_success';return;}if(order.steps.detail?.status==='success'){order.status='detail_ready';return;}order.status='detail_capturing';order.steps.detail={status:'running',startedAt:this.clock().toISOString()};});}
start(versionKey){return this.update(versionKey,order=>{this.assertUniqueTask(order);if(!['identified','detail_error','pdf_error','archive_error','interrupted'].includes(order.status))throw new OrderWorkflowError('INVALID_STATE','当前订单不能开始处理。');if(order.steps.pdf?.status==='success'){order.status='pdf_success';return;}if(order.steps.detail?.status==='success'){order.status='detail_ready';return;}order.status='detail_capturing';order.steps.detail={status:'running',startedAt:this.clock().toISOString()};});}
markDetailReady(versionKey,detailEvidence={}){return this.update(versionKey,order=>{if(!['detail_capturing','detail_error'].includes(order.status))throw new OrderWorkflowError('INVALID_STATE','详情尚未处于采集状态。');order.detailEvidence=clone(detailEvidence);order.steps.detail={status:'success',...clone(detailEvidence)};order.status='detail_ready';});}
beginPdf(versionKey){return this.update(versionKey,order=>{if(!['detail_ready','pdf_error'].includes(order.status))throw new OrderWorkflowError('INVALID_STATE','当前状态不能生成 PDF。');order.status='pdf_pending';order.steps.pdf={status:'running',startedAt:this.clock().toISOString()};});}
beginArchive(versionKey){return this.update(versionKey,order=>{if(order.steps.pdf?.status!=='success'||!['pdf_success','archive_error'].includes(order.status))throw new OrderWorkflowError('INVALID_STATE','当前状态不能归档。');order.status='archive_pending';order.steps.archive={status:'running',startedAt:this.clock().toISOString()};});}
@@ -111,6 +115,7 @@ class OrderWorkflow{
const candidates=[...this.orders.values()].filter(order=>['notification_pending','blocked'].includes(order.status)&&['pending','blocked'].includes(order.notification?.status)&&Date.parse(order.notification.occurredAt)<=Date.parse(cutoff)).map(clone),grouped=new Map();
const block=(order,message)=>{order.notification.status='blocked';order.notification.error=message;order.steps.notification={status:'blocked',error:message};order.status='blocked';};
for(const order of candidates){
try{this.assertUniqueTask(order);}catch(error){block(order,error.message);continue;}
const notification=order.notification,productLine=order.productLine,templateId=order.templateId,rule=order.ruleSnapshot||{};
const group=groups[rule.recipientGroupId||productLine];
if(!Array.isArray(group?.to)||!group.to.length){block(order,'分类规则没有已确认的收件组。');continue;}
@@ -131,7 +136,7 @@ class OrderWorkflow{
saveGraph(orders,batches){if(this.store?.putGraph)this.store.putGraph(orders,batches);else {orders.forEach(order=>this.persistOrder(order));batches.forEach(batch=>this.persistBatch(batch));}orders.forEach(order=>this.orders.set(order.versionKey,order));batches.forEach(batch=>this.batches.set(batch.id,batch));}
freezeBatch(cutoff,options={}){return this.freezeBatches(cutoff,options)[0];}
getBatch(id){const batch=this.batches.get(id);return batch?clone(batch):null;}listBatches(){return [...this.batches.values()].map(clone);}
markBatchSending(id){return this.updateBatch(id,'sending');}markBatchSent(id){return this.updateBatch(id,'sent');}markBatchFailed(id,message){return this.updateBatch(id,'failed',message);}
markBatchSending(id){const batch=this.getBatch(id);for(const key of batch?.orderVersionKeys||[]){const order=this.get(key);if(!order)throw new OrderWorkflowError('ORDER_NOT_FOUND','批次关联订单不存在。');this.assertUniqueTask(order);}return this.updateBatch(id,'sending');}markBatchSent(id){return this.updateBatch(id,'sent');}markBatchFailed(id,message){return this.updateBatch(id,'failed',message);}
updateBatch(id,status,error=null){const saved=this.batches.get(id);if(!saved)throw new OrderWorkflowError('BATCH_NOT_FOUND','批次不存在。');const allowed={prepared:['sending','failed'],sending:['sent','unknown'],failed:['sending','failed'],unknown:[]};if(!allowed[saved.status]?.includes(status))throw new OrderWorkflowError('INVALID_BATCH_STATE','当前批次不能执行此操作。');const batch={...clone(saved),status,error,updatedAt:this.clock().toISOString()};if(status==='sending'||status==='failed')batch.attempts=(batch.attempts||0)+1;const orders=batch.orderVersionKeys.map(key=>this.get(key)).filter(Boolean);for(const order of orders){order.status=status==='failed'?'batched':status;order.notification.status=status;order.steps.notification={status,batchId:id,...(error?{error}:{})};}this.saveGraph(orders,[batch]);return clone(batch);}
markBatchUnknown(id,message){return this.updateBatch(id,'unknown',String(message));}
resolveBatch(id,{resolution,note},actor){const saved=this.getBatch(id);if(!saved||!['unknown','failed'].includes(saved.status))throw new OrderWorkflowError('RESOLUTION_INVALID','只能核验结果不明或明确失败的批次。');if(!['sent','retry'].includes(resolution)||typeof note!=='string'||note.trim().length<5)throw new OrderWorkflowError('RESOLUTION_INVALID','请填写至少 5 字的核验依据。');const batch={...saved,status:resolution==='sent'?'sent':'prepared',resolution,verification:{actor,note:note.trim(),at:this.clock().toISOString()}};if(resolution==='retry')batch.attempts=0;const orders=batch.orderVersionKeys.map(key=>this.get(key)).filter(Boolean);for(const order of orders){order.status=resolution==='sent'?'sent':'batched';order.notification.status=resolution==='sent'?'sent':'reserved';order.steps.notification={status:order.status,batchId:id};}this.saveGraph(orders,[batch]);return clone(batch);}