feat: freeze and recover independent Huizhou notifications
This commit is contained in:
1 parent
d903252807
commit
d8aa14d855
14 files changed
+294
-48
No files matched your search
@@ -1,4 +1,5 @@
|
||||
'use strict';
|
||||
const {needsRuntimeCheck,reserved}=require('../order-rules/delivery.cjs');
|
||||
const crypto=require('node:crypto');
|
||||
const {fail}=require('../order-rules/validation.cjs');
|
||||
const {dayPolicy,nextSlots}=require('../../shared/schedule.cjs');
|
||||
@@ -189,9 +190,9 @@ class OrderExecutionCoordinator{
|
||||
}
|
||||
if(hash(task.row)!==hash(row)&&task.ignoredRevisionHash!==hash(row)){task.conflictRow=clone(row);task.status='blocked';task.error='同一事件修订内容冲突,需核对源版本。';task.conflict=true;this.persist(task);}
|
||||
const order=task.orderId&&this.store.get('orders',task.orderId);
|
||||
const reserved=order?.batchId||['batched','sending','sent','unknown'].includes(order?.status);
|
||||
const isReserved=reserved(order)||['batched','sending','sent','unknown'].includes(order?.status);
|
||||
const protectedTask=task.supersededBy||task.revisionIgnored||['unknown','sending','sent'].includes(task.status);
|
||||
if(historical&&!reserved&&!protectedTask)this.holdMissedTask(task,order,frozen);
|
||||
if(historical&&!isReserved&&!protectedTask)this.holdMissedTask(task,order,frozen);
|
||||
discovered.push(task);
|
||||
}
|
||||
this.query={...this.query,rowCount:rows.length,targetCount:considered,processedCount:0,discoveredAt:this.now()};
|
||||
@@ -204,13 +205,13 @@ class OrderExecutionCoordinator{
|
||||
if(task.missedWindow){await this.exception(task,connection,false);continue;}
|
||||
if(task.conflict){await this.exception(task,connection,false);continue;}
|
||||
this.reconcileArchive(task);
|
||||
if(task.conflict||task.status==='unknown'||task.step==='archive'&&task.status==='failed')continue;
|
||||
if(task.conflict||task.status==='unknown'&&task.step!=='complete'||task.step==='archive'&&task.status==='failed')continue;
|
||||
const order=task.orderId&&this.store.get('orders',task.orderId);
|
||||
if(order&&['pending','batched','sent','unknown','ignored'].includes(order.status)){
|
||||
task.status=order.status;
|
||||
task.error=order.error||null;
|
||||
this.persist(task);
|
||||
if(['pending','batched'].includes(order.status))await this.checkArchivedRuntime(task,order,connection,principal);
|
||||
if(needsRuntimeCheck(order))await this.checkArchivedRuntime(task,order,connection,principal);
|
||||
continue;
|
||||
}
|
||||
await this.execute(task,connection,principal,{automatic:input.automatic===true});
|
||||
@@ -226,9 +227,9 @@ class OrderExecutionCoordinator{
|
||||
if(task.connectionId!==connection.id||observed.has(task.id)||task.conflict)continue;
|
||||
this.reconcileArchive(task);
|
||||
const order=task.orderId&&this.store.get('orders',task.orderId);
|
||||
if(!order?.archive||!['pending','batched'].includes(order.status))continue;
|
||||
if(!needsRuntimeCheck(order))continue;
|
||||
const window=this.store.snapshot().window;
|
||||
if(window&&!order.batchId&&Date.parse(order.event.receivedAt)<Date.parse(window.start))continue;
|
||||
if(window&&!reserved(order)&&Date.parse(order.event.receivedAt)<Date.parse(window.start))continue;
|
||||
await this.checkArchivedRuntime(task,order,connection,principal);
|
||||
}
|
||||
if(input.automatic&&!this.store.settings().processingEnabled)throw Error('自动处理已暂停,待处理对账保留到恢复后继续。');
|
||||
|
||||
@@ -22,7 +22,7 @@ function validFile(file){
|
||||
return file&&typeof file.name==='string'&&file.name.length>0&&!/[\r\n\x00-\x1f]/.test(file.name)&&typeof file.path==='string'&&!/[\r\n\x00-\x1f]/.test(file.path)&&(path.isAbsolute(file.path)||path.win32.isAbsolute(file.path))&&!/^[a-z]+:\/\//i.test(file.path)&&/^[a-f\d]{64}$/i.test(file.sha256)&&Number.isSafeInteger(file.size)&&file.size>=0&&['pdf','notice'].includes(file.kind);
|
||||
}
|
||||
|
||||
function buildBatch(rule,orders,cutoff,{maxMessageBytes=20971520,window}={}){
|
||||
function buildBatch(rule,orders,cutoff,{maxMessageBytes=20971520,window,notificationMode='normal'}={}){
|
||||
const limit=Date.parse(cutoff);
|
||||
if(!Number.isFinite(limit)||!Number.isSafeInteger(maxMessageBytes)||maxMessageBytes<1)fail('截止时间或邮件大小设置无效。');
|
||||
const start=window?Date.parse(window.start):null,end=window?Date.parse(window.end):null;
|
||||
@@ -44,16 +44,17 @@ function buildBatch(rule,orders,cutoff,{maxMessageBytes=20971520,window}={}){
|
||||
if(!order.archive||!Number.isFinite(Date.parse(order.archive.archivedAt))||!Array.isArray(order.archive.files)||!order.archive.files.length)fail(`订单 ${number} 缺少归档证据,本类别已阻塞。`);
|
||||
if(order.archive.files.some(file=>!validFile(file)))fail(`订单 ${number} 的归档文件证据无效。`);
|
||||
if(rule.attachPdf&&!order.archive.files.some(file=>file.kind==='pdf'&&/\.pdf$/i.test(file.name)))fail(`订单 ${number} 缺少必需 PDF,本类别已阻塞。`);
|
||||
orderIds.push(order.id);orderNos.push(number);
|
||||
orderIds.push(order.id);orderNos.push(...(notificationMode==='huizhou'?order.event.titleOrders.map(row=>row.orderNo):[number]));
|
||||
const files=order.archive.files;
|
||||
attachments.push(...files.filter(file=>file.kind!=='pdf'||rule.attachPdf).map(file=>({...file})));
|
||||
plain.push(`${number}\n${String(order.event.brief??'')}\n${files.map(file=>file.path).join('\n')}`);
|
||||
html.push(`<li><strong>${escape(number)}</strong><br><span style="color:#0000ff">${lines(order.event.brief)}</span><br>${files.map(file=>`<a style="color:#0000ff" href="${escape(fileLink(file.path))}">${escape(file.path)}</a>`).join('<br>')}</li>`);
|
||||
plain.push(`${number}\n${String(order.event.brief??'')}`+(notificationMode==='huizhou'?'':`\n${files.map(file=>file.path).join('\n')}`));
|
||||
html.push(`<li><strong>${escape(number)}</strong><br><span style="color:#0000ff">${lines(order.event.brief)}</span>`+(notificationMode==='huizhou'?'':`<br>${files.map(file=>`<a style="color:#0000ff" href="${escape(fileLink(file.path))}">${escape(file.path)}</a>`).join('<br>')}`)+'</li>');
|
||||
}
|
||||
const prefix=String(rule.subjectPrefix||rule.name||'订单通知');
|
||||
if(/[\r\n\x00-\x1f]/.test(prefix))fail('邮件标题无效。');
|
||||
const snapshot={categoryId:rule.categoryId,subject:`${prefix} ${orderNos.join('、')}`,text:[rule.intro||'',...plain,rule.signature||''].filter(Boolean).join('\n\n'),html:`<div>${lines(rule.intro)}</div><ul>${html.join('')}</ul><div>${lines(rule.signature)}</div>`,to,cc,orderIds,orderNos,attachments,cutoff:new Date(limit).toISOString()};
|
||||
if(rule.categoryId==='overseas-notice'){
|
||||
snapshot.notificationMode=notificationMode;
|
||||
if(notificationMode==='normal'&&rule.categoryId==='overseas-notice'){
|
||||
const content=mailContent(orders);
|
||||
snapshot.text=[rule.intro,content.details,'存放地址:'+content.directories.join('\n'),rule.signature].filter(Boolean).join('\n\n');
|
||||
snapshot.html='<div>'+lines(rule.intro)+'</div>'+content.htmlDetails+content.htmlDirectories+'<div>'+lines(rule.signature)+'</div>';
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
'use strict';
|
||||
function modeOf(batch){return batch?.notificationMode||'normal';}
|
||||
function delivery(order,mode='normal'){
|
||||
if(!order)return null;
|
||||
return mode==='normal'?{status:order.status,batchId:order.batchId||null,error:order.error||null}:order.notifications?.huizhou||null;
|
||||
}
|
||||
function updateDelivery(order,mode,patch){
|
||||
if(mode==='normal')Object.assign(order,patch);
|
||||
else {if(!order.notifications?.huizhou)throw Error('惠州通知没有独立预留记录。');Object.assign(order.notifications.huizhou,patch);}
|
||||
return order;
|
||||
}
|
||||
function notifications(order){
|
||||
if(!order)return undefined;
|
||||
const h=delivery(order,'huizhou');
|
||||
return {normal:delivery(order),huizhou:h?{status:h.status,batchId:h.batchId||null,error:h.error||null,orderNos:[...(h.orderNos||[])],issues:[...(h.issues||[])]}:{status:'not_applicable',batchId:null,error:null,orderNos:[],issues:[]}};
|
||||
}
|
||||
function needsRuntimeCheck(order){return !!order?.archive&&(['pending','batched'].includes(order.status)||['pending','batched'].includes(delivery(order,'huizhou')?.status));}
|
||||
function reserved(order){return !!order?.batchId||!!delivery(order,'huizhou')?.batchId;}
|
||||
module.exports={modeOf,delivery,updateDelivery,notifications,needsRuntimeCheck,reserved};
|
||||
@@ -5,6 +5,7 @@ const crypto=require('node:crypto');
|
||||
const {nextSlots}=require('../../shared/schedule.cjs');
|
||||
const {windowForCutoff}=require('./window.cjs');
|
||||
const {fail}=require('./validation.cjs');
|
||||
const {modeOf,delivery,updateDelivery}=require('./delivery.cjs');
|
||||
|
||||
function freeze(value){
|
||||
if(value&&typeof value==='object'){for(const item of Object.values(value))freeze(item);Object.freeze(value);}
|
||||
@@ -90,7 +91,7 @@ class OrderRuleDispatcher{
|
||||
const partial=result?.rejected?.length||[...batch.to,...batch.cc].some(address=>!accepted.has(address.toLowerCase()));
|
||||
this.store.finishSending(batch.id,partial?'unknown':'sent',partial?'部分收件人未被服务器接受,请核对邮件记录后处理。':'邮件服务器已接受全部收件人;最终送达请以邮件记录为准。');
|
||||
}catch(error){
|
||||
if(!sending&&error.code==='DISCOVERY_INCOMPLETE')return false;
|
||||
if(!sending&&!manual&&error.code==='DISCOVERY_INCOMPLETE')return false;
|
||||
const rejected=error.code==='EENVELOPE'&&error.command==='RCPT TO'&&Array.isArray(error.rejected)&&error.rejected.length>0&&(!error.accepted||error.accepted.length===0)&&[...batch.to,...batch.cc].every(address=>error.rejected.some(r=>String(r.address||r).toLowerCase()===address.toLowerCase()));
|
||||
this.store.finishSending(batch.id,sending&&!rejected?'unknown':'failed',sending&&!rejected?'发送结果待核实,请核对邮件服务器记录后决定是否重试。':`发送前验证失败:${error.code==='ENOENT'?'归档文件不存在。':error.message==='归档文件校验失败。'?error.message:'请检查归档证据、SMTP 与启用状态。'}`);
|
||||
}finally{
|
||||
@@ -113,9 +114,9 @@ class OrderRuleDispatcher{
|
||||
const source=this.store.get('batches',id);if(input.version!==(source.version||1)||source.status!=='failed')fail('批次版本已变化,或发送结果尚未核验。',409);
|
||||
const root=source.rootBatchId||source.id;
|
||||
if(this.store.all('batches').some(b=>b.id!==source.id&&(b.rootBatchId||b.id)===root&&['sent','sending','unknown','prepared'].includes(b.status)))fail('此批次已发送、结果待核实或已有补发尝试。',409);
|
||||
if(source.orderIds.some(oid=>{const o=this.store.get('orders',oid);return !o||['sent','unknown','batched'].includes(o.status);}))fail('原订单关联已发送或结果待核实。',409);
|
||||
if(source.orderIds.some(oid=>{const state=delivery(this.store.get('orders',oid),modeOf(source));return !state||['sent','unknown','batched','sending'].includes(state.status);}))fail('原订单关联已发送或结果待核实。',409);
|
||||
const next={...structuredClone(source),id:crypto.randomUUID(),version:1,parentBatchId:source.id,rootBatchId:root,status:'prepared',manual:true,createdAt:this.clock().toISOString(),error:null,resolution:null,finishedAt:null,resend:{actor:actor.username,note:input.note.trim(),at:this.clock().toISOString()}};
|
||||
this.store.put('batches',next);for(const oid of next.orderIds){const o=this.store.get('orders',oid);o.batchId=next.id;o.status='batched';o.error=null;this.store.put('orders',o);}
|
||||
this.store.put('batches',next);for(const oid of next.orderIds){const o=this.store.get('orders',oid);updateDelivery(o,modeOf(next),{batchId:next.id,status:'batched',error:null});this.store.put('orders',o);}
|
||||
this.store.put('resend-requests',{id:requestId,batchId:next.id,inputHash});this.store.audit(actor.username,'人工补发冻结分类邮件',source.id+':'+input.note.trim());return next;
|
||||
});
|
||||
await this.dispatch(freeze(structuredClone(batch)),{...this.store.settings(),channelId:batch.channelId},{manual:true});return this.store.get('batches',batch.id);
|
||||
|
||||
@@ -3,8 +3,10 @@ const path=require('node:path');
|
||||
const {publicationIssues}=require('./validation.cjs');
|
||||
const {archiveFilename}=require('../storage/order-filename.cjs');
|
||||
const {buildBatch}=require('./batch.cjs'),{applyBodyTemplate}=require('./template.cjs');
|
||||
const {initialNotification,ordersForMode}=require('./huizhou.cjs');
|
||||
function previewEffects(rule,event,store){
|
||||
const result={simulation:true,archiveVerified:false,filename:null,path:null,mail:null,issues:publicationIssues(rule,store.adapters()),provisionalDate:rule.filenameDate==='archiveDate'};
|
||||
const hui=initialNotification(rule,event);
|
||||
const result={simulation:true,archiveVerified:false,filename:null,path:null,mail:null,issues:publicationIssues(rule,store.adapters()),provisionalDate:rule.filenameDate==='archiveDate',notifications:{normal:{status:'blocked',mail:null,issues:[]},huizhou:{status:hui.status,mail:null,orderNos:hui.orderNos,issues:hui.issues}}};
|
||||
try{
|
||||
const at=rule.filenameDate==='appDate'?event.appDate:rule.filenameDate==='receivedAt'?event.receivedAt:store.now();
|
||||
result.filename=archiveFilename(event,rule.filenameDate,at);
|
||||
@@ -14,8 +16,14 @@ function previewEffects(rule,event,store){
|
||||
const file={name:result.filename,path:result.path,size:0,sha256:'0'.repeat(64),kind:'pdf'};
|
||||
const order={id:'simulation',event,ruleSnapshot:rule,status:'pending',archive:{archivedAt:store.now(),files:[file]}};
|
||||
const cutoff=new Date(Math.max(Date.parse(event.receivedAt),Date.parse(store.now()))).toISOString();
|
||||
const snapshot=applyBodyTemplate(buildBatch(rule,[order],cutoff,{maxMessageBytes:store.settings().maxMessageBytes}),store.templateResolver?.(rule.categoryId,rule),[order],store.settings().maxMessageBytes);
|
||||
result.mail={subject:snapshot.subject,text:snapshot.text,to:snapshot.to,cc:snapshot.cc,attachments:snapshot.attachments.map(f=>f.name),template:snapshot.template||null};
|
||||
for(const mode of ['normal','huizhou']){
|
||||
if(mode==='huizhou'&&hui.status!=='pending')continue;
|
||||
try{
|
||||
const orders=ordersForMode([order],mode),snapshot=applyBodyTemplate(buildBatch(rule,orders,cutoff,{maxMessageBytes:store.settings().maxMessageBytes,notificationMode:mode}),store.templateResolver?.(rule.categoryId,rule,mode),orders,store.settings().maxMessageBytes);
|
||||
const mail={subject:snapshot.subject,text:snapshot.text,to:snapshot.to,cc:snapshot.cc,attachments:snapshot.attachments.map(f=>f.name),template:snapshot.template||null};
|
||||
result.notifications[mode]={...result.notifications[mode],status:'ready',mail};if(mode==='normal')result.mail=mail;
|
||||
}catch(error){result.notifications[mode].status='blocked';result.notifications[mode].issues.push(error.message);if(mode==='normal')result.issues.push(error.message);}
|
||||
}
|
||||
}catch(error){result.issues.push(error.message);}
|
||||
return result;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
'use strict';
|
||||
const MODES=new Set(['惠州','惠州数字','惠州模式']);
|
||||
const CUSTOMER='惠州创维数字技术有限公司';
|
||||
const clean=value=>String(value||'').trim().replace(/[|,,;;\s]+$/u,'');
|
||||
function selectHuizhou(event){
|
||||
const orders=[],issues=[];
|
||||
for(const row of event?.titleOrders||[]){
|
||||
const mode=clean(row.businessMode),customer=clean(row.customer||row.customerShort);
|
||||
const modeMatch=MODES.has(mode),customerMatch=customer===CUSTOMER;
|
||||
const conflict=row.businessModeAmbiguous||customerMatch&&mode&&!modeMatch;
|
||||
if(conflict){issues.push('订单 '+row.orderNo+' 的惠州业务模式与客户证据冲突或段落归属不明,需核实。');continue;}
|
||||
if(modeMatch||customerMatch){orders.push(structuredClone(row));continue;}
|
||||
if(/^HA/i.test(row.orderNo||'')||mode.includes('惠州')||customer.includes('惠州'))issues.push('订单 '+row.orderNo+' 仅有惠州线索,缺少明确业务模式或已知客户证据,需核实。');
|
||||
}
|
||||
// Whole-event fields may flag missing segment evidence, but can never select all rows.
|
||||
if(!event?.titleOrders?.length&&(MODES.has(clean(event?.businessMode))||clean(event?.customer)===CUSTOMER||/^HA/i.test(event?.orderNo||'')))issues.push('缺少逐订单标题明细,惠州需求需核实。');
|
||||
return {orders,orderNos:orders.map(row=>row.orderNo),issues};
|
||||
}
|
||||
function initialNotification(rule,event){
|
||||
if(rule?.huizhouEnabled!==true)return {status:'disabled',batchId:null,error:null,orderNos:[],issues:[]};
|
||||
const selection=selectHuizhou(event);
|
||||
return {status:selection.issues.length?'blocked':selection.orders.length?'pending':'empty',batchId:null,error:selection.issues.join(';')||null,orderNos:selection.orderNos,issues:selection.issues};
|
||||
}
|
||||
function ordersForMode(orders,mode='normal'){
|
||||
if(mode==='normal')return orders;
|
||||
return orders.flatMap(order=>{
|
||||
const selected=selectHuizhou(order.event);if(!selected.orders.length)return [];
|
||||
return [{...order,status:'pending',event:{...order.event,orderNo:selected.orderNos.join('、'),brief:selected.orders.map(row=>row.text).join('\n'),titleOrders:selected.orders}}];
|
||||
});
|
||||
}
|
||||
module.exports={selectHuizhou,initialNotification,ordersForMode};
|
||||
@@ -58,7 +58,7 @@ function previewMatch(rules, adapters, input, {mappingEvidence=false}={}) {
|
||||
const extracted=titleSource?extractTitle(sample[titleSource]):null;
|
||||
if(extracted){
|
||||
event.rawTitle=extracted.rawTitle;event.titleOrders=extracted.orders;event.factoryHints=extracted.factoryHints;
|
||||
check('标题提取',extracted.issues.length===0,extracted.issues.join(';')||`从标题提取 ${extracted.orders.length} 个订单段落;惠州线索仅供核实,不触发额外发送`);
|
||||
check('标题提取',extracted.issues.length===0,extracted.issues.join(';')||`从标题提取 ${extracted.orders.length} 个订单段落;惠州通知按每段业务模式与客户证据独立判断`);
|
||||
}
|
||||
for (const key of new Set(['orderNo', 'appDate', 'customer', 'productLine', 'quantity', ...Object.keys(mappings), ...Object.keys(sources), 'brief'])) {
|
||||
const selected=readSource(sources[key],sample);
|
||||
|
||||
@@ -7,7 +7,7 @@ const digest=v=>crypto.createHash('sha256').update(JSON.stringify(canonical(v)))
|
||||
|
||||
function frozen(store,order){
|
||||
if(!order)return false;
|
||||
return !!order.batchId||!!order.blockedByBatchId||!!order.missedWindow
|
||||
return !!order.batchId||!!order.notifications?.huizhou?.batchId||!!order.blockedByBatchId||!!order.missedWindow
|
||||
||['batched','sending','sent','unknown'].includes(order.status)
|
||||
||store.all('batches').some(batch=>batch.orderIds?.includes(order.id));
|
||||
}
|
||||
@@ -99,6 +99,7 @@ function apply(store,id,input,actor){
|
||||
order.event=proposed.result.event;
|
||||
order.trace=proposed.result;
|
||||
order.ruleSnapshot=structuredClone(rule);
|
||||
if(order.notifications)order.notifications.huizhou=require('./huizhou.cjs').initialNotification(rule,order.event);
|
||||
order.categoryId=rule.categoryId;
|
||||
order.updatedAt=store.now();
|
||||
order.error=null;
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
const crypto=require('node:crypto');
|
||||
const {canReadConnection,canReadOrder,canReadBatch}=require('./access.cjs');
|
||||
const {fail}=require('./validation.cjs');
|
||||
const {notifications,modeOf}=require('./delivery.cjs');
|
||||
const cache=new WeakMap();
|
||||
const orderStates=['identified','preparing','archived','pending','batched','blocked','unknown','sent','failed','capturing','archiving','queued','ignored'];
|
||||
const batchStates=['prepared','sending','unknown','failed','sent','cancelled'];
|
||||
@@ -37,7 +38,7 @@ function taskEvidence(task,context,user){
|
||||
}
|
||||
function orderRow(order,task){
|
||||
const event=identity(order?.event||task?.row);
|
||||
return {...event,...pick(order,['id','status','categoryId','error','reason','batchId','createdAt','updatedAt','orderNo','receivedAt']),
|
||||
return {...event,...pick(order,['id','status','categoryId','error','reason','batchId','createdAt','updatedAt','orderNo','receivedAt']),...(order?{notifications:notifications(order)}:{}),
|
||||
id:order?.id||'task:'+task.id,connectionId:order?.sample?.connectionId||event.connectionId||task?.connectionId,
|
||||
error:task?.error||order?.error,executionTaskId:task?.id,executionStatus:task?.status,exceptionId:task?.exceptionId,orderNo:order?.orderNo||event.orderNo||event.serialNum||event.taskId,
|
||||
categoryId:order?.categoryId||task?.categoryIds?.[0]||'',status:task&&['failed','blocked','unknown','capturing','archiving'].includes(task.status)?task.status:order?.status||task?.status};
|
||||
@@ -76,7 +77,7 @@ function publicRevision(context,user){
|
||||
}
|
||||
function queryOrders(context,input,user){return page(visibleOrders(context,user),filters(input,'orders'),publicRevision(context,user));}
|
||||
function batchRow(context,batch){
|
||||
return {...pick(batch,['id','version','categoryId','subject','status','error','createdAt','windowStart','windowEnd','cutoff','orderNos']),windowStart:batch.windowStart||batch.window?.start,windowEnd:batch.windowEnd||batch.window?.end||batch.cutoff,orderCount:batch.orderIds?.length||0,connectionIds:[...new Set((batch.orderIds||[]).map(id=>{const o=context.orderRules.get('orders',id);return o?.sample?.connectionId||o?.event?.connectionId||o?.connectionId;}).filter(Boolean))]};
|
||||
return {...pick(batch,['id','version','categoryId','subject','status','error','createdAt','windowStart','windowEnd','cutoff','orderNos']),notificationMode:modeOf(batch),windowStart:batch.windowStart||batch.window?.start,windowEnd:batch.windowEnd||batch.window?.end||batch.cutoff,orderCount:batch.orderIds?.length||0,connectionIds:[...new Set((batch.orderIds||[]).map(id=>{const o=context.orderRules.get('orders',id);return o?.sample?.connectionId||o?.event?.connectionId||o?.connectionId;}).filter(Boolean))]};
|
||||
}
|
||||
function queryBatches(context,input,user){
|
||||
const f=filters(input,'batches'),data=records(context.orderRules);
|
||||
@@ -115,9 +116,9 @@ function summary(context,user){
|
||||
const rows=visibleOrders(context,user),data=records(context.orderRules),batches=data.batches.filter(b=>canReadBatch(context.workspace,user,b,context.orderRules));
|
||||
const count=(items,status)=>items.filter(i=>status.includes(i.status)).length;
|
||||
result.scans=context.orderRules.all('execution-scans').filter(s=>canReadConnection(context.workspace,user,s.connectionId||s.id)).map(s=>pick(s,['id','connectionId','status','startedAt','finishedAt','rowCount','targetCount','error']));
|
||||
result.counts={orders:rows.length,blocked:count(rows,['blocked','failed']),unknown:count(batches,['unknown']),activeBatches:count(batches,['prepared','sending','unknown','failed'])};
|
||||
result.issues=data.issues.filter(issue=>!['resolved','retired'].includes(issue.status)).filter(issue=>user.role==='admin'||((issue.orderIds?.length||issue.taskIds?.length)&& (issue.orderIds||[]).every(id=>canReadOrder(context.workspace,user,context.orderRules.get('orders',id)))&&(issue.taskIds||[]).every(id=>canReadConnection(context.workspace,user,context.orderRules.get('execution-tasks',id)?.connectionId)))).slice(-50).map(i=>{const linked=context.workspace?.businessIssue?.(i.id);return pick(linked?{...i,status:linked.status,owner:linked.owner,exceptionId:linked.id}:i,['id','status','type','message','error','component','owner','owners','exceptionId','createdAt','batchId','orderIds','taskIds']);}).filter(i=>!['resolved','retired'].includes(i.status));
|
||||
result.templateUsage=context.orderRules.all('rules').map(r=>({categoryId:r.published?.categoryId||r.draft?.categoryId,name:r.draft?.name,templateId:r.published?.bodyTemplateId||'',legacyBinding:!!r.published&&r.published.bodyTemplateId===undefined,publishedVersion:r.published?.version||null,status:r.published?.status||'draft'}));
|
||||
result.counts={orders:rows.length,blocked:rows.filter(row=>['blocked','failed'].includes(row.status)||row.notifications?.huizhou?.status==='blocked').length,unknown:count(batches,['unknown']),activeBatches:count(batches,['prepared','sending','unknown','failed'])};
|
||||
result.issues=data.issues.filter(issue=>!['resolved','retired'].includes(issue.status)).filter(issue=>user.role==='admin'||((issue.orderIds?.length||issue.taskIds?.length)&& (issue.orderIds||[]).every(id=>canReadOrder(context.workspace,user,context.orderRules.get('orders',id)))&&(issue.taskIds||[]).every(id=>canReadConnection(context.workspace,user,context.orderRules.get('execution-tasks',id)?.connectionId)))).slice(-50).map(i=>{const linked=context.workspace?.businessIssue?.(i.id);return pick(linked?{...i,status:linked.status,owner:linked.owner,exceptionId:linked.id}:i,['id','status','type','message','error','component','notificationMode','owner','owners','exceptionId','createdAt','batchId','orderIds','taskIds']);}).filter(i=>!['resolved','retired'].includes(i.status));
|
||||
result.templateUsage=context.orderRules.all('rules').map(r=>({categoryId:r.published?.categoryId||r.draft?.categoryId,name:r.draft?.name,templateId:r.published?.bodyTemplateId||'',huizhouEnabled:r.published?.huizhouEnabled===true,huizhouTemplateId:r.published?.huizhouTemplateId||'',legacyBinding:!!r.published&&r.published.bodyTemplateId===undefined,publishedVersion:r.published?.version||null,status:r.published?.status||'draft'}));
|
||||
result.revision=crypto.createHash('sha256').update(publicRevision(context,user)+JSON.stringify([result.window,result.issues])).digest('hex').slice(0,24);
|
||||
return result;
|
||||
}
|
||||
|
||||
@@ -7,6 +7,8 @@ const {applyBodyTemplate}=require('./template.cjs');
|
||||
const {fail,validateRule,publicationIssues}=require('./validation.cjs');
|
||||
const {windowForCutoff,upcomingWindow,inWindow}=require('./window.cjs');
|
||||
const {matchesScope,scopesOverlap}=require('./scopes.cjs');
|
||||
const {initialNotification,ordersForMode}=require('./huizhou.cjs');
|
||||
const {modeOf,delivery,updateDelivery}=require('./delivery.cjs');
|
||||
const canonical=value=>Array.isArray(value)?value.map(canonical):value&&typeof value==='object'?Object.fromEntries(Object.keys(value).sort().map(k=>[k,canonical(value[k])])):value;
|
||||
const digest=value=>crypto.createHash('sha256').update(JSON.stringify(canonical(value))).digest('hex');
|
||||
const copy=value=>structuredClone(value);
|
||||
@@ -133,6 +135,7 @@ class RuleStore{
|
||||
const result=previewMatch(active,this.adapters(),sample),rule=active.find(r=>r.id===result.ruleId);
|
||||
const ready=this.providersReady(),enabled=rule?.status==='enabled';
|
||||
const order={id,sourceHash,event:result.event||copy(sample),sample:copy(sample),ruleSnapshot:rule?copy(rule):null,categoryId:result.categoryId||rule?.categoryId||'',status:result.valid&&ready&&enabled?'identified':'blocked',error:result.valid?(!enabled?'该类别规则已暂停。':ready?null:'待办接入、PDF 导出和自动归档待联调。'):result.issues.join(';'),ingestedAt:this.now(),updatedAt:this.now(),archive:null,batchId:null,trace:result};
|
||||
order.notifications={huizhou:initialNotification(rule,order.event)};
|
||||
const window=upcomingWindow(this.clock(),this.schedule(),this.calendar());
|
||||
if(window&&validDate(sample.receivedAt)&&Date.parse(sample.receivedAt)<Date.parse(window.start)){order.status='ignored';order.error='早于当前处理时段的历史订单,不归档、不补发。';}
|
||||
const frozen=this.all('batches').find(b=>b.categoryId===order.categoryId&&b.window&&inWindow(sample.receivedAt,b.window));
|
||||
@@ -177,6 +180,7 @@ class RuleStore{
|
||||
const result=previewMatch(published,this.adapters(),order.sample),rule=published.find(r=>r.id===result.ruleId);
|
||||
if(!result.valid||rule?.status!=='enabled')fail(result.issues.join(';')||'对应规则尚未启用。',409);
|
||||
order.event=result.event;order.ruleSnapshot=copy(rule);order.categoryId=rule.categoryId;order.trace=result;
|
||||
if(order.notifications)order.notifications.huizhou=initialNotification(rule,order.event);
|
||||
require('./migrations.cjs').invalidateArchive(order);order.status=this.providersReady()?'identified':'blocked';
|
||||
order.error=order.status==='blocked'?'待办接入、PDF 导出和自动归档待联调。':null;order.updatedAt=this.now();
|
||||
this.put('orders',order);require('./migrations.cjs').synchronizeTasks(this,order);this.audit(actor,'应用当前规则重新识别',id+':'+input.note.trim());return order;
|
||||
@@ -199,10 +203,10 @@ class RuleStore{
|
||||
return blockers;
|
||||
}
|
||||
categoryIncomplete(categoryId,window){
|
||||
return this.all('execution-tasks').some(task=>task.categoryIds?.includes(categoryId)&&(!Number.isFinite(Date.parse(task.row?.receivedAt))||inWindow(task.row?.receivedAt,window))&&(task.conflict||['identified','blocked','failed','unknown','capturing','archiving'].includes(task.status)||task.runtimeCheck?.status==='blocked'));
|
||||
return this.all('execution-tasks').some(task=>task.categoryIds?.includes(categoryId)&&(!Number.isFinite(Date.parse(task.row?.receivedAt))||inWindow(task.row?.receivedAt,window))&&(task.conflict||['identified','blocked','failed','capturing','archiving'].includes(task.status)||task.status==='unknown'&&task.step!=='complete'||task.runtimeCheck?.status==='blocked'));
|
||||
}
|
||||
batchIncomplete(batch){
|
||||
return this.all('execution-tasks').some(task=>batch.orderIds.includes(task.orderId)&&(task.conflict||task.runtimeCheck?.status==='blocked'||['failed','unknown','capturing','archiving'].includes(task.status)));
|
||||
return this.all('execution-tasks').some(task=>batch.orderIds.includes(task.orderId)&&(task.conflict||task.runtimeCheck?.status==='blocked'||['failed','capturing','archiving'].includes(task.status)||task.status==='unknown'&&task.step!=='complete'));
|
||||
}
|
||||
issueOwners(input){
|
||||
const orderIds=input.orderIds||[];
|
||||
@@ -231,42 +235,55 @@ class RuleStore{
|
||||
const window=windowForCutoff(cutoff,this.schedule(),this.calendar());
|
||||
if(requestedWindow&&(requestedWindow.start!==window.start||requestedWindow.end!==window.end))fail('发送时段与业务日历不一致。',409);
|
||||
const blockers=this.discoveryBlockers(cutoff);
|
||||
for(const record of this.all('rules').filter(r=>r.published?.status==='enabled')){const categoryId=record.published.categoryId,existing=this.all('batches').find(b=>b.categoryId===categoryId&&Date.parse(b.cutoff)===Date.parse(cutoff));this.put('window-results',{id:categoryId+':'+cutoff,categoryId,cutoff,status:existing?'frozen':blockers.length?'blocked':'empty',batchId:existing?.id||null,error:blockers.join(';')||null,updatedAt:this.now()});}
|
||||
const resultId=(category,mode)=>category+':'+cutoff+(mode==='normal'?'':':'+mode);
|
||||
const existingBatch=(category,mode)=>this.all('batches').find(b=>b.categoryId===category&&modeOf(b)===mode&&Date.parse(b.cutoff)===Date.parse(cutoff)&&!(b.status==='cancelled'&&b.resolution?.resolution==='retry'));
|
||||
for(const record of this.all('rules').filter(r=>r.published?.status==='enabled'))for(const mode of record.published.huizhouEnabled===true?['normal','huizhou']:['normal']){const categoryId=record.published.categoryId,existing=existingBatch(categoryId,mode);this.put('window-results',{id:resultId(categoryId,mode),categoryId,notificationMode:mode,cutoff,status:existing?'frozen':blockers.length?'blocked':'empty',batchId:existing?.id||null,error:blockers.join(';')||null,updatedAt:this.now()});}
|
||||
if(blockers.length)return [];
|
||||
const grouped=new Map(),batches=[];
|
||||
for(const order of this.all('orders')){
|
||||
if(!['identified','preparing','archived','pending','blocked'].includes(order.status)||!order.categoryId||order.blockedByBatchId)continue;
|
||||
for(const order of this.all('orders'))for(const mode of ['normal','huizhou']){
|
||||
const state=delivery(order,mode);
|
||||
if(!state||!['identified','preparing','archived','pending','blocked'].includes(state.status)||!order.categoryId||order.blockedByBatchId||order.missedWindow||order.status==='ignored')continue;
|
||||
if(mode==='huizhou'&&(order.ruleSnapshot?.huizhouEnabled!==true||(!state.orderNos?.length&&!state.issues?.length)))continue;
|
||||
const at=order.event.receivedAt||order.sample.receivedAt;
|
||||
if(validDate(at)&&Date.parse(at)<Date.parse(window.start)){this.recordIssue('missed:'+order.id,{component:'rules',error:'错过整理时点,等待人工处理。',orderIds:[order.id]});order.status='ignored';order.error='早于本时段的历史订单,不补发。';this.put('orders',order);continue;}
|
||||
if(validDate(at)&&Date.parse(at)<Date.parse(window.start)){this.recordIssue('missed:'+order.id+':'+mode,{component:'rules',notificationMode:mode,error:'错过整理时点,等待人工处理。',orderIds:[order.id]});updateDelivery(order,mode,{status:'ignored',error:'早于本时段的历史订单,不补发。'});this.put('orders',order);continue;}
|
||||
if(!inWindow(at,window))continue;
|
||||
if(!grouped.has(order.categoryId))grouped.set(order.categoryId,[]);grouped.get(order.categoryId).push(order);
|
||||
const key=order.categoryId+':'+mode;if(!grouped.has(key))grouped.set(key,{mode,orders:[]});grouped.get(key).orders.push(order);
|
||||
}
|
||||
for(const orders of grouped.values()){
|
||||
if(this.categoryIncomplete(orders[0].categoryId,window)){const categoryId=orders[0].categoryId,error='本类别存在未完成的采集、归档或核验任务。';this.put('window-results',{id:categoryId+':'+cutoff,categoryId,cutoff,status:'blocked',error,updatedAt:this.now()});this.recordIssue('build:'+categoryId+':'+cutoff,{component:'rules',error,cutoff,categoryId,orderIds:orders.map(o=>o.id)});continue;}
|
||||
for(const {mode,orders} of grouped.values()){
|
||||
const rule=orders[0].ruleSnapshot;if(!rule)continue;
|
||||
if(this.all('batches').some(b=>b.categoryId===rule.categoryId&&Date.parse(b.cutoff)===Date.parse(cutoff)&&!(b.status==='cancelled'&&b.resolution?.resolution==='retry')))continue;
|
||||
if(existingBatch(rule.categoryId,mode))continue;
|
||||
// Only a normal freeze produced by this dual-delivery flow may gain a late
|
||||
// companion after repairing a Hui-only blocker. Historical freezes stay closed.
|
||||
const normal=mode==='huizhou'&&existingBatch(rule.categoryId,'normal');
|
||||
if(normal&&normal.huizhouPlanned!==true)continue;
|
||||
const published=this.get('rules',rule.id)?.published;
|
||||
let error=!published||published.status!=='enabled'?'该类别规则已暂停。':null;
|
||||
if(!error&&orders.some(o=>o.status!=='pending'))error='本类别存在字段、文件或归档尚未准备完成的订单。';
|
||||
if(!error&&published.version!==rule.version)error='本类别订单规则版本已过期,请应用当前已发布规则后处理。';
|
||||
if(!error&&this.categoryIncomplete(rule.categoryId,window))error='本类别存在未完成的采集、归档或核验任务。';
|
||||
if(!error&&mode==='huizhou'&&orders.some(o=>delivery(o,mode).issues?.length))error=orders.flatMap(o=>delivery(o,mode).issues||[]).join(';');
|
||||
if(!error&&orders.some(o=>mode==='normal'?o.status!=='pending':!o.archive||!['pending','batched','sent','unknown'].includes(o.status)))error='本类别存在字段、文件或归档尚未准备完成的订单。';
|
||||
let snapshot;
|
||||
if(!error)try{snapshot=buildBatch(rule,orders,cutoff,{maxMessageBytes:this.settings().maxMessageBytes,window});snapshot=applyBodyTemplate(snapshot,this.templateResolver?.(rule.categoryId,rule),orders,this.settings().maxMessageBytes);}catch(cause){error=cause.message;}
|
||||
if(error){this.put('window-results',{id:rule.categoryId+':'+cutoff,categoryId:rule.categoryId,cutoff,status:'blocked',error,updatedAt:this.now()});this.recordIssue('build:'+rule.categoryId+':'+cutoff,{component:'rules',error,cutoff,categoryId:rule.categoryId,orderIds:orders.map(o=>o.id)});for(const order of orders){order.error=error;this.put('orders',order);}continue;}
|
||||
if(!error)try{const selected=ordersForMode(orders,mode);snapshot=buildBatch(rule,selected,cutoff,{maxMessageBytes:this.settings().maxMessageBytes,window,notificationMode:mode});snapshot=applyBodyTemplate(snapshot,this.templateResolver?.(rule.categoryId,rule,mode),selected,this.settings().maxMessageBytes);}catch(cause){error=cause.message;}
|
||||
const key=resultId(rule.categoryId,mode);
|
||||
if(error){this.put('window-results',{id:key,categoryId:rule.categoryId,notificationMode:mode,cutoff,status:'blocked',error,updatedAt:this.now()});this.recordIssue('build:'+key,{component:'rules',notificationMode:mode,error,cutoff,categoryId:rule.categoryId,orderIds:orders.map(o=>o.id)});for(const original of orders){const order=this.get('orders',original.id);updateDelivery(order,mode,{error,...(mode==='huizhou'?{status:'blocked'}:{})});this.put('orders',order);}continue;}
|
||||
const batch={...snapshot,id:crypto.randomUUID(),version:1,status:'prepared',createdAt:this.now(),ruleSnapshot:copy(rule),channelId:this.settings().channelId,error:null};
|
||||
this.put('batches',batch);this.put('window-results',{id:rule.categoryId+':'+cutoff,categoryId:rule.categoryId,cutoff,status:'frozen',batchId:batch.id,updatedAt:this.now()});
|
||||
const issue=this.get('business-issues','build:'+rule.categoryId+':'+cutoff);if(issue)this.put('business-issues',{...issue,status:'awaiting_verification',updatedAt:this.now()});
|
||||
for(const order of orders){order.status=transition('order',order.status,'batch');order.batchId=batch.id;order.error=null;order.updatedAt=this.now();this.put('orders',order);}
|
||||
if(mode==='normal')batch.huizhouPlanned=rule.huizhouEnabled===true&&orders.some(order=>!!order.notifications?.huizhou);
|
||||
this.put('batches',batch);this.put('window-results',{id:key,categoryId:rule.categoryId,notificationMode:mode,cutoff,status:'frozen',batchId:batch.id,updatedAt:this.now()});
|
||||
const issue=this.get('business-issues','build:'+key);if(issue)this.put('business-issues',{...issue,status:'awaiting_verification',updatedAt:this.now()});
|
||||
for(const original of orders){const order=this.get('orders',original.id);updateDelivery(order,mode,{status:mode==='normal'?transition('order',order.status,'batch'):'batched',batchId:batch.id,error:null});order.updatedAt=this.now();this.put('orders',order);}
|
||||
this.audit(actor,'固定分类邮件批次',batch.id+' '+orders.length+'单');batches.push(batch);
|
||||
}
|
||||
return batches;
|
||||
});}
|
||||
updateBatchOrders(batch,status,error=null){for(const id of batch.orderIds){const order=this.get('orders',id);if(order?.batchId===batch.id){order.status=status;order.error=error;order.updatedAt=this.now();this.put('orders',order);}}}
|
||||
updateBatchOrders(batch,status,error=null){for(const id of batch.orderIds){const order=this.get('orders',id),mode=modeOf(batch);if(delivery(order,mode)?.batchId===batch.id){updateDelivery(order,mode,{status,error});order.updatedAt=this.now();this.put('orders',order);}}}
|
||||
releaseBatchOrders(batch){for(const id of batch.orderIds){const order=this.get('orders',id),mode=modeOf(batch);if(delivery(order,mode)?.batchId===batch.id){updateDelivery(order,mode,{batchId:null});this.put('orders',order);}}}
|
||||
beginSending(id,{manual=false}={}){return this.transaction(()=>{
|
||||
const batch=this.get('batches',id);if(!batch)fail('批次不存在。',404);
|
||||
if(!(manual&&batch.manual)&&this.get('rules',batch.ruleSnapshot.id)?.published?.status!=='enabled')fail('该类别规则已暂停,批次不能进入发送。',409);
|
||||
if(!(manual&&batch.manual)&&(this.discoveryBlockers(batch.cutoff).length||this.batchIncomplete(batch)))throw Object.assign(Error('待办扫描或类别订单尚不完整,等待完整扫描与恢复。'),{status:409,code:'DISCOVERY_INCOMPLETE'});
|
||||
if(this.batchIncomplete(batch)||!(manual&&batch.manual)&&this.discoveryBlockers(batch.cutoff).length)throw Object.assign(Error('待办扫描或类别订单尚不完整,等待完整扫描与恢复。'),{status:409,code:'DISCOVERY_INCOMPLETE'});
|
||||
const orders=batch.orderIds.map(oid=>this.get('orders',oid));
|
||||
if(this.all('execution-tasks').some(task=>batch.orderIds.includes(task.orderId)&&task.runtimeCheck?.status==='blocked'))fail('已归档订单的运行条件复核未通过,批次不能进入发送。',409);
|
||||
if(orders.some(o=>!o||o.batchId!==id||o.status!=='batched'))fail('批次订单预留已变化。',409);
|
||||
if(orders.some(o=>!o||delivery(o,modeOf(batch))?.batchId!==id||delivery(o,modeOf(batch))?.status!=='batched'))fail('批次订单预留已变化。',409);
|
||||
batch.version=(batch.version||1)+1;batch.status=transition('batch',batch.status,'send');this.put('batches',batch);return batch;
|
||||
});}
|
||||
finishSending(id,status,message=null){return this.transaction(()=>{
|
||||
@@ -274,7 +291,7 @@ class RuleStore{
|
||||
if(!['sent','unknown','failed'].includes(status))fail('发送结果无效。');
|
||||
batch.version=(batch.version||1)+1;batch.status=transition('batch',batch.status,{sent:'sent',unknown:'unknown',failed:'fail'}[status]);batch.error=message;batch.finishedAt=this.now();this.put('batches',batch);
|
||||
this.updateBatchOrders(batch,status==='failed'?'pending':status,message);
|
||||
if(status==='failed')for(const oid of batch.orderIds){const order=this.get('orders',oid);if(order?.batchId===batch.id){order.batchId=null;this.put('orders',order);}}
|
||||
if(status==='failed')this.releaseBatchOrders(batch);
|
||||
if(['failed','unknown'].includes(status))this.recordIssue('batch:'+id,{component:'mail',batchId:id,error:message,orderIds:batch.orderIds});
|
||||
this.audit('系统发送','更新批次结果',id+' '+status);return batch;
|
||||
});}
|
||||
@@ -290,7 +307,7 @@ class RuleStore{
|
||||
if(!input||!['sent','retry'].includes(input.resolution)||typeof input.note!=='string'||input.note.trim().length<5||input.note.length>2000)fail('请选择核验结果并填写至少5字依据。');
|
||||
batch.version=(batch.version||1)+1;batch.status=transition('batch',batch.status,input.resolution==='sent'?'resolve_sent':'retry');batch.resolution={...input,actor,at:this.now()};if(input.resolution==='retry'){batch.status='failed';batch.error='人工已核验未发送,等待受控人工补发。';}this.put('batches',batch);
|
||||
this.updateBatchOrders(batch,input.resolution==='sent'?'sent':'pending',null);
|
||||
if(input.resolution==='retry')for(const oid of batch.orderIds){const order=this.get('orders',oid);if(order?.batchId===id){order.batchId=null;this.put('orders',order);}}
|
||||
if(input.resolution==='retry')this.releaseBatchOrders(batch);
|
||||
if(controlled)this.put('resolve-requests',{id:requestId,batchId:id,inputHash,at:this.now()});this.audit(actor,'核验分类邮件结果',id+':'+input.note.trim());return batch;
|
||||
});}
|
||||
close(){this.db.close();this.vault.destroy();}
|
||||
|
||||
@@ -4,6 +4,7 @@ const {fail}=require('./validation.cjs');
|
||||
const {mailContent,fileLink}=require('./mail-content.cjs');
|
||||
const has=(part,key)=>new RegExp('{{\\s*'+key+'\\s*}}').test(part||'');
|
||||
function applyBodyTemplate(snapshot,template,orders,maxMessageBytes){
|
||||
if(snapshot.notificationMode==='huizhou')return applyHuizhouTemplate(snapshot,template,orders,maxMessageBytes);
|
||||
if(!template)return snapshot;
|
||||
const listing=orders.map(order=>`${order.event.orderNo}\n${String(order.event.brief||'')}\n${order.archive.files.map(file=>file.path).join('\n')}`).join('\n\n');
|
||||
const content=mailContent(orders),category=orders[0]?.ruleSnapshot?.name||'';
|
||||
@@ -28,4 +29,17 @@ function applyBodyTemplate(snapshot,template,orders,maxMessageBytes){
|
||||
if(bytes>maxMessageBytes)fail('关联模板展开后超过邮件容量限制。');
|
||||
return {...snapshot,text,html,template:{id:template.id,version:template.version,bindingVersion:template.bindingVersion}};
|
||||
}
|
||||
function applyHuizhouTemplate(snapshot,template,orders,maxMessageBytes){
|
||||
const rule=orders[0]?.ruleSnapshot;
|
||||
if(!template||!rule?.huizhouTemplateId||template.id!==rule.huizhouTemplateId||template.notificationMode!=='huizhou'||template.status!=='active')fail('惠州通知必须选择已确认且启用的惠州模板。',409);
|
||||
const content=mailContent(orders),details=content.details;
|
||||
const values={'产品线':[...new Set(orders.map(order=>order.event.productLine).filter(Boolean))].join('、'),'订单号':snapshot.orderNos.join('、'),'日期':new Intl.DateTimeFormat('en-CA',{timeZone:'Asia/Shanghai'}).format(new Date(snapshot.cutoff)),'订单列表':details,'订单明细':details,'存放地址':content.directories.join('\n'),'类别名称':rule.name||''};
|
||||
const rendered=renderTemplate({...template,attachments:[]},values);
|
||||
const subject=rendered.subject+(has(template.subject,'订单号')?'':' '+snapshot.orderNos.join('、'));
|
||||
const text=rendered.text+(['订单列表','订单明细'].some(key=>has(template.text,key))?'':'\n\n'+details);
|
||||
const html=template.html?rendered.html+(['订单列表','订单明细'].some(key=>has(template.html,key))?'':content.htmlDetails):'<div>'+escape(text).replace(/\r?\n/g,'<br>')+'</div>';
|
||||
const bytes=16384+Buffer.byteLength(text+html+subject)*2+(snapshot.attachments||[]).reduce((sum,file)=>sum+Math.ceil(file.size/3)*4+4096,0);
|
||||
if(bytes>maxMessageBytes)fail('关联模板展开后超过邮件容量限制。');
|
||||
return {...snapshot,subject,text,html,template:{id:template.id,version:template.version,bindingVersion:template.bindingVersion,notificationMode:'huizhou'}};
|
||||
}
|
||||
module.exports={applyBodyTemplate};
|
||||
@@ -7,7 +7,7 @@ function extractTitle(title){
|
||||
const raw=typeof title==='string'?title:'';
|
||||
const text=raw.replace(/<br\s*\/?\s*>/gi,'\n').replace(/ | | /gi,' ');
|
||||
const matches=[...text.matchAll(/(客户等级|毛利|订单号|机芯号|产品型号|客户简称|出货方式|总数量|订单类别|订单类型|业务模式)\s*[::]/gu)];
|
||||
const orders=[],factoryHints=[],issues=[];let current=null;
|
||||
const orders=[],factoryHints=[],issues=[];let current=null,pendingMode=null,pendingAmbiguous=false;
|
||||
for(let i=0;i<matches.length;i++){
|
||||
const match=matches[i],label=match[1],value=text.slice(match.index+match[0].length,matches[i+1]?.index??text.length).trim();
|
||||
if(['业务模式','客户简称'].includes(label)&&value.includes('惠州'))factoryHints.push({source:label,value,status:'待核实额外通知'});
|
||||
@@ -15,9 +15,21 @@ function extractTitle(title){
|
||||
// Unknown labels and pipe-separated titles still delimit the identifier.
|
||||
// Keep their original content in the notification paragraph below.
|
||||
const identifier=/^([A-Za-z0-9][A-Za-z0-9._/-]*)(?=$|\s|[\p{Script=Han}|,,;;])/u.exec(value)?.[1]||value;
|
||||
current={orderNo:identifier,text:''};orders.push(current);
|
||||
current={orderNo:identifier,text:''};if(pendingMode){current.businessMode=pendingMode;if(pendingAmbiguous)current.businessModeAmbiguous=true;pendingMode=null;pendingAmbiguous=false;}orders.push(current);
|
||||
if(!value)issues.push('标题中的订单号为空,不能遗漏该订单段落');
|
||||
}
|
||||
if(label==='业务模式'){
|
||||
const nextOrder=matches.findIndex((m,index)=>index>i&&m[1]==='订单号');
|
||||
const between=nextOrder<0?[]:matches.slice(i+1,nextOrder).map(m=>m[1]);
|
||||
// BPM starts the next paragraph with business mode + margin before its order number.
|
||||
// Ordinary summary text remains byte-for-byte compatible with the existing extractor.
|
||||
const startsParagraph=/[\n|]\s*$/.test(text.slice(0,match.index));
|
||||
if(!current||nextOrder>=0&&(between.includes('毛利')||startsParagraph)){
|
||||
if(pendingMode&&pendingMode!==value)pendingAmbiguous=true;
|
||||
pendingMode=value;
|
||||
}
|
||||
else if(current){if(current.businessMode&¤t.businessMode!==value)current.businessModeAmbiguous=true;current.businessMode=value;}
|
||||
}
|
||||
if(current&&retained.has(label)){current.text+=`${label}:${value}`;if(summaryKeys[label])current[summaryKeys[label]]=value;}
|
||||
}
|
||||
if(!orders.length)issues.push('标题中没有可识别的“订单号:”段落');
|
||||
|
||||
Reference in new issue
Block a user