feat: add guarded BPM category and template workflow
Implement server-owned read-only sample checks, category publication, explicit order-version identity and durable PDF/archive/notification steps. Freeze category-bound templates and recipients for isolated scheduled delivery, and require human verification for unknown SMTP outcomes. Add order/batch views and local HTTP/browser/PDF/archive regression coverage. Fix Unicode Windows startup links found by full regression using IShellLinkW. Automatic processing and sending stay disabled; no service deployment. Validation: npm ci; npm test -- --test-concurrency=1 (242 pass, 1 optional ZCode skip, 0 fail); 31 syntax checks; scoped independent code review. Live BPM V13/SMB/163 acceptance remains pending.
This commit is contained in:
1 parent
6e795a99b7
commit
94fc985553
38 files changed
+1204
-131
No files matched your search
+115
-57
@@ -1,6 +1,7 @@
|
||||
'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;}
|
||||
@@ -9,75 +10,132 @@ class OrderWorkflowError extends Error{
|
||||
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 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('、'));
|
||||
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','字段存在多个不同候选值:'+paths.join('、'));
|
||||
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||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','当前节点与已确认规则不一致。');
|
||||
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]));}
|
||||
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)};
|
||||
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]));
|
||||
}
|
||||
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);
|
||||
persistOrder(order){this.store?.putOrder?.(order);}persistBatch(batch){this.store?.putBatch?.(batch);}
|
||||
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);
|
||||
}
|
||||
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);}
|
||||
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);
|
||||
const mappedVersion=mapping.businessVersion?readCandidate({arrival,detail},mapping.businessVersion,'业务版本'):null;
|
||||
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','缺少表单版本。');
|
||||
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 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)};
|
||||
}
|
||||
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()};});}
|
||||
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){
|
||||
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){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};
|
||||
module.exports={OrderWorkflow,OrderWorkflowError,readCandidate};
|
||||
Reference in new issue
Block a user