feat: add guarded order workflow state
This commit is contained in:
1 parent
9854d2d5c2
commit
6e795a99b7
8 files changed
+250
-5
No files matched your search
@@ -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};
|
||||
Reference in new issue
Block a user