feat: edit HTML templates and freeze sender account signatures

This commit is contained in:
abaishu0730 committed 2026-10-23 18:19:34 +08:00
1 parent 61f561a842
commit 97e06328c3
24 files changed
+215 -29

No files matched your search

+16 -2
View File
@@ -20,11 +20,25 @@ async function mailApi({mail,workspace,user,route,method,body,request,response,r
const result=await mail.history(match[1],body);audit('mail.history.read',store.publicChannel(match[1]).name+' · '+String(body.action));reply(200,result);return true;
}
if(mail.historyOnly&&method==='POST')fail('此空间仅允许查询历史邮件,不能发信或收取模板。',409);
const publicTemplate=t=>{const {raw,attachments,...detail}=t;return {...detail,hasSource:!!raw,attachments:attachments.map(({content,...a})=>a)};};
if(route==='/api/mail/preview'&&method==='POST'){
if(!body||Object.keys(body).some(k=>!['format','body'].includes(k)))fail('预览参数无效。',400);
const content=require('./content.cjs').normalizeBody(body),html=content.html||'<pre>'+escape(content.text)+'</pre>',id=require('node:crypto').randomUUID(),now=Date.now(),previews=mail.editorPreviews||(mail.editorPreviews=new Map());
for(const [key,item]of previews)if(item.expiresAt<=now)previews.delete(key);while(previews.size>=20)previews.delete(previews.keys().next().value);
previews.set(id,{owner:user.username,html,expiresAt:now+5*60000});reply(200,{text:content.text,html,previewUrl:'/api/mail/previews/'+id});return true;
}
const preview=/^\/api\/mail\/previews\/([\w-]+)$/.exec(route);
if(preview&&method==='GET'){
if(user.role!=='admin')fail('仅管理员可查看编辑中的预览。',403);const item=mail.editorPreviews?.get(preview[1]);if(!item||item.owner!==user.username||item.expiresAt<=Date.now()){if(item?.expiresAt<=Date.now())mail.editorPreviews.delete(preview[1]);fail('预览已过期,请重新点击预览。',404);}
response.writeHead(200,{'Content-Type':'text/html; charset=utf-8','Content-Security-Policy':"default-src 'none'; img-src data:; style-src 'unsafe-inline'; sandbox; base-uri 'none'; form-action 'none'; frame-ancestors 'self'"});response.end(require('./content.cjs').previewDocument(item.html));return true;
}
if(route==='/api/mail/templates'&&method==='POST'){const saved=store.saveTemplate(null,body,user.username);audit('mail.template.create',saved.subject);reply(201,publicTemplate(saved));return true;}
match=/^\/api\/mail\/channels\/([\w-]+)\/(verify|poll|test)$/.exec(route);
if(match&&method==='POST'){const [,id,action]=match;let result;if(action==='test'){if(typeof body.templateId!=='string')fail('请选择已生效模板。',400);result=await mail.sendTest(id,body.templateId);}else result=await mail[action](id);audit('mail.'+action,store.publicChannel(id).name);reply(200,result);return true;}
match=/^\/api\/mail\/templates\/([\w-]+)(?:\/(confirm|reject|preview|source|attachments\/([0-9]+)))?$/.exec(route);
match=/^\/api\/mail\/templates\/([\w-]+)(?:\/(confirm|reject|preview|save|source|attachments\/([0-9]+)))?$/.exec(route);
if(match){const [,id,action,index]=match;const template=store.template(id);
if(method==='GET'&&!action){const {raw,attachments,...detail}=template;reply(200,{...detail,attachments:attachments.map(({content,...a})=>a)});return true;}
if(method==='GET'&&!action){reply(200,publicTemplate(template));return true;}
if(method==='POST'&&action==='save'){const saved=store.saveTemplate(id,body,user.username);audit('mail.template.edit',saved.subject);reply(200,publicTemplate(saved));return true;}
if(method==='GET'&&action==='preview'){
response.setHeader('Content-Security-Policy',"default-src 'none'; img-src data:; style-src 'unsafe-inline'; sandbox; base-uri 'none'; form-action 'none'");
response.writeHead(200,{'Content-Type':'text/html; charset=utf-8'});response.end('<!doctype html><html lang="zh-CN"><meta charset="utf-8"><style>body{font:14px/1.7 system-ui,sans-serif;padding:16px;color:#182433;overflow-wrap:anywhere}img{max-width:100%;height:auto}table{border-collapse:collapse;max-width:100%}td,th{padding:6px;border:1px solid #ddd}pre{white-space:pre-wrap}</style><body>'+(template.html||'<pre>'+escape(template.text)+'</pre>')+'</body></html>');return true;
+24
View File
@@ -0,0 +1,24 @@
'use strict';
const {convert}=require('html-to-text');
const {cleanHtml,escape}=require('./parser.cjs');
const fail=message=>{throw Object.assign(Error(message),{status:400});};
function normalizeBody({format,body},attachments=[]){
if(!['text','html'].includes(format)||typeof body!=='string'||body.length>(format==='html'?1048576:200000)||/[\x00-\x08\x0b\x0c\x0e-\x1f]/.test(body))fail('正文格式或长度无效。');
if(format==='text'){if(!body.trim())fail('正文不能为空。');return {format,text:body,html:'',body};}
const html=cleanHtml(body,attachments),text=convert(html,{wordwrap:false,selectors:[{selector:'a',options:{ignoreHref:true}},{selector:'img',format:'skip'}]});
if(!text.trim()&&!/<img\s/i.test(html))fail('HTML正文清理后为空,请填写有效内容。');
return {format,body:html,text,html};
}
function normalizeSignature(input){
if(!input||Object.keys(input).some(k=>!['enabled','format','body'].includes(k))||typeof input.enabled!=='boolean'||typeof input.body!=='string'||input.body.length>50000||!['text','html'].includes(input.format)||/{{|}}/.test(input.body))fail('签名格式无效;请填写固定内容,不使用订单变量。');
if(!input.body.trim()){if(input.enabled)fail('开启签名时请填写签名内容。');return {...input,text:'',html:''};}
return {...normalizeBody(input),enabled:input.enabled};
}
function appendSignature(snapshot,signature,maxMessageBytes=20971520){
if(snapshot.signature||!signature?.enabled)return snapshot;
const text=String(snapshot.text||'')+'\n\n'+signature.text,html=(snapshot.html||'<div>'+escape(snapshot.text).replace(/\r?\n/g,'<br>')+'</div>')+'<div style="margin-top:16px">'+(signature.html||escape(signature.text).replace(/\r?\n/g,'<br>'))+'</div>';
if(16384+Buffer.byteLength(text+html+String(snapshot.subject||''))*2>maxMessageBytes)throw Object.assign(Error('包含邮箱签名的邮件超过容量限制。'),{status:409});
return {...snapshot,text,html,signature:{channelId:signature.channelId,version:signature.version,format:signature.format,text:signature.text,html:signature.html}};
}
const previewDocument=html=>'<!doctype html><html lang="zh-CN"><meta charset="utf-8"><style>body{font:14px/1.7 system-ui,sans-serif;padding:16px;color:#182433;overflow-wrap:anywhere}img{max-width:100%;height:auto}table{border-collapse:collapse;max-width:100%}td,th{padding:6px;border:1px solid #ddd}pre{white-space:pre-wrap}</style><body>'+html+'</body></html>';
module.exports={normalizeBody,normalizeSignature,appendSignature,previewDocument};
+1 -1
View File
@@ -41,7 +41,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','类别名称':'测试通知','订单明细':'订单号: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);}});}
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=require('./content.cjs').appendSignature(renderTemplate(t,values),{...c.signature,channelId:c.id,version:c.version});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()]);}
}
+23 -1
View File
@@ -42,6 +42,7 @@ class MailStore{
if(!readOnly&&(typeof input.enabled!=='boolean'||!Array.isArray(input.senders)||!input.senders.length||input.senders.length>100))fail('请填写模板发件人名单,并选择是否启用收信。');
const endpoint=kind=>{const v=input[kind];if(!v||!['tls','starttls'].includes(v.security)||!Number.isInteger(v.port)||v.port<1||v.port>65535)fail(kind.toUpperCase()+' 端口或加密方式无效。');const host=text(v.host,'服务器地址',253);if(!/^[a-zA-Z0-9.:-]+$/.test(host)||host.startsWith('-'))fail('服务器地址只填写主机名或 IP。');const password=v.password===''&&old?old[kind]?.password:v.password;if(typeof password!=='string'||!password||password.length>2048)fail('请输入 '+kind.toUpperCase()+' 密码或授权码。');const user=text(v.user,'登录账号',254);if(old&&v.password===''&&(old.email!==address||old[kind].user!==user||old[kind].host!==host))fail('更换邮箱、服务器或登录账号时,请重新填写密码。');return {host,port:v.port,security:v.security,user,password};};
const saved={name:text(input.name,'邮箱名称',80),email:address,readOnly,smtp:readOnly?{}:endpoint('smtp'),imap:endpoint('imap'),senders:readOnly?[]:[...new Set(input.senders.map(email))],enabled:readOnly?false:input.enabled,createdAt:old?.createdAt||at(),updatedAt:at()};
if(input.signature!==undefined)saved.signature=require('./content.cjs').normalizeSignature(input.signature);else if(old?.signature)saved.signature=old.signature;
const reset=!old||old.email!==address||JSON.stringify(old.imap)!==JSON.stringify(saved.imap);const oldrow=old?this.row(id):null;
const changed=reset||JSON.stringify(old?.smtp)!==JSON.stringify(saved.smtp);const state=changed?{checkedAt:null,smtp:false,imap:false,pollAt:null,message:'待检查连接'}:JSON.parse(oldrow.state);
this.db.prepare('INSERT INTO channels VALUES(?,?,?,?,?,?) ON CONFLICT(id) DO UPDATE SET email=excluded.email,version=excluded.version,payload=excluded.payload,state=excluded.state,cursor=excluded.cursor').run(id,address,(old?.version||0)+1,this.encode(id,saved),JSON.stringify(state),reset?'{}':oldrow.cursor);return this.publicChannel(id);
@@ -59,6 +60,27 @@ class MailStore{
this.receipt(channelId,epoch,uid,old?'duplicate':'pending',old?'已识别,未重复导入':'待确认模板');this.advance(channelId,epoch,uid);return {...this.template(id),created:!old};
});}
template(id){const r=this.db.prepare('SELECT * FROM templates WHERE id=?').get(id);if(!r)fail('模板不存在。',404);return {...this.decode(id,r.payload),id:r.id,channelId:r.channel_id,scope:r.scope,notificationMode:r.notification_mode,status:r.status,version:r.version,baseId:r.base_id,createdAt:r.created_at};}
signature(id){const c=this.channelSecret(id);return {channelId:c.id,version:c.version,...(c.signature||{enabled:false,format:'text',body:'',text:'',html:''})};}
saveTemplate(id,input,actor){return this.transaction(()=>{
if(!input||typeof input!=='object'||Array.isArray(input)||Object.keys(input).some(k=>!['version','channelId','subject','scope','notificationMode','format','body'].includes(k)))fail('模板编辑参数无效。');
const previous=id?this.template(id):null;if(previous&&(!['pending','active'].includes(previous.status)||input.version!==previous.version))fail('模板版本已变化或属于历史版本,请刷新或复制后编辑。',409);
const channelId=previous?.channelId==='legacy'?input.channelId:previous?.channelId||input.channelId;
if(previous&&previous.channelId!=='legacy'&&input.channelId!==undefined&&input.channelId!==channelId)fail('现有模板不能更换邮箱,请复制后编辑。',409);
if(this.channelSecret(channelId).readOnly)fail('只读邮箱不能维护发信模板。',409);
const subject=text(input.subject,'邮件标题',300),scope=typeof input.scope==='string'?input.scope.trim():null,mode=input.notificationMode;
if(scope===null||scope.length>80||/[\[\]\x00-\x1f]/.test(scope)||!['normal','huizhou'].includes(mode))fail('产品线或通知模式无效。');
if(previous?.status==='active'&&previous.notificationMode!==mode)fail('已生效模板不能改变通知模式,请复制为新模板。',409);
const content=require('./content.cjs').normalizeBody(input,previous?.attachments||[]);validateVariables(subject,content.text,content.html);
const current=this.activeId(channelId,scope,mode);if(previous?.status==='active'&&current&&current!==id)fail('该范围已有其他生效模板,请更换范围。',409);
const payload={...(previous||{}),...content,bodyFormat:content.format,subject,scope,notificationMode:mode,attachments:previous?.attachments||[],sender:previous?.sender||actor+'(页面编辑)',sourceSubject:previous?.sourceSubject||subject,editedBy:actor,editedAt:at()};delete payload.id;
if(previous?.status==='pending'||!previous)payload.notificationBaseIds={normal:this.activeId(channelId,scope),huizhou:this.activeId(channelId,scope,'huizhou')};
if(!previous){id=crypto.randomUUID();this.db.prepare('INSERT INTO templates(id,channel_id,source_key,scope,status,version,base_id,payload,created_at,summary,notification_mode) VALUES(?,?,?,?,?,?,?,?,?,?,?)').run(id,channelId,'manual:'+id,scope,'pending',1,payload.notificationBaseIds[mode],this.encode(id,payload),at(),this.summary(payload),mode);}
else{
if(previous.status==='active'){const historyId=crypto.randomUUID();this.db.prepare('INSERT INTO templates(id,channel_id,source_key,scope,status,version,base_id,payload,created_at,summary,notification_mode) VALUES(?,?,?,?,?,?,?,?,?,?,?)').run(historyId,previous.channelId,'revision:'+id+':'+previous.version,previous.scope,'archived',previous.version,id,this.encode(historyId,previous),at(),this.summary(previous),previous.notificationMode);}
this.db.prepare('UPDATE templates SET channel_id=?,scope=?,notification_mode=?,version=version+1,payload=?,summary=? WHERE id=?').run(channelId,scope,mode,this.encode(id,payload),this.summary(payload),id);
}
return this.template(id);
});}
templates(){return ['pending','active','archived','rejected'].flatMap(status=>this.db.prepare('SELECT id,channel_id,scope,notification_mode,status,version,created_at,summary FROM templates WHERE status=? ORDER BY created_at DESC,rowid DESC LIMIT 200').all(status).map(r=>({...JSON.parse(r.summary),id:r.id,channelId:r.channel_id,scope:r.scope,notificationMode:r.notification_mode,status:r.status,version:r.version,createdAt:r.created_at})));}
stats(){return Object.fromEntries(this.db.prepare('SELECT status,COUNT(*) AS count FROM templates GROUP BY status').all().map(r=>[r.status,r.count]));}
categoryBindings(){return JSON.parse(this.db.prepare("SELECT value FROM meta WHERE key='categoryBindings'").get()?.value||'[]');}
@@ -75,7 +97,7 @@ class MailStore{
activeId(channelId,scope,mode='normal'){return this.db.prepare("SELECT id FROM templates WHERE channel_id=? AND scope=? AND notification_mode=? AND status='active'").get(channelId,scope,mode)?.id||null;}
active(channelId,scope,mode='normal'){const id=this.activeId(channelId,scope,mode);return id?this.template(id):null;}
confirm(id,input,actor){return this.transaction(()=>{const t=this.template(id);if(t.status!=='pending'||input.version!==t.version)fail('模板状态已变化,请刷新。',409);const notificationMode=input.notificationMode===undefined?'normal':input.notificationMode;if(!['normal','huizhou'].includes(notificationMode))fail('通知模式无效。');if(t.channelId==='legacy'){this.row(input.channelId);t.channelId=input.channelId;}const subject=text(input.subject,'邮件标题',300);if(typeof input.scope!=='string'||input.scope.length>80||/[\[\]\x00-\x1f]/.test(input.scope))fail('产品线格式无效。');const scope=input.scope.trim(),current=this.activeId(t.channelId,scope,notificationMode),base=t.notificationBaseIds?.[notificationMode]??(notificationMode==='normal'?t.baseId:null);if(current!==(scope===t.scope?base:null))fail('该范围已有更新的模板,请重新导入后确认。',409);
if(typeof input.useText!=='boolean')fail('正文模式无效。');if(input.useText){if(typeof input.text!=='string'||!input.text.trim()||input.text.length>200000)fail('正文应为 1–200000 字。');t.text=input.text;t.html='';}
if(typeof input.useText!=='boolean')fail('正文模式无效。');if(input.useText){if(typeof input.text!=='string'||!input.text.trim()||input.text.length>200000)fail('正文应为 1–200000 字。');t.text=input.text;t.html='';t.bodyFormat='text';t.body=t.text;}
validateVariables(subject,t.text,t.html);const payload={...t,subject,scope,notificationMode,confirmedBy:actor,confirmedAt:at()};delete payload.id;this.db.prepare("UPDATE templates SET status='archived',version=version+1 WHERE channel_id=? AND scope=? AND notification_mode=? AND status='active'").run(t.channelId,scope,notificationMode);this.db.prepare("UPDATE templates SET channel_id=?,scope=?,notification_mode=?,status='active',version=version+1,payload=?,summary=? WHERE id=?").run(t.channelId,scope,notificationMode,this.encode(id,payload),this.summary(payload),id);return this.template(id);
});}
reject(id,version){const t=this.template(id);if(t.status!=='pending'||t.version!==version)fail('模板状态已变化。',409);this.db.prepare("UPDATE templates SET status='rejected',version=version+1 WHERE id=?").run(id);}
+1 -1
View File
@@ -21,7 +21,7 @@ class OrderRuleDispatcher{
constructor({store,mail,settings,calendar=()=>[],clock=()=>new Date(),providersReady=()=>false,attachmentReader,templateResolver}){
this.store=store;this.mail=mail;this.settings=settings;this.calendar=calendar;this.clock=clock;this.providersReady=providersReady;
this.running=null;this.stopped=false;this.schedule=null;this.timer=null;
this.attachmentReader=attachmentReader;if(templateResolver)store.templateResolver=templateResolver;
this.attachmentReader=attachmentReader;if(templateResolver)store.templateResolver=templateResolver;if(mail?.store?.signature)store.signatureResolver=id=>mail.store.signature(id);
}
ready(){
const config=this.store.settings(),cap=this.store.snapshot().capabilities;
+3 -3
View File
@@ -2,7 +2,7 @@
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 {composeBatch}=require('./template.cjs');
const {initialNotification,ordersForMode}=require('./huizhou.cjs');
function previewEffects(rule,event,store){
const hui=initialNotification(rule,event);
@@ -19,8 +19,8 @@ function previewEffects(rule,event,store){
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};
const orders=ordersForMode([order],mode),snapshot=composeBatch(rule,orders,cutoff,store,{notificationMode:mode,simulation:true});
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,signature:snapshot.signature||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);}
}
+3 -3
View File
@@ -2,8 +2,8 @@
const fs=require('node:fs');const path=require('node:path');const crypto=require('node:crypto');
const {DatabaseSync}=require('node:sqlite');const {BpmVault}=require('../../platform/security/vault.cjs');
const {seedRules}=require('./catalog.cjs');const registry=require('./registry.cjs');const {previewMatch,describeRule}=require('./matching.cjs');
const {buildBatch}=require('./batch.cjs');const {transition}=require('./state.cjs');
const {applyBodyTemplate}=require('./template.cjs');
const {transition}=require('./state.cjs');
const {composeBatch}=require('./template.cjs');
const {fail,validateRule,publicationIssues}=require('./validation.cjs');
const {windowForCutoff,upcomingWindow,inWindow}=require('./window.cjs');
const {matchesScope,scopesOverlap}=require('./scopes.cjs');
@@ -284,7 +284,7 @@ class RuleStore{
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{for(const order of orders)require('./restricted-test.cjs').assertOrder(this,order);const selected=ordersForMode(orders,mode);snapshot=buildBatch(rule,selected,cutoff,{store:this,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;}
if(!error)try{for(const order of orders)require('./restricted-test.cjs').assertOrder(this,order);snapshot=composeBatch(rule,ordersForMode(orders,mode),cutoff,this,{window,notificationMode:mode});}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};
+7 -1
View File
@@ -52,4 +52,10 @@ function applyHuizhouTemplate(snapshot,template,orders,maxMessageBytes){
if(bytes>maxMessageBytes)fail('关联模板展开后超过邮件容量限制。');
return {...snapshot,subject,text,html,template:{id:template.id,version:template.version,bindingVersion:template.bindingVersion,notificationMode:'huizhou'}};
}
module.exports={applyBodyTemplate};
function composeBatch(rule,orders,cutoff,store,{window,notificationMode='normal',simulation=false}={}){
const settings=store.settings(),signature=settings.channelId?store.signatureResolver?.(settings.channelId):null;
const snapshot=require('./batch.cjs').buildBatch(signature?.enabled?{...rule,signature:''}:rule,orders,cutoff,{...(!simulation?{store}:{}),maxMessageBytes:settings.maxMessageBytes,window,notificationMode});
const rendered=applyBodyTemplate(snapshot,store.templateResolver?.(rule.categoryId,rule,notificationMode),orders,settings.maxMessageBytes);
return require('../mail/content.cjs').appendSignature(rendered,signature,settings.maxMessageBytes);
}
module.exports={applyBodyTemplate,composeBatch};