diff --git a/docs/HANDOFF.md b/docs/HANDOFF.md
index ccc5f23..670ea61 100644
--- a/docs/HANDOFF.md
+++ b/docs/HANDOFF.md
@@ -1,5 +1,13 @@
# 开发交接(2026-10-23)
+## 邮件模板编辑与账户签名
+
+- 邮件模板页可新建、编辑待确认/已生效模板,支持纯文本、HTML源码及安全预览。active编辑保留模板ID和分类关联,版本递增并保留修改前历史;历史/忽略模板可复制为新草稿。新建/待确认模板仍需确认生效;已生效模板不能直接改变普通/惠州通知模式。
+- 邮箱管理→管理邮箱中维护固定尾部签名,可选纯文本或HTML。默认未启用,不自动迁移或删除旧正文中的署名。启用后由实际发件账户在新批次冻结时追加;旧规则署名仅兼容保留,页面不再编辑。模板内已有署名须由用户在正文中调整,避免重复。
+- 正文效果预览与实际冻结共用composeBatch,包括模板、签名及容量检查。冻结保存模板/账户签名版本及最终正文,后续编辑不改写已冻结批次;测试发信也使用该账户签名。To/Cc隔离、无附件及unknown不重发约束不变。
+- HTML复用现有白名单清理,并生成纯文本备选。编辑预览使用独立受限页面,保留安全内联样式,禁止脚本/远程图片;预览仅在内存中保存最多20条、5分钟并绑定管理员,不写业务数据库。HTML转文本库原已安装,现声明html-to-text 10.0.1为直接依赖。
+- 本轮34项相关验收全部通过,另有SMTP服务专项通过;未重跑旧千项全量。独立复核发现的预览签名差异已补失败测试并闭合。已备份并更新原本机测试副本,实机打开HTML编辑/预览及账户签名入口验收。原模板与邮箱配置、规则、订单、批次和发信记录哈希保持一致。本轮未发送真实邮件、未办理BPM,也未操作正式服务机。
+
## 匹配编辑交互更新
移除分类规则中的独立“搜索流程或节点”框和可见Excel类别编号,内部类别标识保留以兼容导入。流程、节点选择复用Tabler配套Tom Select,输入即时筛选、支持键盘选择,禁止创建未采集项;节点按流程联动。搜索输入不标记草稿变更,切换/离页时销毁控件。此次为界面调整,不修改业务快照、发送设置或BPM行为。
diff --git a/docs/business-configuration.md b/docs/business-configuration.md
index d6bd245..4abe8d2 100644
--- a/docs/business-configuration.md
+++ b/docs/business-configuration.md
@@ -1,5 +1,11 @@
# 业务配置与 Excel 导入
+## 邮件模板与账户签名
+
+“邮件模板”可直接新建,或打开现有模板后点击“编辑模板”。可以维护标题、正文、适用产品线,正文可选择纯文本或HTML源码;“预览正文”不会发信。保存后的内容存入加密数据库,刷新、重启后保留。待确认模板须确认生效后才可被规则使用;编辑已生效模板保留原分类关联并更新版本,只影响后续新冻结批次。历史版本保持只读,可复制编辑。
+
+邮件尾部在“邮箱管理→管理邮箱→邮件尾部签名”设置,可选择纯文本或HTML并预览。签名为固定内容,不使用订单变量;启用后按实际发信账户追加到新批次。正文中原来已经写死的签名不会自动删除,请在模板编辑时手动调整。签名修改不会清除SMTP/IMAP密码或重置连接状态。规则试运行正文也会显示账户签名,已冻结批次保留当时正文和签名版本。
+
## 字段映射与规则导入(2026-10-23更新)
“字段映射”页面现在只展示BPM实际采集到的流程、对应节点,以及自动采集开关。名称和配对保存在数据库;开启后监听完整待办列表或手动“从 BPM 更新”会新增去重项,关闭后保留目录和既有业务规则。初始化仅读取已保存的服务端真实采集证据,不使用分类种子、Excel或历史查看占位节点生成选项。采集不创建业务订单、不发信、不办理BPM。
diff --git a/docs/superpowers/plans/2026-10-23-template-editor-signatures.md b/docs/superpowers/plans/2026-10-23-template-editor-signatures.md
new file mode 100644
index 0000000..6aeba21
--- /dev/null
+++ b/docs/superpowers/plans/2026-10-23-template-editor-signatures.md
@@ -0,0 +1,14 @@
+# 模板编辑与邮箱签名
+
+用户要求直接实施。复用现有模板、邮箱数据库及批次冻结,不增加第二套通知链。
+
+- [x] 失败测试:HTML模板编辑保存、历史/绑定/并发版本、账户签名持久化、冻结不变和权限。
+- [x] 新建/编辑模板及HTML安全预览;active模板ID稳定、每次保存保留历史,pending仍需确认。
+- [x] 邮箱账户维护纯文本/HTML签名,空签名默认不改变现有邮件;冻结时追加,旧批次不追加或重渲染。
+- [x] 隔离界面和相关业务回归,复审、备份、更新本机测试副本、提交推送。禁止真实发信和BPM写操作。
+
+HTML使用现有白名单清理;签名为固定内容。旧模板内已有签名不自动猜测删除,可在正文编辑时调整。历史模板只读,可复制编辑;viewer/operator只读。原账号、密钥、业务状态及自动发送设置保留。
+
+验收:本轮相关34项全部通过。已观察保存接口、HTML样式及预览签名差异的失败并修复,独立复核完成。预览与冻结复用composeBatch。未运行旧全量。
+
+本机测试副本已备份更新,原模板及邮箱配置、业务规则、订单、批次和发送记录哈希保持一致。实机检查仅打开编辑器与预览,没有保存原业务模板或账户设置,没有真实发信。截图及回执在忽略的output/business-flow-test目录。
diff --git a/package-lock.json b/package-lock.json
index a9ede2a..895ad06 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -20,7 +20,8 @@
"photoswipe": "5.4.4",
"playwright-core": "1.62.1",
"sanitize-html": "2.18.1",
- "xlsx": "https://cdn.sheetjs.com/xlsx-0.20.3/xlsx-0.20.3.tgz"
+ "xlsx": "https://cdn.sheetjs.com/xlsx-0.20.3/xlsx-0.20.3.tgz",
+ "html-to-text": "10.0.1"
},
"devDependencies": {
"smtp-server": "3.19.22"
diff --git a/package.json b/package.json
index 588d460..eb9caa2 100644
--- a/package.json
+++ b/package.json
@@ -13,7 +13,7 @@
"service:stop": "node scripts/service.cjs stop",
"service:restart": "node scripts/service.cjs restart",
"test": "npm run test:business",
- "test:business": "node --test --test-concurrency=1 tests/mail/sample-send.test.cjs tests/order-rules/scope-catalog.test.cjs tests/order-rules/field-mapping-ui.test.cjs tests/order-rules/scope-search-ui.test.cjs tests/order-rules/excel-import-contract.test.cjs tests/order-rules/excel-execution-bridge.test.cjs tests/order-rules/excel-import-flow-ui.test.cjs tests/order-rules/query.test.cjs tests/order-rules/scheduled-mail-policy.test.cjs",
+ "test:business": "node --test --test-concurrency=1 tests/mail/sample-send.test.cjs tests/mail/template-editing.test.cjs tests/mail/template-editor-ui.test.cjs tests/order-rules/scope-catalog.test.cjs tests/order-rules/field-mapping-ui.test.cjs tests/order-rules/scope-search-ui.test.cjs tests/order-rules/excel-import-contract.test.cjs tests/order-rules/excel-execution-bridge.test.cjs tests/order-rules/excel-import-flow-ui.test.cjs tests/order-rules/query.test.cjs tests/order-rules/scheduled-mail-policy.test.cjs",
"test:full": "node --test --test-concurrency=2 \"tests/**/*.test.cjs\""
},
"engines": {
@@ -32,7 +32,8 @@
"photoswipe": "5.4.4",
"playwright-core": "1.62.1",
"sanitize-html": "2.18.1",
- "xlsx": "https://cdn.sheetjs.com/xlsx-0.20.3/xlsx-0.20.3.tgz"
+ "xlsx": "https://cdn.sheetjs.com/xlsx-0.20.3/xlsx-0.20.3.tgz",
+ "html-to-text": "10.0.1"
},
"devDependencies": {
"smtp-server": "3.19.22"
diff --git a/src/app/assets.cjs b/src/app/assets.cjs
index d59edbb..7f13005 100644
--- a/src/app/assets.cjs
+++ b/src/app/assets.cjs
@@ -12,6 +12,7 @@ function createAssets(){
'/bpm-sync-settings.js':{path:path.join(webRoot,'modules/bpm/sync-settings.js'),type:'text/javascript'},
'/bpm.js':{path:path.join(webRoot,'modules/bpm/view.js'),type:'text/javascript'},
'/mail.js':{path:path.join(webRoot,'modules/mail/view.js'),type:'text/javascript'},
+ '/mail-template-editor.js':{path:path.join(webRoot,'modules/mail/template-editor.js'),type:'text/javascript'},
'/mail-history.js':{path:path.join(webRoot,'modules/mail/history.js'),type:'text/javascript'},
'/orders.js':{path:path.join(webRoot,'modules/bpm/arrivals.js'),type:'text/javascript'},
'/record-state.js':{path:path.join(webRoot,'modules/records/state.js'),type:'text/javascript'},
diff --git a/src/app/request.cjs b/src/app/request.cjs
index ae1067a..312fffd 100644
--- a/src/app/request.cjs
+++ b/src/app/request.cjs
@@ -14,9 +14,10 @@ async function readBody(request,fail){
let body;
if(request.method==='POST') {
if(!/^application\/json(?:;|$)/i.test(request.headers['content-type'] || ''))fail(415,'需要 JSON 数据。');
- if(Number(request.headers['content-length'] || 0)>128*1024){request.resume();fail(413,'提交内容过大。');}
+ const mailEditor=/^\/api\/mail\/(?:templates(?:\/[\w-]+\/save)?|preview)(?:\?|$)/.test(request.url||''),mailAccount=/^\/api\/mail\/channels(?:\?|$)/.test(request.url||''),maxBytes=mailEditor?4*1024*1024:mailAccount?256*1024:128*1024;
+ if(Number(request.headers['content-length'] || 0)>maxBytes){request.resume();fail(413,'提交内容过大。');}
const chunks=[];let size=0;
- for await(const chunk of request){size+=chunk.length;if(size>128*1024)fail(413,'提交内容过大。');chunks.push(chunk);}
+ for await(const chunk of request){size+=chunk.length;if(size>maxBytes)fail(413,'提交内容过大。');chunks.push(chunk);}
try{body=JSON.parse(Buffer.concat(chunks).toString('utf8'));if(!body || Array.isArray(body) || typeof body!=='object')throw new Error();}catch{fail(400,'数据格式不正确。');}
}
return body;
diff --git a/src/modules/mail/api.cjs b/src/modules/mail/api.cjs
index 5dadc6c..00fb1ca 100644
--- a/src/modules/mail/api.cjs
+++ b/src/modules/mail/api.cjs
@@ -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||'
'+escape(content.text)+'
',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(''+(template.html||''+escape(template.text)+'
')+'');return true;
diff --git a/src/modules/mail/content.cjs b/src/modules/mail/content.cjs
new file mode 100644
index 0000000..9a278bb
--- /dev/null
+++ b/src/modules/mail/content.cjs
@@ -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()&&!/
!['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||''+escape(snapshot.text).replace(/\r?\n/g,'
')+'
')+''+(signature.html||escape(signature.text).replace(/\r?\n/g,'
'))+'
';
+ 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=>''+html+'';
+module.exports={normalizeBody,normalizeSignature,appendSignature,previewDocument};
diff --git a/src/modules/mail/service.cjs b/src/modules/mail/service.cjs
index 9dfcab4..a78868a 100644
--- a/src/modules/mail/service.cjs
+++ b/src/modules/mail/service.cjs
@@ -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()]);}
}
diff --git a/src/modules/mail/store.cjs b/src/modules/mail/store.cjs
index b2c96c7..4255ad4 100644
--- a/src/modules/mail/store.cjs
+++ b/src/modules/mail/store.cjs
@@ -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'&¤t&¤t!==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);}
diff --git a/src/modules/order-rules/dispatcher.cjs b/src/modules/order-rules/dispatcher.cjs
index 0b49fc2..c8f1a02 100644
--- a/src/modules/order-rules/dispatcher.cjs
+++ b/src/modules/order-rules/dispatcher.cjs
@@ -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;
diff --git a/src/modules/order-rules/effects-preview.cjs b/src/modules/order-rules/effects-preview.cjs
index 9fc67f5..f916793 100644
--- a/src/modules/order-rules/effects-preview.cjs
+++ b/src/modules/order-rules/effects-preview.cjs
@@ -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);}
}
diff --git a/src/modules/order-rules/store.cjs b/src/modules/order-rules/store.cjs
index 250b6e3..22d9b4a 100644
--- a/src/modules/order-rules/store.cjs
+++ b/src/modules/order-rules/store.cjs
@@ -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};
diff --git a/src/modules/order-rules/template.cjs b/src/modules/order-rules/template.cjs
index dd28f39..7fea148 100644
--- a/src/modules/order-rules/template.cjs
+++ b/src/modules/order-rules/template.cjs
@@ -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};
diff --git a/tests/mail/mail-http.test.cjs b/tests/mail/mail-http.test.cjs
index e65a425..7a4d502 100644
--- a/tests/mail/mail-http.test.cjs
+++ b/tests/mail/mail-http.test.cjs
@@ -28,3 +28,7 @@ test('history access requires administrator and same origin; isolated history mo
mail.imapFactory=()=>({on(){},async connect(){},async list(){return [{path:'Sent',specialUse:'\\Sent'}];},async logout(){},close(){}});
const folders=await call(url+'/history',{action:'folders'},admin);assert.equal(folders.status,200);assert.deepEqual((await folders.json()).folders,[{path:'Sent',name:'Sent'}]);
});
+test('HTML editor previews larger UTF-8 bodies within a bounded mail-only request limit',async t=>{
+ const {call,login}=await setup(t),admin=await login('admin'),body='正文
'.repeat(16000);assert(Buffer.byteLength(JSON.stringify({format:'html',body}))>128*1024);
+ const preview=await call('/api/mail/preview',{format:'html',body},admin);assert.equal(preview.status,200);const result=await preview.json();assert.match(result.html,/正文<\/p>/);const frame=await call(result.previewUrl,undefined,admin);assert.equal(frame.status,200);assert.match(frame.headers.get('content-security-policy'),/sandbox/);assert.match(frame.headers.get('content-security-policy'),/style-src 'unsafe-inline'/);assert.equal((await call(result.previewUrl,undefined,await login('reader'))).status,403);
+});
diff --git a/tests/mail/mail-service.test.cjs b/tests/mail/mail-service.test.cjs
index 6fb3f64..4056285 100644
--- a/tests/mail/mail-service.test.cjs
+++ b/tests/mail/mail-service.test.cjs
@@ -6,9 +6,9 @@ async function fixture(t,options={}){const dir=fs.mkdtempSync(path.join(os.tmpdi
test('self-test renders business template variables with synthetic data and the configured self recipient',async t=>{
let sent;const {store,service}=await fixture(t,{smtpFactory:()=>({verify:async()=>{},sendMail:async message=>{sent=message;return {accepted:[config.email]};},close(){}})});
- const c=store.saveChannel(config),p=require('../../src/modules/mail/parser.cjs'),body='{{类别名称}}\n{{订单明细}}\n存放地址:{{存放地址}}',mail=Buffer.from(raw.toString().replace('Hello {{订单号}}',body));
+ const c=store.saveChannel({...config,signature:{enabled:true,format:'html',body:'
Best Regards! 隔离账户签名
'}}),p=require('../../src/modules/mail/parser.cjs'),body='{{类别名称}}\n{{订单明细}}\n存放地址:{{存放地址}}',mail=Buffer.from(raw.toString().replace('Hello {{订单号}}',body));
const draft=store.ingest(c.id,'1',1,await p.parseTemplate(mail,config),mail,c.version);store.confirm(draft.id,{version:1,subject:'测试摘要',scope:'',text:body,useText:true},'admin');
- await service.sendTest(c.id,draft.id);assert.equal(sent.to.address,config.email);assert.match(sent.text,/订单号:TEST/);assert.match(sent.text,/示例归档目录/);assert.doesNotMatch(sent.text,/{{/);assert.equal(store.sends()[0].status,'sent');
+ await service.sendTest(c.id,draft.id);assert.equal(sent.to.address,config.email);assert.match(sent.text,/订单号:TEST/);assert.match(sent.text,/示例归档目录/);assert.match(sent.text,/隔离账户签名/);assert.match(sent.html,/Best Regards!/);assert.doesNotMatch(sent.text,/{{/);assert.equal(store.sends()[0].status,'sent');
});
test('read-only poll uses UID epoch, ignores ordinary messages, does not double ingest, and records source denials',async t=>{
let downloads=0,locks=0;const client={mailbox:{uidValidity:10n},on(){},async connect(){},async getMailboxLock(box,options){assert.equal(box,'INBOX');assert.equal(options.readOnly,true);locks++;return {release(){locks--;}};},async search(query,options){assert.equal(options.uid,true);return [1,2,3];},async fetchOne(uid,query,options){assert.equal(options.uid,true);if(query.source){downloads++;return {source:uid===3?Buffer.from(raw.toString().replace('author@','unknown@')):raw};}return {size:raw.length,envelope:{subject:uid===1?'Ordinary':'[模板]Notice'}};},async logout(){},close(){}};
diff --git a/tests/mail/template-editing.test.cjs b/tests/mail/template-editing.test.cjs
new file mode 100644
index 0000000..f873416
--- /dev/null
+++ b/tests/mail/template-editing.test.cjs
@@ -0,0 +1,29 @@
+'use strict';
+const test=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs'),os=require('node:os'),path=require('node:path');
+const {MailStore}=require('../../src/modules/mail/store.cjs');
+const config={name:'隔离邮箱',email:'orders@example.test',smtp:{host:'smtp.example.test',port:465,security:'tls',user:'orders',password:'test-only-password'},imap:{host:'imap.example.test',port:993,security:'tls',user:'orders',password:'test-only-password'},senders:['author@example.test'],enabled:false};
+function fixture(t){const dir=fs.mkdtempSync(path.join(os.tmpdir(),'mail-edit-'));let store=new MailStore(dir);const channel=store.saveChannel(config);t.after(()=>{store.close();assert.equal(path.dirname(fs.realpathSync(dir)).toLowerCase(),fs.realpathSync(os.tmpdir()).toLowerCase());fs.rmSync(dir,{recursive:true,force:true});});return {get store(){return store;},channel,reopen(){store.close();store=new MailStore(dir);}};}
+test('editable HTML templates retain their ID, history and category bindings across restart',t=>{
+ const f=fixture(t),s=f.store,input={channelId:f.channel.id,subject:'通知 {{订单号}}',scope:'试产',notificationMode:'normal',format:'html',body:'
大家好:
'};
+ let saved=s.saveTemplate(null,input,'admin');assert.equal(saved.status,'pending');saved=s.confirm(saved.id,{version:saved.version,subject:saved.subject,scope:saved.scope,notificationMode:'normal',useText:false},'admin');s.bindCategory({categoryId:'trial-notice',templateId:saved.id,version:0});
+ const frozen={text:saved.text,html:saved.html,template:{id:saved.id,version:saved.version}},old=structuredClone(saved);
+ saved=s.saveTemplate(saved.id,{version:saved.version,...input,body:'更新 &内容
{{订单明细}}
'},'admin');
+ assert.equal(saved.id,old.id);assert.equal(saved.status,'active');assert.equal(saved.version,old.version+1);assert.match(saved.html,/color:#123456/);assert.doesNotMatch(saved.html,/script|tracker|bad\(/);assert.match(saved.text,/更新.*&内容/);assert.match(saved.text,/{{订单明细}}/);assert.equal(s.categoryTemplate('trial-notice').id,old.id);
+ const history=s.templates().find(r=>r.status==='archived');assert(history);assert.equal(s.template(history.id).html,old.html);assert.deepEqual(frozen,{text:old.text,html:old.html,template:{id:old.id,version:old.version}});
+ assert.throws(()=>s.saveTemplate(saved.id,{version:old.version,...input},'admin'),e=>e.status===409);f.reopen();assert.equal(f.store.template(saved.id).html,saved.html);assert.equal(f.store.categoryTemplate('trial-notice').version,saved.version);
+});
+test('account signatures persist without resetting SMTP status or credentials and freeze into content once',t=>{
+ const f=fixture(t),s=f.store,c=f.channel;s.setState(c.id,c.version,{smtp:true,imap:true});
+ const saved=s.saveChannel({...config,id:c.id,version:c.version,smtp:{...config.smtp,password:''},imap:{...config.imap,password:''},signature:{enabled:true,format:'html',body:'Best Regards!
测试签名 &团队
'}});
+ assert.equal(saved.state.smtp,true);assert.equal(s.channelSecret(c.id).smtp.password,config.smtp.password);assert.match(saved.signature.text,/Best Regards!/);assert.doesNotMatch(saved.signature.html,/script|bad\(/);
+ const {appendSignature}=require('../../src/modules/mail/content.cjs'),base={subject:'通知',text:'订单号:TEST',html:'订单号:TEST
',attachments:[]};const frozen=appendSignature(base,s.signature(c.id),100000);assert.match(frozen.text,/测试签名.*&团队/);assert.equal(frozen.signature.version,saved.version);assert.equal(appendSignature(frozen,s.signature(c.id),100000).html,frozen.html);
+ s.saveChannel({...config,id:c.id,version:saved.version,signature:{enabled:true,format:'text',body:'新签名'}});assert.doesNotMatch(frozen.text,/新签名/);f.reopen();assert.equal(f.store.publicChannel(c.id).signature.text,'新签名');assert.equal(f.store.signature(c.id).channelId,c.id);
+});
+test('invalid template bodies, variable names and incompatible live modes are rejected without a revision',t=>{
+ const f=fixture(t),s=f.store,input={channelId:f.channel.id,subject:'通知',scope:'',notificationMode:'normal',format:'text',body:'正文 {{订单列表}}'};let t1=s.saveTemplate(null,input,'admin');t1=s.confirm(t1.id,{version:t1.version,subject:t1.subject,scope:'',notificationMode:'normal',useText:false},'admin');const before=s.templates();
+ for(const patch of [{body:'{{不存在}}'},{format:'html',body:''},{notificationMode:'huizhou'},{body:'x'.repeat(200001)}])assert.throws(()=>s.saveTemplate(t1.id,{version:t1.version,...input,...patch},'admin'));
+ assert.deepEqual(s.templates(),before);assert.throws(()=>s.saveChannel({...config,id:f.channel.id,version:f.channel.version,signature:{enabled:true,format:'html',body:''}}));assert.equal(s.publicChannel(f.channel.id).version,f.channel.version);
+});
+test('new editing and preview APIs enforce admin permissions without SMTP side effects',async()=>{
+ const {mailApi}=require('../../src/modules/mail/api.cjs');for(const role of ['viewer','operator'])for(const route of ['/api/mail/templates','/api/mail/templates/test/save','/api/mail/preview'])await assert.rejects(mailApi({mail:{store:{}},user:{username:role,role},route,method:'POST',body:{},reply(){throw Error('unexpected write');}}),e=>e.status===403);
+});
diff --git a/tests/mail/template-editor-ui.test.cjs b/tests/mail/template-editor-ui.test.cjs
new file mode 100644
index 0000000..d40a0c1
--- /dev/null
+++ b/tests/mail/template-editor-ui.test.cjs
@@ -0,0 +1,21 @@
+'use strict';
+const test=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs/promises'),os=require('node:os'),path=require('node:path');
+const {startTestDashboard,login}=require('../fixtures/dashboard-runtime.cjs'),{loadPlaywright,browserOptions}=require('../../src/platform/browser.cjs');
+const config={name:'隔离编辑邮箱',email:'orders@example.test',smtp:{host:'smtp.example.test',port:465,security:'tls',user:'orders',password:'test-only-password'},imap:{host:'imap.example.test',port:993,security:'tls',user:'orders',password:'test-only-password'},senders:['author@example.test'],enabled:false};
+async function setup(t){const dir=await fs.mkdtemp(path.join(os.tmpdir(),'template-editor-ui-')),runtime=await startTestDashboard({stateDir:dir,mailHistory:true}),browser=await loadPlaywright().chromium.launch(browserOptions());t.after(async()=>{await browser.close();await runtime.close();assert.equal(path.dirname(await fs.realpath(dir)).toLowerCase(),(await fs.realpath(os.tmpdir())).toLowerCase());await fs.rm(dir,{recursive:true,force:true});});const channel=runtime.mail.store.saveChannel(config),page=await browser.newPage({viewport:{width:1440,height:1000}});page.setDefaultTimeout(10000);const base='http://127.0.0.1:'+runtime.server.address().port;return {runtime,page,base,channel};}
+test('active templates edit HTML, preview safely and retain binding after reload without sending mail',{timeout:90000},async t=>{
+ const {runtime,page,base,channel}=await setup(t),store=runtime.mail.store;let template=store.saveTemplate(null,{channelId:channel.id,subject:'原模板',scope:'海外',notificationMode:'normal',format:'text',body:'大家好:\n{{订单明细}}'},'admin');template=store.confirm(template.id,{version:template.version,subject:template.subject,scope:template.scope,notificationMode:'normal',useText:false},'admin');
+ await page.goto(base+'/#templates');await login(page);await page.getByRole('button',{name:'查看版本',exact:true}).click();await page.getByRole('button',{name:'编辑模板',exact:true}).click();
+ await page.getByLabel('正文格式',{exact:true}).selectOption('html');await page.getByLabel('HTML正文(源码)',{exact:true}).fill('大家好:
');await page.getByLabel('模板标题',{exact:true}).fill('更新模板 {{订单号}}');
+ await page.getByRole('button',{name:'预览正文',exact:true}).click();await page.frameLocator('iframe[title="编辑正文预览"]').getByText('{{订单明细}}',{exact:true}).waitFor();
+ assert.equal(await page.frameLocator('iframe[title="编辑正文预览"]').getByText('大家好:',{exact:true}).evaluate(e=>getComputedStyle(e).color),'rgb(18, 52, 86)');
+ await page.route('**/api/mail/templates/'+template.id+'/save',r=>r.fulfill({status:503,json:{error:'隔离保存失败'}}));await page.getByRole('button',{name:'保存模板',exact:true}).click();await page.getByText('隔离保存失败',{exact:true}).waitFor();assert.equal(store.template(template.id).version,template.version);assert.match(await page.getByLabel('HTML正文(源码)',{exact:true}).inputValue(),//);await page.getByRole('button',{name:'取消',exact:true}).click();await page.getByRole('button',{name:'留在此页',exact:true}).click();await page.unroute('**/api/mail/templates/'+template.id+'/save');
+ await page.getByRole('button',{name:'保存模板',exact:true}).click();await page.getByText('模板已保存。',{exact:true}).waitFor();assert.equal(store.template(template.id).version,template.version+1);assert.doesNotMatch(store.template(template.id).html,/script|bad\(/);assert.equal(store.template(template.id).status,'active');
+ await page.reload();await page.getByRole('button',{name:'查看版本',exact:true}).click();await page.getByRole('button',{name:'编辑模板',exact:true}).click();assert.equal(await page.getByLabel('模板标题',{exact:true}).inputValue(),'更新模板 {{订单号}}');assert.match(await page.getByLabel('HTML正文(源码)',{exact:true}).inputValue(),//);assert.deepEqual(store.sends(),[]);
+ await page.setViewportSize({width:390,height:844});assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true);
+});
+test('new page templates save as drafts and HTML account signatures survive account reload',{timeout:90000},async t=>{
+ const {runtime,page,base,channel}=await setup(t),store=runtime.mail.store,seed=store.saveTemplate(null,{channelId:channel.id,subject:'已有模板',scope:'已有',notificationMode:'normal',format:'text',body:'{{订单明细}}'},'admin');store.confirm(seed.id,{version:seed.version,subject:seed.subject,scope:seed.scope,notificationMode:'normal',useText:false},'admin');await page.goto(base+'/#templates');await login(page);await page.getByRole('button',{name:'新建模板',exact:true}).click();await page.getByLabel('模板标题',{exact:true}).fill('新建业务模板');await page.getByRole('button',{name:'保存模板',exact:true}).click();await page.getByText('模板已保存。',{exact:true}).waitFor();assert.equal(store.templates()[0].status,'pending');assert.equal(await page.getByLabel('模板状态',{exact:true}).inputValue(),'pending');
+ await page.getByRole('link',{name:'邮箱管理',exact:true}).click();await page.getByRole('button',{name:'管理邮箱',exact:true}).click();await page.getByLabel('启用邮件签名',{exact:true}).check();await page.getByLabel('签名格式',{exact:true}).selectOption('html');await page.getByLabel('签名内容',{exact:true}).fill('Best Regards!
隔离测试团队
');await page.getByRole('button',{name:'保存邮箱',exact:true}).click();await page.getByText('邮箱已保存。',{exact:true}).waitFor();
+ await page.reload();await page.getByRole('button',{name:'管理邮箱',exact:true}).click();assert.equal(await page.getByLabel('签名格式',{exact:true}).inputValue(),'html');assert.match(await page.getByLabel('签名内容',{exact:true}).inputValue(),/隔离测试团队/);assert.match(store.signature(channel.id).text,/Best Regards!/);assert.equal(store.channelSecret(channel.id).smtp.password,config.smtp.password);assert.deepEqual(store.sends(),[]);
+});
diff --git a/tests/order-rules/excel-execution-bridge.test.cjs b/tests/order-rules/excel-execution-bridge.test.cjs
index 8b9236a..e5b0a2a 100644
--- a/tests/order-rules/excel-execution-bridge.test.cjs
+++ b/tests/order-rules/excel-execution-bridge.test.cjs
@@ -61,3 +61,12 @@ test('first restricted activation cannot bypass an unknown imported notification
const f=fixture(t),draft=f.store.get('rules','bs-change').draft;f.store.saveRule({...draft,scopes:[{processName:'备损订单更改评审',nodeName:'Excel未知节点'}]},'admin');f.store.put('restricted-test',{id:'main',value:null});
assert.throws(()=>f.store.saveRestrictedTest({version:0,enabled:true,recipient:'2639266652@qq.com',archiveRoot:f.root,channelId:'fixture-mail',ruleIds:['bs-change']},admin),e=>e.status===409&&/字段映射/.test(e.message));assert.equal(f.store.restrictedTest(),null);
});
+test('native batch freeze snapshots the sender signature and template before later edits',t=>{
+ const f=fixture(t),plan=previewImport(f.store,f.input,'admin');commitImport(f.store,{id:plan.id,applyToTest:true},'admin',{user:admin});
+ let signature={channelId:'fixture-mail',version:7,enabled:true,format:'html',text:'账户签名',html:'账户签名
'},template={id:'fixture-template',version:3,bindingVersion:1,subject:'通知 {{订单号}}',text:'大家好:\n{{订单明细}}\n存放地址:{{存放地址}}',html:'大家好:
{{订单明细}}
{{存放地址}}
',attachments:[]};
+ new (require('../../src/modules/order-rules/dispatcher.cjs').OrderRuleDispatcher)({store:f.store,mail:{store:{signature:()=>signature}},settings:()=>({}),templateResolver:()=>template});
+ const order=f.store.ingest(f.event('signature-task'),'fixture'),content=Buffer.from('%PDF-1.7 fixture');f.store.recordArchive(order.id,{archivedAt:'2026-10-23T01:01:00Z',files:[{name:'fixture.pdf',path:f.root+'\\orders\\fixture.pdf',size:content.length,sha256:crypto.createHash('sha256').update(content).digest('hex'),kind:'pdf'}]},'fixture');f.store.saveSettings({...f.store.settings(),enabled:true,channelId:'fixture-mail'},'admin');f.store.clock=()=>new Date('2026-10-23T03:00:00Z');
+ const [batch]=f.store.prepare('2026-10-23T03:00:00Z','fixture');assert(batch);assert.match(batch.text,/账户签名/);assert.match(batch.html,/账户签名<\/p>/);assert.equal(batch.signature.version,7);assert.equal(batch.template.version,3);assert.deepEqual(batch.attachments,[]);
+ const effects=require('../../src/modules/order-rules/effects-preview.cjs').previewEffects(batch.ruleSnapshot,order.event,f.store);assert.equal(effects.mail.text,batch.text);assert.equal(effects.mail.signature.version,7);
+ signature={...signature,version:8,text:'新账户签名',html:'
新账户签名
'};template={...template,version:4,text:'修改后的正文'};assert.deepEqual(f.store.get('batches',batch.id),batch);
+});
diff --git a/web/index.html b/web/index.html
index 32f0ef5..8eb42ac 100644
--- a/web/index.html
+++ b/web/index.html
@@ -1,3 +1,3 @@
订单通知中心
-
+