Files
order-notification-automation/src/order-workflow.cjs
T

147 lines
24 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
'use strict';
const crypto=require('node:crypto');
const {renderOrderTemplate}=require('./order-template-bridge.cjs');
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()!=='');
const text=value=>String(value??'').trim();
function candidateValues(source,spec){
const paths=Array.isArray(spec)?spec:[spec];
if(!paths.length||paths.some(path=>typeof path!=='string'&&!(path&&typeof path==='object'&&typeof path.path==='string'))){throw new OrderWorkflowError('MISSING_FIELD','字段映射路径不能为空。');}
return paths.map(item=>{
const descriptor=typeof item==='string'?{source:'detail',path:item}:item;
const origin=descriptor.source||descriptor.from||'detail';
if(!['detail','arrival','list'].includes(origin)||!descriptor.path.trim())throw new OrderWorkflowError('MISSING_FIELD','字段来源或路径无效。');
const value=origin==='arrival'||origin==='list'?source.arrival?.[descriptor.path]:source.detail?.fields?.[descriptor.path];
if(present(value)&&!['string','number'].includes(typeof value))throw new OrderWorkflowError('AMBIGUOUS_FIELD','业务字段必须为单一文本或数值:'+descriptor.path);
return {path:`${origin}.${descriptor.path}`,value};
}).filter(item=>present(item.value));
}
function readCandidate(source,spec,label='字段'){
const values=candidateValues(source,spec);
if(!values.length){
const paths=(Array.isArray(spec)?spec:[spec]).map(item=>typeof item==='string'?item:item?.path||'').filter(Boolean);
throw new OrderWorkflowError('MISSING_FIELD','缺少字段'+(label?`(${label})`:'')+':'+paths.join('、'));
}
const distinct=new Map(values.map(item=>[JSON.stringify(item.value),item]));
if(distinct.size>1)throw new OrderWorkflowError('AMBIGUOUS_FIELD','字段存在多个不同候选值:'+values.map(item=>item.path).join('、'));
return values[0];
}
function nodeNames(steps){return (Array.isArray(steps)?steps:[]).map(step=>text(step?.name||step?.nodeName||step?.activityName||step?.text)).filter(Boolean);}
function exactRule(arrival,detail,rule){
if(!rule||rule.enabled!==true)throw new OrderWorkflowError('RULE_BLOCKED','订单规则未启用。');
if(rule.processName!==arrival.processName||(detail.processName!==undefined&&rule.processName!==detail.processName))throw new OrderWorkflowError('PROCESS_CONFLICT','流程名称与已确认规则不一致。');
const arrivalNode=text(arrival.activityName),detailNode=text(detail.nodeName);
if((arrivalNode&&arrivalNode!==rule.nodeName)||(detailNode&&detailNode!==rule.nodeName)||(arrivalNode&&detailNode&&arrivalNode!==detailNode))throw new OrderWorkflowError('NODE_CONFLICT','当前节点与已确认规则不一致。');
const observed=nodeNames(detail.processSteps);if(observed.length&&!observed.includes(rule.nodeName))throw new OrderWorkflowError('NODE_CONFLICT','流程步骤证据中没有当前节点。');
const current=nodeNames((detail.processSteps||[]).filter(step=>['处理中','running','active'].includes(step.status)));if(current.length&&(new Set(current).size!==1||current[0]!==rule.nodeName))throw new OrderWorkflowError('NODE_CONFLICT','流程步骤当前办理节点与列表不一致。');
}
function dateOnly(value){const date=new Date(value);if(Number.isNaN(+date))return text(value);return new Intl.DateTimeFormat('en-CA',{timeZone:'Asia/Shanghai'}).format(date);}
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]));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','字段适配器版本无效。');
const old=this.ruleMap.get(rule.id);if(old&&rule.version!==old.version)throw new OrderWorkflowError('RULE_VERSION_CONFLICT','分类规则已被修改,请刷新后保存。');
const value={batchMode:'category_template',notificationType:'order',pdfTemplateId:'bpm-snapshot-v1',...clone(rule),version:(old?.version||0)+1,status:'draft',check:null,enabled:rule.enabled!==false,processName:rule.processName.trim(),nodeName:rule.nodeName.trim(),productLine:rule.productLine.trim(),templateId:rule.templateId.trim()};
if(!['category_template','product_line','order'].includes(value.batchMode))throw new OrderWorkflowError('RULE_INVALID','批次模式无效。');
this.store?.putRule?.(value);this.ruleMap.set(value.id,value);return clone(value);
}
checkRule(id,{arrival,detail,provenance}){
const rule=this.getRule(id);if(!rule)throw new OrderWorkflowError('RULE_NOT_FOUND','分类规则不存在。');if(provenance!=='bpm-readonly'||detail?.readOnly===false)throw new OrderWorkflowError('DETAIL_PROVENANCE','只能使用服务器只读采集的 BPM 样本。');
rule.check=null;this.store?.putRule?.(rule);this.ruleMap.set(id,rule);
try{const preview=new OrderWorkflow({clock:this.clock});preview.identify({arrival,detail,rule:{...rule,enabled:true},mapping:rule.adapters[String(detail.processVersion)]});}
catch(error){return {valid:false,issues:[{code:error.code||'SAMPLE_INVALID',message:error.message}],sample:{processName:arrival.processName,nodeName:detail.nodeName,processVersion:detail.processVersion,fields:clone(detail.fields),tid:detail.tid,pid:detail.pid}};}
const check={checkId:crypto.randomUUID(),version:rule.version,checkedAt:this.clock().toISOString(),evidenceHash:hash(JSON.stringify({arrival,detail}))};rule.check=check;this.store?.putRule?.(rule);this.ruleMap.set(id,rule);return {valid:true,issues:[],...check,sample:{processName:arrival.processName,nodeName:detail.nodeName,processVersion:detail.processVersion,fields:clone(detail.fields),tid:detail.tid,pid:detail.pid}};
}
publishRule(id,{version,checkId}){
const rule=this.getRule(id);if(!rule||rule.version!==version||rule.check?.version!==version||!checkId||rule.check?.checkId!==checkId)throw new OrderWorkflowError('RULE_CHECK_REQUIRED','必须对当前版本执行真实只读样本检查后发布。');
if(rule.enabled&&[...this.ruleMap.values()].some(old=>old.id!==id&&old.status==='published'&&old.enabled&&old.processName===rule.processName&&old.nodeName===rule.nodeName))throw new OrderWorkflowError('RULE_CONFLICT','同一流程和节点已有发布规则。');
rule.status='published';rule.publishedAt=this.clock().toISOString();this.store?.putRule?.(rule);this.ruleMap.set(id,rule);return clone(rule);
}
invalidateCheck(id){const rule=this.getRule(id);if(!rule)throw new OrderWorkflowError('RULE_NOT_FOUND','分类规则不存在。');rule.check=null;this.store?.putRule?.(rule);this.ruleMap.set(id,rule);}
getRule(id){const rule=this.ruleMap.get(id);return rule?clone(rule):null;}rules(){return [...this.ruleMap.values()].map(clone);}
resolveRule(arrival,detail){
const node=text(arrival?.activityName||detail?.nodeName);if(arrival?.activityName&&detail?.nodeName&&arrival.activityName!==detail.nodeName)throw new OrderWorkflowError('NODE_CONFLICT','列表当前节点与详情节点不一致。');
const candidates=[...this.ruleMap.values()].filter(rule=>rule.enabled===true&&rule.status==='published'&&rule.processName===arrival?.processName&&rule.nodeName===node);if(candidates.length!==1)throw new OrderWorkflowError(candidates.length?'RULE_CONFLICT':'RULE_UNMATCHED',candidates.length?'流程和节点命中多个分类规则。':'流程和节点没有命中已发布分类规则。');
const rule=candidates[0],mapping=rule.adapters?.[String(detail?.processVersion||'')];if(!mapping)throw new OrderWorkflowError('ADAPTER_MISSING','当前表单版本没有字段适配器:'+String(detail?.processVersion||''));return {rule,mapping};
}
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);
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)||![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},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: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=>{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()};});}
markPdfSuccess(versionKey,pdf){return this.update(versionKey,order=>{if(!['detail_ready','pdf_error','pdf_pending'].includes(order.status))throw new OrderWorkflowError('INVALID_STATE','详情未准备好,不能记录 PDF。');if(!pdf?.jobId)throw new OrderWorkflowError('PDF_EVIDENCE_MISSING','缺少 PDF 任务证据。');order.pdf=clone(pdf);order.steps.pdf={status:'success',...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.steps.pdf={status:'error',error:String(message)};order.status='pdf_error';});}
markArchiveSuccess(versionKey,archive){return this.update(versionKey,order=>{if(!['pdf_success','archive_error','archive_pending'].includes(order.status))throw new OrderWorkflowError('INVALID_STATE','PDF 未成功,不能记录归档。');if(!archive?.archiveId)throw new OrderWorkflowError('ARCHIVE_EVIDENCE_MISSING','缺少 SMB 归档回执。');order.archive=clone(archive);order.steps.archive={status:'success',...clone(archive)};order.status='archived';});}
markArchiveError(versionKey,message){return this.update(versionKey,order=>{if(!['pdf_success','archive_pending'].includes(order.status))throw new OrderWorkflowError('INVALID_STATE','当前状态不能记录归档失败。');order.error=String(message);order.steps.archive={status:'error',error:String(message)};order.status='archive_error';});}
createNotification(versionKey,input){return this.update(versionKey,order=>{if(order.status!=='archived')throw new OrderWorkflowError('ARCHIVE_REQUIRED','归档未成功,不能创建通知事件。');const data=input||{productLine:order.productLine,templateId:order.templateId,brief:order.brief,subject:order.subject,occurredAt:order.businessTime};data.templateId||=order.templateId;for(const key of ['productLine','templateId','brief','subject','occurredAt'])if(!present(data[key]))throw new OrderWorkflowError('NOTIFICATION_FIELD_MISSING','通知字段未确认:'+key);order.notification={...clone(data),orderVersionKey:versionKey,createdAt:this.clock().toISOString(),status:'pending'};order.steps.notification={status:'pending'};order.status='notification_pending';});}
freezeBatches(cutoff,{mode='product_line',groups={},templates={}}={}){
if(!Number.isFinite(Date.parse(cutoff)))throw new OrderWorkflowError('WINDOW_INVALID','发送窗口无效。');
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;}
const template=templates[templateId];if(!template){block(order,'分类规则绑定的邮件模板未加载。');continue;}
const key=JSON.stringify([order.ruleId,rule.version,productLine,templateId,rule.batchMode==='order'||mode==='order'?order.versionKey:'',group.to,group.cc||[]]);
if(!grouped.has(key))grouped.set(key,{ruleId:order.ruleId,productLine,templateId,group,template,orders:[]});grouped.get(key).orders.push(order);
}
const batches=[];
for(const selected of grouped.values()){
const orders=selected.orders,date=[...new Set(orders.map(order=>dateOnly(order.businessTime)))].join('、');let rendered;
try{rendered=renderOrderTemplate(selected.template,{productLine:selected.productLine,orders,date});}catch(error){orders.forEach(order=>block(order,error.message));continue;}
const batch={id:crypto.randomUUID(),status:'prepared',cutoff,mode,ruleId:selected.ruleId,productLine:selected.productLine,templateId:selected.templateId,templateVersion:rendered.templateVersion,templateSnapshot:{id:selected.template.id,version:selected.template.version,subject:selected.template.subject,text:selected.template.text,html:selected.template.html},to:[...selected.group.to],cc:[...(selected.group.cc||[])],orderVersionKeys:orders.map(order=>order.versionKey),subject:rendered.subject,text:rendered.text,html:rendered.html,attachments:[],attempts:0,createdAt:this.clock().toISOString()};
for(const order of orders){order.notification.status='reserved';order.notification.batchId=batch.id;delete order.notification.error;order.steps.notification={status:'batched',batchId:batch.id};order.status='batched';}batches.push(batch);
}
this.saveGraph(candidates,batches);
if(!batches.length)throw new OrderWorkflowError('EMPTY_BATCH','当前发送窗口没有待发通知。');return batches.map(clone);
}
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){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);}
canAutoRetry(id){const batch=this.batches.get(id);return !!batch&&batch.status==='failed';}
}
module.exports={OrderWorkflow,OrderWorkflowError,readCandidate};