refactor: separate notification distribution from field mapping
This commit is contained in:
1 parent
3748d05d96
commit
c53da6f025
25 files changed
+773
-118
No files matched your search
@@ -3,7 +3,7 @@ const {simpleParser}=require('mailparser');const sanitize=require('sanitize-html
|
||||
const MAX_MAIL=10*1024*1024;
|
||||
const fail=message=>{throw Object.assign(new Error(message),{status:400});};
|
||||
const escape=value=>String(value??'').replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));
|
||||
const VARIABLES=['产品线','订单号','日期','订单列表'];
|
||||
const VARIABLES=['产品线','订单号','日期','订单列表','订单明细','存放地址','类别名称'];
|
||||
function validateVariables(...parts){for(const part of parts)for(const token of String(part||'').matchAll(/{{([\s\S]*?)}}/g))if(!VARIABLES.includes(token[1].trim()))fail('模板含有不支持的变量,请使用:'+VARIABLES.map(x=>'{{'+x+'}}').join('、'));}
|
||||
function cleanHtml(html,attachments=[]){
|
||||
let expandedBytes=Buffer.byteLength(html||'');
|
||||
@@ -29,7 +29,7 @@ async function parseTemplate(raw,channel){
|
||||
}
|
||||
function renderTemplate(template,values){
|
||||
validateVariables(template.subject,template.text,template.html);
|
||||
const replace=(input,html)=>String(input||'').replace(/{{\s*(产品线|订单号|日期|订单列表)\s*}}/g,(_,key)=>{if(values[key]===undefined)fail('缺少模板变量:'+key);return html?escape(values[key]).replace(/\r?\n/g,'<br>'):String(values[key]);});
|
||||
const replace=(input,html)=>String(input||'').replace(/{{\s*(产品线|订单号|日期|订单列表|订单明细|存放地址|类别名称)\s*}}/g,(_,key)=>{if(values[key]===undefined)fail('缺少模板变量:'+key);return html?escape(values[key]).replace(/\r?\n/g,'<br>'):String(values[key]);});
|
||||
let html=template.html?replace(template.html,true):undefined;
|
||||
for(const a of template.attachments||[])if(html&&a.cid&&/^[A-Za-z0-9._@+-]{1,200}$/.test(a.cid))html=html.replaceAll('src="data:'+a.contentType+';base64,'+a.content+'"','src="cid:'+a.cid+'"');
|
||||
return {subject:replace(template.subject,false).replace(/[\r\n]/g,' '),text:replace(template.text,false),html};
|
||||
|
||||
@@ -27,7 +27,7 @@ class MailService{
|
||||
}finally{lock.release();}});
|
||||
this.store.setState(id,c.version,{imap:true,pollAt:new Date().toISOString(),message:`收信完成:新增 ${imported} 个模板,${rejected} 封未导入`});return {imported,rejected};
|
||||
}catch(error){if(error.status===409)throw error;const message=safeError(error,'IMAP');try{this.store.setState(id,c.version,{imap:false,pollAt:new Date().toISOString(),message});}catch{}fail(message);}});}
|
||||
sendTest(id,templateId){return this.exclusive(id,async()=>{const c=this.store.channelSecret(id);if(c.readOnly)fail('只读邮箱不能发送邮件。',409);const t=this.store.template(templateId);if(t.channelId!==id||t.status!=='active')fail('请选择此邮箱已确认生效的模板。',409);const values={'产品线':t.scope||'默认','订单号':'TEST','日期':new Intl.DateTimeFormat('en-CA',{timeZone:'Asia/Shanghai'}).format(new Date()),'订单列表':'测试订单 TEST'};const rendered=renderTemplate(t,values);const transport=this.smtpFactory(c.smtp);this.clients.add(transport);let sendId;try{await transport.verify();this.store.guard(id,c.version);sendId=this.store.beginSend(id,t.id);const result=await transport.sendMail({from:{address:c.email,name:c.name},to:{address:c.email},subject:'[测试] '+rendered.subject,text:rendered.text,html:rendered.html,messageId:`<${sendId}@${c.email.split('@')[1]}>`,disableFileAccess:true,disableUrlAccess:true,attachments:t.attachments.map(a=>({filename:a.filename,content:Buffer.from(a.content,'base64'),contentType:a.contentType,...(a.cid?{cid:a.cid}:{}),contentDisposition:a.inline?'inline':'attachment'}))});if(!result.accepted?.length)throw new Error('Recipient rejected');this.store.finishSend(sendId,'sent');return {id:sendId,status:'sent',to:c.email};}catch(e){if(sendId)this.store.finishSend(sendId,'unknown');if(e.status===409)throw e;fail(sendId?'发信结果待核对,请检查本邮箱后再决定是否重试。':safeError(e,'SMTP'));}finally{transport.close?.();this.clients.delete(transport);}});}
|
||||
sendTest(id,templateId){return this.exclusive(id,async()=>{const c=this.store.channelSecret(id);if(c.readOnly)fail('只读邮箱不能发送邮件。',409);const t=this.store.template(templateId);if(t.channelId!==id||t.status!=='active')fail('请选择此邮箱已确认生效的模板。',409);const values={'产品线':t.scope||'默认','订单号':'TEST','日期':new Intl.DateTimeFormat('en-CA',{timeZone:'Asia/Shanghai'}).format(new Date()),'订单列表':'测试订单 TEST','类别名称':'测试通知','订单明细':'订单号:TEST 机芯号:CORE 产品型号:MODEL 客户简称:示例 出货方式:CBU 总数量:1','存放地址':'示例归档目录(测试数据)'};const rendered=renderTemplate(t,values);const transport=this.smtpFactory(c.smtp);this.clients.add(transport);let sendId;try{await transport.verify();this.store.guard(id,c.version);sendId=this.store.beginSend(id,t.id);const result=await transport.sendMail({from:{address:c.email,name:c.name},to:{address:c.email},subject:'[测试] '+rendered.subject,text:rendered.text,html:rendered.html,messageId:`<${sendId}@${c.email.split('@')[1]}>`,disableFileAccess:true,disableUrlAccess:true,attachments:t.attachments.map(a=>({filename:a.filename,content:Buffer.from(a.content,'base64'),contentType:a.contentType,...(a.cid?{cid:a.cid}:{}),contentDisposition:a.inline?'inline':'attachment'}))});if(!result.accepted?.length)throw new Error('Recipient rejected');this.store.finishSend(sendId,'sent');return {id:sendId,status:'sent',to:c.email};}catch(e){if(sendId)this.store.finishSend(sendId,'unknown');if(e.status===409)throw e;fail(sendId?'发信结果待核对,请检查本邮箱后再决定是否重试。':safeError(e,'SMTP'));}finally{transport.close?.();this.clients.delete(transport);}});}
|
||||
start(){this.stopped=false;const tick=()=>{for(const c of this.store.channels())if(c.enabled&&!this.busy(c.id))this.poll(c.id).catch(()=>{});};this.timer=setInterval(tick,this.interval);this.timer.unref?.();this.startTimer=setTimeout(tick,2000);this.startTimer.unref?.();}
|
||||
async stop(){this.stopped=true;clearInterval(this.timer);clearTimeout(this.startTimer);for(const client of this.clients)try{client.close?.();}catch{}await Promise.allSettled([...this.running.values()]);}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
'use strict';
|
||||
const path=require('node:path');
|
||||
const {mailContent,fileLink}=require('./mail-content.cjs');
|
||||
const fail=message=>{throw Object.assign(new Error(message),{status:409});};
|
||||
const escape=value=>String(value??'').replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));
|
||||
const lines=value=>escape(value).replace(/\r?\n/g,'<br>');
|
||||
@@ -17,11 +18,6 @@ function recipients(values,label){
|
||||
return result;
|
||||
}
|
||||
|
||||
function fileLink(filePath){
|
||||
if(filePath.startsWith('\\\\'))return 'file://'+filePath.slice(2).split('\\').map(encodeURIComponent).join('/');
|
||||
if(/^[a-z]:[\\/]/i.test(filePath))return 'file:///'+filePath.replace(/\\/g,'/').split('/').map((p,i)=>i===0?p:encodeURIComponent(p)).join('/');
|
||||
return 'file://'+filePath.split('/').map(encodeURIComponent).join('/');
|
||||
}
|
||||
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);
|
||||
}
|
||||
@@ -57,6 +53,11 @@ function buildBatch(rule,orders,cutoff,{maxMessageBytes=20971520,window}={}){
|
||||
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'){
|
||||
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>';
|
||||
}
|
||||
if(window){snapshot.window=structuredClone(window);snapshot.windowStart=new Date(start).toISOString();snapshot.windowEnd=new Date(end).toISOString();}
|
||||
// MIME headers, encoded-word subjects, base64 wrapping, attachment metadata and
|
||||
// boundary overhead are intentionally overestimated rather than truncating.
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
'use strict';
|
||||
const path=require('node:path');
|
||||
const {escape}=require('../mail/parser.cjs');
|
||||
const lines=value=>escape(value).replace(/\r?\n/g,'<br>');
|
||||
function fileLink(filePath){
|
||||
if(filePath.startsWith('\\\\'))return 'file://'+filePath.slice(2).split('\\').map(encodeURIComponent).join('/');
|
||||
if(/^[a-z]:[\\/]/i.test(filePath))return 'file:///'+filePath.replace(/\\/g,'/').split('/').map((p,i)=>i===0?p:encodeURIComponent(p)).join('/');
|
||||
return 'file://'+filePath.split('/').map(encodeURIComponent).join('/');
|
||||
}
|
||||
// Content is derived from the event and its recorded archive, never current configuration.
|
||||
function mailContent(orders){
|
||||
const details=orders.map(order=>order.event.titleOrders?.length&&order.event.titleOrders.every(row=>typeof row.text==='string'&&row.text.trim())?order.event.titleOrders.map(row=>row.text).join('\n\n'):String(order.event.brief||'')).join('\n\n');
|
||||
const seen=new Set(),directories=[];
|
||||
for(const order of orders)for(const file of order.archive.files){
|
||||
const windows=path.win32.isAbsolute(file.path),directory=(windows?path.win32:path.posix).dirname(file.path),key=windows?directory.toLowerCase():directory;
|
||||
if(!seen.has(key)){seen.add(key);directories.push(directory);}
|
||||
}
|
||||
return {details,directories,htmlDetails:'<div style="color:#0000ff">'+lines(details)+'</div>',htmlDirectories:'<div>存放地址:<br>'+directories.map(directory=>'<a style="color:#0000ff" href="'+escape(fileLink(directory))+'">'+escape(directory)+'</a>').join('<br>')+'</div>'};
|
||||
}
|
||||
module.exports={mailContent,fileLink};
|
||||
@@ -1,18 +1,29 @@
|
||||
'use strict';
|
||||
const {renderTemplate}=require('../mail/parser.cjs');
|
||||
const {renderTemplate,escape}=require('../mail/parser.cjs');
|
||||
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(!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 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)),'订单列表':listing};
|
||||
const content=mailContent(orders),category=orders[0]?.ruleSnapshot?.name||'';
|
||||
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)),'订单列表':listing,'订单明细':content.details,'存放地址':content.directories.join('\n'),'类别名称':category};
|
||||
const rendered=renderTemplate({...template,attachments:[]},values);
|
||||
// The frozen mandatory order summary and archive links remain complete even
|
||||
// when a mail author omitted the list variable from a custom template.
|
||||
const text=rendered.text+(/{{\s*订单列表\s*}}/.test(template.text||'')?'':'\n\n'+listing);
|
||||
const token='ORDER_LIST_'+require('node:crypto').randomUUID();
|
||||
const htmlList=snapshot.html.match(/<ul>[\s\S]*<\/ul>/)?.[0]||snapshot.html;
|
||||
const formatted=template.html?renderTemplate({...template,attachments:[]},{...values,'订单列表':token}).html?.replaceAll(token,htmlList):null;
|
||||
const html=formatted?formatted+(/{{\s*订单列表\s*}}/.test(template.html||'')?'':htmlList):snapshot.html;
|
||||
const business=snapshot.categoryId==='overseas-notice'||['订单明细','存放地址'].some(key=>has(template.text,key)||has(template.html,key));
|
||||
let text=rendered.text,html=snapshot.html;
|
||||
// Omitted variables must not silently drop mandatory summaries or archive locations.
|
||||
if(!has(template.text,'订单列表')){
|
||||
if(business){if(!has(template.text,'订单明细'))text+='\n\n'+content.details;if(!has(template.text,'存放地址'))text+='\n\n存放地址:'+content.directories.join('\n');}
|
||||
else text+='\n\n'+listing;
|
||||
}
|
||||
if(template.html){
|
||||
if(has(template.html,'订单列表')){
|
||||
const legacy=snapshot.categoryId==='overseas-notice'?'<ul>'+orders.map(order=>'<li><strong>'+escape(order.event.orderNo)+'</strong><br><span style="color:#0000ff">'+escape(order.event.brief).replace(/\r?\n/g,'<br>')+'</span><br>'+order.archive.files.map(file=>'<a style="color:#0000ff" href="'+escape(fileLink(file.path))+'">'+escape(file.path)+'</a>').join('<br>')+'</li>').join('')+'</ul>':snapshot.html.match(/<ul>[\s\S]*<\/ul>/)?.[0]||snapshot.html;
|
||||
const token='ORDER_LIST_'+require('node:crypto').randomUUID();
|
||||
html=renderTemplate({...template,attachments:[]},{...values,'订单列表':token}).html.replaceAll(token,legacy);
|
||||
}else if(business){html=rendered.html+(has(template.html,'订单明细')?'':content.htmlDetails)+(has(template.html,'存放地址')?'':content.htmlDirectories);}
|
||||
else html=rendered.html+(snapshot.html.match(/<ul>[\s\S]*<\/ul>/)?.[0]||snapshot.html);
|
||||
}
|
||||
const bytes=16384+Buffer.byteLength(text+html+snapshot.subject)*2+(snapshot.attachments||[]).reduce((sum,file)=>sum+Math.ceil(file.size/3)*4+4096,0);
|
||||
if(bytes>maxMessageBytes)fail('关联模板展开后超过邮件容量限制。');
|
||||
return {...snapshot,text,html,template:{id:template.id,version:template.version,bindingVersion:template.bindingVersion}};
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
'use strict';
|
||||
|
||||
// Fixed field boundaries keep extraction deterministic; raw title stays on the event.
|
||||
const retained=new Set(['订单号','机芯号','产品型号','客户简称','总数量','订单类别']);
|
||||
const summaryKeys={'机芯号':'coreNo','产品型号':'productModel','客户简称':'customerShort','出货方式':'shippingMethod','总数量':'totalQuantity','订单类别':'orderCategory'};
|
||||
const retained=new Set(['订单号',...Object.keys(summaryKeys)]);
|
||||
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 matches=[...text.matchAll(/(客户等级|毛利|订单号|机芯号|产品型号|客户简称|出货方式|总数量|订单类别|订单类型|业务模式)\s*[::]/gu)];
|
||||
const orders=[],factoryHints=[],issues=[];let current=null;
|
||||
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();
|
||||
@@ -17,7 +18,7 @@ function extractTitle(title){
|
||||
current={orderNo:identifier,text:''};orders.push(current);
|
||||
if(!value)issues.push('标题中的订单号为空,不能遗漏该订单段落');
|
||||
}
|
||||
if(current&&retained.has(label))current.text+=`${label}:${value}`;
|
||||
if(current&&retained.has(label)){current.text+=`${label}:${value}`;if(summaryKeys[label])current[summaryKeys[label]]=value;}
|
||||
}
|
||||
if(!orders.length)issues.push('标题中没有可识别的“订单号:”段落');
|
||||
return {rawTitle:raw,orders,brief:orders.map(order=>order.text).join('\n'),factoryHints,issues};
|
||||
|
||||
Reference in new issue
Block a user