diff --git a/src/modules/mail/rule-template.cjs b/src/modules/mail/rule-template.cjs index 8995d9b..c56629b 100644 --- a/src/modules/mail/rule-template.cjs +++ b/src/modules/mail/rule-template.cjs @@ -1,9 +1,14 @@ 'use strict'; -function ruleTemplate(store,categoryId,rule){ - if(rule?.bodyTemplateId===undefined)return store.categoryTemplate(categoryId); - if(!rule.bodyTemplateId)return null; - const template=store.template(rule.bodyTemplateId); - if(template.status!=='active')throw Object.assign(new Error('本分类选择的邮件模板已停用,请重新选择已确认模板。'),{status:409}); +function ruleTemplate(store,categoryId,rule,mode='normal'){ + if(!['normal','huizhou'].includes(mode))throw Object.assign(new Error('通知模式无效。'),{status:400}); + if(mode==='huizhou'&&rule?.huizhouEnabled!==true)return null; + const id=mode==='huizhou'?rule.huizhouTemplateId:rule?.bodyTemplateId; + if(mode==='huizhou'&&!id)throw Object.assign(new Error('开启惠州通知时请选择已确认的惠州模板。'),{status:409}); + const template=mode==='normal'&&id===undefined?store.categoryTemplate(categoryId):id?store.template(id):null; + if(!template)return null; + if((template.notificationMode??'normal')!==mode)throw Object.assign(new Error('邮件模板通知模式不匹配,请重新选择。'),{status:409}); + // Legacy category bindings already check status in the store. + if(template.status!=='active'&&!(mode==='normal'&&id===undefined&&template.status===undefined))throw Object.assign(new Error('本分类选择的邮件模板已停用,请重新选择已确认模板。'),{status:409}); return template; } module.exports={ruleTemplate}; diff --git a/src/modules/mail/store.cjs b/src/modules/mail/store.cjs index 571bd7b..5aa28de 100644 --- a/src/modules/mail/store.cjs +++ b/src/modules/mail/store.cjs @@ -10,11 +10,15 @@ class MailStore{ this.vault=new BpmVault({stateDir:path.join(dir,'secrets')});this.db=new DatabaseSync(path.join(dir,'mail.sqlite'));this.db.exec(`PRAGMA journal_mode=WAL; PRAGMA busy_timeout=5000; PRAGMA secure_delete=ON; CREATE TABLE IF NOT EXISTS channels(id TEXT PRIMARY KEY,email TEXT NOT NULL UNIQUE,version INTEGER NOT NULL,payload BLOB NOT NULL,state TEXT NOT NULL,cursor TEXT NOT NULL); CREATE TABLE IF NOT EXISTS templates(id TEXT PRIMARY KEY,channel_id TEXT NOT NULL,source_key TEXT NOT NULL,scope TEXT NOT NULL,status TEXT NOT NULL,version INTEGER NOT NULL,base_id TEXT,payload BLOB NOT NULL,created_at TEXT NOT NULL,UNIQUE(channel_id,source_key)); - CREATE UNIQUE INDEX IF NOT EXISTS active_template ON templates(channel_id,scope) WHERE status='active'; CREATE TABLE IF NOT EXISTS receipts(id INTEGER PRIMARY KEY,channel_id TEXT NOT NULL,epoch TEXT NOT NULL,uid INTEGER NOT NULL,status TEXT NOT NULL,detail TEXT NOT NULL,at TEXT NOT NULL,UNIQUE(channel_id,epoch,uid)); CREATE TABLE IF NOT EXISTS sends(id TEXT PRIMARY KEY,channel_id TEXT NOT NULL,template_id TEXT NOT NULL,status TEXT NOT NULL,at TEXT NOT NULL); CREATE TABLE IF NOT EXISTS meta(key TEXT PRIMARY KEY,value TEXT NOT NULL);`); if(!this.db.prepare('PRAGMA table_info(templates)').all().some(c=>c.name==='summary'))this.db.exec("ALTER TABLE templates ADD COLUMN summary TEXT NOT NULL DEFAULT '{}'"); + this.transaction(()=>{ + if(!this.db.prepare('PRAGMA table_info(templates)').all().some(c=>c.name==='notification_mode'))this.db.exec("ALTER TABLE templates ADD COLUMN notification_mode TEXT NOT NULL DEFAULT 'normal' CHECK(notification_mode IN ('normal','huizhou'))"); + const columns=this.db.prepare('PRAGMA index_info(active_template)').all().map(c=>c.name).join(','); + if(columns!=='channel_id,scope,notification_mode')this.db.exec("DROP INDEX IF EXISTS active_template; CREATE UNIQUE INDEX active_template ON templates(channel_id,scope,notification_mode) WHERE status='active'"); + }); for(const r of this.db.prepare("SELECT id,payload FROM templates WHERE summary='{}'").all()){const p=this.decode(r.id,r.payload);this.db.prepare('UPDATE templates SET summary=? WHERE id=?').run(this.summary(p),r.id);} } catch(error) { try { this.db?.close(); } catch {} @@ -51,11 +55,11 @@ class MailStore{ receipts(){return this.db.prepare('SELECT * FROM receipts ORDER BY id DESC LIMIT 100').all();} ingest(channelId,epoch,uid,parsed,raw,configVersion){return this.transaction(()=>{ this.guard(channelId,configVersion);const key=parsed.messageId?hash(parsed.messageId+'\0'+hash(raw)):hash(raw);const old=this.db.prepare('SELECT id FROM templates WHERE channel_id=? AND source_key=?').get(channelId,key); - let id=old?.id;if(!id){id=crypto.randomUUID();const payload={...parsed,raw:raw.toString('base64')};const base=this.activeId(channelId,parsed.scope);this.db.prepare('INSERT INTO templates VALUES(?,?,?,?,?,?,?,?,?,?)').run(id,channelId,key,parsed.scope,'pending',1,base,this.encode(id,payload),at(),this.summary(parsed));} + let id=old?.id;if(!id){id=crypto.randomUUID();const payload={...parsed,raw:raw.toString('base64'),notificationBaseIds:{normal:this.activeId(channelId,parsed.scope),huizhou:this.activeId(channelId,parsed.scope,'huizhou')}};const base=payload.notificationBaseIds.normal;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,key,parsed.scope,'pending',1,base,this.encode(id,payload),at(),this.summary(parsed),'normal');} 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,status:r.status,version:r.version,baseId:r.base_id,createdAt:r.created_at};} - templates(){return ['pending','active','archived','rejected'].flatMap(status=>this.db.prepare('SELECT id,channel_id,scope,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,status:r.status,version:r.version,createdAt:r.created_at})));} + 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};} + 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||'[]');} bindCategory(input){return this.transaction(()=>{ @@ -63,20 +67,20 @@ class MailStore{ if(!input||Object.keys(input).some(k=>!['categoryId','templateId','version'].includes(k))||!categories.some(c=>c.id===input.categoryId)||typeof input.templateId!=='string')fail('请选择有效的 Excel 类别和模板。'); const bindings=this.categoryBindings(),old=bindings.find(b=>b.categoryId===input.categoryId); if(input.version!==(old?.version||0))fail('类别模板关联已变化,请刷新后重试。',409); - if(input.templateId&&this.template(input.templateId).status!=='active')fail('只能关联已确认生效的模板。',409); + if(input.templateId){const t=this.template(input.templateId);if(t.status!=='active'||t.notificationMode!=='normal')fail('只能关联普通通知已确认生效的模板。',409);} const saved={categoryId:input.categoryId,templateId:input.templateId,version:(old?.version||0)+1}; this.db.prepare("INSERT INTO meta VALUES('categoryBindings',?) ON CONFLICT(key) DO UPDATE SET value=excluded.value").run(JSON.stringify([...bindings.filter(b=>b.categoryId!==input.categoryId),saved]));return saved; });} categoryTemplate(categoryId){const binding=this.categoryBindings().find(b=>b.categoryId===categoryId);if(!binding?.templateId)return null;const template=this.template(binding.templateId);if(template.status!=='active')fail('类别关联的模板已变为历史版本,请重新确认关联。',409);return {...template,bindingVersion:binding.version};} - activeId(channelId,scope){return this.db.prepare("SELECT id FROM templates WHERE channel_id=? AND scope=? AND status='active'").get(channelId,scope)?.id||null;} - active(channelId,scope){const r=this.db.prepare("SELECT id FROM templates WHERE channel_id=? AND scope=? AND status='active'").get(channelId,scope);return r?this.template(r.id):null;} - confirm(id,input,actor){return this.transaction(()=>{const t=this.template(id);if(t.status!=='pending'||input.version!==t.version)fail('模板状态已变化,请刷新。',409);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);if(current!==(scope===t.scope?t.baseId:null))fail('该范围已有更新的模板,请重新导入后确认。',409); + 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='';} - validateVariables(subject,t.text,t.html);const payload={...t,subject,scope,confirmedBy:actor,confirmedAt:at()};delete payload.id;this.db.prepare("UPDATE templates SET status='archived',version=version+1 WHERE channel_id=? AND scope=? AND status='active'").run(t.channelId,scope);this.db.prepare("UPDATE templates SET channel_id=?,scope=?,status='active',version=version+1,payload=?,summary=? WHERE id=?").run(t.channelId,scope,this.encode(id,payload),this.summary(payload),id);return this.template(id); + 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);} source(id){return Buffer.from(this.template(id).raw||'','base64');} - migrateLegacy(legacy){if(this.db.prepare("SELECT 1 FROM meta WHERE key='legacy'").get())return;this.transaction(()=>{if(legacy?.subject?.trim()&&legacy?.body?.trim()){const id=crypto.randomUUID(),payload={subject:legacy.subject,text:legacy.body,html:'',sender:'工作台旧草稿',sourceSubject:legacy.subject,attachments:[],notes:['从原模板草稿迁入,请选择托管邮箱后确认。']};this.db.prepare('INSERT INTO templates VALUES(?,?,?,?,?,?,?,?,?,?)').run(id,'legacy','legacy','','pending',1,null,this.encode(id,payload),at(),this.summary(payload));}this.db.prepare("INSERT INTO meta VALUES('legacy','1')").run();});} + migrateLegacy(legacy){if(this.db.prepare("SELECT 1 FROM meta WHERE key='legacy'").get())return;this.transaction(()=>{if(legacy?.subject?.trim()&&legacy?.body?.trim()){const id=crypto.randomUUID(),payload={subject:legacy.subject,text:legacy.body,html:'',sender:'工作台旧草稿',sourceSubject:legacy.subject,attachments:[],notes:['从原模板草稿迁入,请选择托管邮箱后确认。']};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,'legacy','legacy','','pending',1,null,this.encode(id,payload),at(),this.summary(payload),'normal');}this.db.prepare("INSERT INTO meta VALUES('legacy','1')").run();});} beginSend(channelId,templateId){const id=crypto.randomUUID();this.db.prepare('INSERT INTO sends VALUES(?,?,?,?,?)').run(id,channelId,templateId,'sending',at());return id;} finishSend(id,status){this.db.prepare('UPDATE sends SET status=? WHERE id=?').run(status,id);} sends(){return this.db.prepare('SELECT * FROM sends ORDER BY at DESC LIMIT 50').all();} diff --git a/src/modules/order-rules/api.cjs b/src/modules/order-rules/api.cjs index 31ce0b8..f602f75 100644 --- a/src/modules/order-rules/api.cjs +++ b/src/modules/order-rules/api.cjs @@ -1,9 +1,15 @@ 'use strict'; -const {fail}=require('./validation.cjs'); +const {fail,validateRule}=require('./validation.cjs'); +function checkTemplates(mail,rule){ + if(!mail){if(rule?.bodyTemplateId||rule?.huizhouEnabled===true)fail('邮件模板服务暂不可用。',503);return;} + const {ruleTemplate}=require('../mail/rule-template.cjs'); + ruleTemplate(mail.store,rule?.categoryId,rule); + ruleTemplate(mail.store,rule?.categoryId,rule,'huizhou'); +} async function orderRuleApi({orderRules,mail,workspace,user,route,method,body,reply,response}){ if(route!=='/api/order-rules'&&!route.startsWith('/api/order-rules/'))return false; if(!orderRules)fail('分类通知规则服务未启动。',503); - if(route==='/api/order-rules'&&method==='GET'){reply(200,require('./access.cjs').publicSnapshot(orderRules,workspace,user));return true;} + if(route==='/api/order-rules'&&method==='GET'){const snapshot=require('./access.cjs').publicSnapshot(orderRules,workspace,user);snapshot.rules=snapshot.rules.map(rule=>({huizhouEnabled:false,huizhouTemplateId:'',...rule}));reply(200,snapshot);return true;} if(route==='/api/order-rules/import-template'&&method==='GET'){ if(user.role!=='admin')fail('仅管理员可导出规则配置。',403); const bytes=await require('./import-template.cjs').template(orderRules);response.writeHead(200,{'Content-Type':'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet','Content-Disposition':"attachment; filename*=UTF-8''"+encodeURIComponent('分类规则.xlsx')});response.end(bytes);return true; @@ -31,7 +37,8 @@ async function orderRuleApi({orderRules,mail,workspace,user,route,method,body,re if(route==='/api/order-rules/import/preview')result=require('./import.cjs').previewImport(orderRules,body,actor); else if(route==='/api/order-rules/import/commit')result=require('./import.cjs').commitImport(orderRules,body,actor); else if(route==='/api/order-rules/rules'){ - if(body?.bodyTemplateId){if(!mail)fail('邮件模板服务暂不可用。',503);require('../mail/rule-template.cjs').ruleTemplate(mail.store,body.categoryId,body);} + const old=orderRules.get('rules',body?.id)?.draft; + if(old)checkTemplates(mail,validateRule(body,old)); result=orderRules.saveRule(body,actor); } else if(route==='/api/order-rules/settings'){ @@ -47,7 +54,7 @@ async function orderRuleApi({orderRules,mail,workspace,user,route,method,body,re const batch=/^\/api\/order-rules\/batches\/([\w-]+)\/resolve$/.exec(route); const recheck=/^\/api\/order-rules\/orders\/([\w-]+)\/recheck$/.exec(route); if(rule){if(!body||Object.keys(body).some(k=>!['version','publishedVersion','activationVersion'].includes(k)))fail('请提供当前规则和启停版本。');const record=orderRules.get('rules',rule[1]);if(rule[2]==='publish'){if(!record?.trialSampleId||!orderRules.get('capture-samples',record.trialSampleId))fail('发布前必须选择服务端真实采集样本完成试运行。',409);} - if(rule[2]!=='pause'){const selected=rule[2]==='resume'?record?.published:record?.draft;if(mail)require('../mail/rule-template.cjs').ruleTemplate(mail.store,selected?.categoryId,selected);else if(selected?.bodyTemplateId)fail('邮件模板服务暂不可用。',503);} + if(rule[2]!=='pause'){const selected=rule[2]==='resume'?record?.published:record?.draft;checkTemplates(mail,selected);} result=orderRules[rule[2]](rule[1],body,actor);} else if(batch){if(!body||Object.keys(body).some(k=>!['version','idempotencyKey','resolution','note'].includes(k)))fail('核验内容无效。');result=orderRules.resolve(batch[1],body,actor,{controlled:true});} else if(recheck){if(!body||Object.keys(body).some(k=>k!=='note'))fail('重新识别内容无效。');result=orderRules.recheck(recheck[1],body,actor);} diff --git a/src/modules/order-rules/catalog.cjs b/src/modules/order-rules/catalog.cjs index 07ae58b..add34d9 100644 --- a/src/modules/order-rules/catalog.cjs +++ b/src/modules/order-rules/catalog.cjs @@ -32,6 +32,7 @@ function seedRules() { archiveDirectory: '', filenameDate: '', subjectPrefix: `【${name}】`, intro: `大家好:\n以下为${name},请查收!`, signature: '', to: [], cc: [], attachPdf: id.endsWith('-change'), sourceRow: index + 2, + huizhouEnabled: false, huizhouTemplateId: '', })); } diff --git a/src/modules/order-rules/validation.cjs b/src/modules/order-rules/validation.cjs index d6bbd36..a7541f8 100644 --- a/src/modules/order-rules/validation.cjs +++ b/src/modules/order-rules/validation.cjs @@ -1,7 +1,7 @@ 'use strict'; const {normalizeScopes}=require('./scopes.cjs'); const fail=(message,status=400)=>{throw Object.assign(new Error(message),{status});}; -const fields=['id','version','name','categoryId','processNames','nodeNames','adapterIds','archiveDirectory','filenameDate','subjectPrefix','intro','signature','to','cc','attachPdf','sourceRow','bodyTemplateId']; +const fields=['id','version','name','categoryId','processNames','nodeNames','adapterIds','archiveDirectory','filenameDate','subjectPrefix','intro','signature','to','cc','attachPdf','sourceRow','bodyTemplateId','huizhouEnabled','huizhouTemplateId']; function addresses(values){ if(!Array.isArray(values)||values.length>500)fail('收件名单格式无效。'); return [...new Set(values.map(v=>{ @@ -14,6 +14,9 @@ function validateRule(input,old){ if(!old||input.id!==old.id||input.categoryId!==old.categoryId)fail('规则类别标识不能修改。'); if(input.version!==old.version)fail('规则已被其他人修改,请刷新后重试。',409); const rule=Object.fromEntries(fields.map(k=>[k,input[k]??old[k]])); + for(const [key,fallback] of [['huizhouEnabled',false],['huizhouTemplateId','']])rule[key]=input[key]!==undefined?input[key]:old[key]!==undefined?old[key]:fallback; + if(typeof rule.huizhouEnabled!=='boolean')fail('惠州通知开关无效。'); + if(typeof rule.huizhouTemplateId!=='string'||rule.huizhouTemplateId.length>100||!/^[\w-]*$/.test(rule.huizhouTemplateId))fail('请选择有效的惠州邮件模板。'); if(rule.bodyTemplateId!==undefined&&(typeof rule.bodyTemplateId!=='string'||rule.bodyTemplateId.length>100||!/^[\w-]*$/.test(rule.bodyTemplateId)))fail('请选择有效的邮件模板。'); if(Object.hasOwn(input,'scopes')&&input.scopes!==undefined){ rule.scopes=normalizeScopes(input.scopes); @@ -35,6 +38,7 @@ function validateRule(input,old){ } function publicationIssues(rule,adapters){ const issues=[]; + if(rule.huizhouEnabled===true&&!rule.huizhouTemplateId)issues.push('开启惠州通知时请选择惠州邮件模板'); if(!rule.processNames.length||!rule.nodeNames.length)issues.push('请选择适用流程和到达节点'); if(!rule.subjectPrefix)issues.push('请填写邮件主题前缀'); if(!rule.archiveDirectory||!/^\\\\[^\\]+\\[^\\]+/.test(rule.archiveDirectory)||/(?:^|[\\/])\.\.(?:[\\/]|$)/.test(rule.archiveDirectory))issues.push('请选择完整服务器共享归档目录'); diff --git a/tests/mail/huizhou-template.test.cjs b/tests/mail/huizhou-template.test.cjs new file mode 100644 index 0000000..763a69d --- /dev/null +++ b/tests/mail/huizhou-template.test.cjs @@ -0,0 +1,35 @@ +'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 {DatabaseSync}=require('node:sqlite'); +const {BpmVault}=require('../../src/platform/security/vault.cjs'); +const {MailStore}=require('../../src/modules/mail/store.cjs'); +const {ruleTemplate}=require('../../src/modules/mail/rule-template.cjs'); +function fixture(t){const dir=fs.mkdtempSync(path.join(os.tmpdir(),'hui-template-'));let store=new MailStore(dir);const channel=store.saveChannel({readOnly:true,name:'test',email:'orders@example.test',imap:{host:'imap.example.test',port:993,security:'tls',user:'orders',password:'isolated-test'}});let uid=0;t.after(()=>{store.close();fs.rmSync(dir,{recursive:true,force:true});});return {dir,get store(){return store;},channel,draft(){const n=++uid;return store.ingest(channel.id,'test',n,{scope:'scope',subject:'Notice',text:'Body {{订单号}}',html:'',sender:'author@example.test',attachments:[]},Buffer.from('isolated '+n),channel.version);},confirm(d,mode){return store.confirm(d.id,{version:d.version,scope:d.scope,subject:d.subject,useText:false,...(mode===undefined?{}:{notificationMode:mode})},'admin');},reopen(){store.close();store=new MailStore(dir);return store;}};} +test('legacy template migration defaults to normal without rewriting payloads or versions',t=>{ + const dir=fs.mkdtempSync(path.join(os.tmpdir(),'hui-legacy-')),vault=new BpmVault({stateDir:path.join(dir,'secrets')}),db=new DatabaseSync(path.join(dir,'mail.sqlite')); + db.exec("CREATE TABLE templates(id TEXT PRIMARY KEY,channel_id TEXT NOT NULL,source_key TEXT NOT NULL,scope TEXT NOT NULL,status TEXT NOT NULL,version INTEGER NOT NULL,base_id TEXT,payload BLOB NOT NULL,created_at TEXT NOT NULL,summary TEXT NOT NULL DEFAULT '{}',UNIQUE(channel_id,source_key)); CREATE UNIQUE INDEX active_template ON templates(channel_id,scope) WHERE status='active'"); + const payload={subject:'Legacy',text:'original body',html:'',sender:'author@example.test',attachments:[]},encrypted=vault.encode('old',payload); + db.prepare('INSERT INTO templates VALUES(?,?,?,?,?,?,?,?,?,?)').run('old','legacy','source','scope','active',7,null,encrypted,'2026-10-01T00:00:00Z',JSON.stringify({subject:'Legacy',attachmentCount:0}));db.close();vault.destroy(); + const store=new MailStore(dir);t.after(()=>{store.close();fs.rmSync(dir,{recursive:true,force:true});}); + assert.equal(store.template('old').notificationMode,'normal');assert.equal(store.templates()[0].notificationMode,'normal');assert.equal(store.template('old').version,7);assert.equal(store.template('old').text,'original body');assert.deepEqual(Buffer.from(store.db.prepare('SELECT payload FROM templates WHERE id=?').get('old').payload),Buffer.from(encrypted)); +}); +test('confirming and replacing templates archives only the same notification mode and survives reopen',t=>{ + const f=fixture(t),normal=f.confirm(f.draft()),hui=f.confirm(f.draft(),'huizhou'); + assert.equal(f.store.template(normal.id).status,'active');assert.equal(hui.notificationMode,'huizhou');assert.equal(f.store.active(f.channel.id,'scope').id,normal.id);assert.equal(f.store.active(f.channel.id,'scope','huizhou').id,hui.id); + const hui2=f.confirm(f.draft(),'huizhou');assert.equal(f.store.template(hui.id).status,'archived');assert.equal(f.store.template(normal.id).status,'active'); + f.reopen();assert.equal(f.store.templates().find(t=>t.id===hui2.id).notificationMode,'huizhou');assert.equal(f.store.active(f.channel.id,'scope').id,normal.id); +}); +test('mode confirmation rejects invalid values and concurrent replacements within the selected mode',t=>{ + const f=fixture(t),d=f.draft();for(const mode of ['',null,false,'HUIZHOU','other'])assert.throws(()=>f.confirm(d,mode),e=>e.status===400); + f.confirm(d,'huizhou');const a=f.draft(),b=f.draft();f.confirm(a,'huizhou');assert.throws(()=>f.confirm(b,'huizhou'),e=>e.status===409); +}); +test('resolver isolates modes, requires explicit Hui selection and rejects inactive selections',t=>{ + const f=fixture(t),normal=f.confirm(f.draft()),hui=f.confirm(f.draft(),'huizhou'),rule={bodyTemplateId:normal.id,huizhouEnabled:true,huizhouTemplateId:hui.id,to:['owner@example.test'],cc:['copy@example.test']}; + assert.equal(ruleTemplate(f.store,'bs-change',rule).id,normal.id);assert.equal(ruleTemplate(f.store,'bs-change',rule,'huizhou').id,hui.id); + assert.equal(ruleTemplate(f.store,'bs-change',{...rule,huizhouEnabled:false},'huizhou'),null); + assert.throws(()=>ruleTemplate(f.store,'bs-change',{...rule,huizhouTemplateId:''},'huizhou'),e=>e.status===409); + assert.throws(()=>ruleTemplate(f.store,'bs-change',{...rule,bodyTemplateId:hui.id}),e=>e.status===409); + assert.throws(()=>ruleTemplate(f.store,'bs-change',{...rule,huizhouTemplateId:normal.id},'huizhou'),e=>e.status===409); + assert.throws(()=>f.store.bindCategory({categoryId:'bs-change',templateId:hui.id,version:0}),e=>e.status===409); + f.confirm(f.draft(),'huizhou');assert.throws(()=>ruleTemplate(f.store,'bs-change',rule,'huizhou'),e=>e.status===409);assert.equal(ruleTemplate(f.store,'bs-change',rule).id,normal.id); +}); diff --git a/tests/order-rules/huizhou-config.test.cjs b/tests/order-rules/huizhou-config.test.cjs new file mode 100644 index 0000000..254b6af --- /dev/null +++ b/tests/order-rules/huizhou-config.test.cjs @@ -0,0 +1,40 @@ +'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 {RuleStore}=require('../../src/modules/order-rules/store.cjs'),{MailStore}=require('../../src/modules/mail/store.cjs'); +const {orderRuleApi}=require('../../src/modules/order-rules/api.cjs'); +const {activateReferenceMapping}=require('../fixtures/activate-field-mapping.cjs'); +function fixture(t){const dir=fs.mkdtempSync(path.join(os.tmpdir(),'hui-config-'));let rules=new RuleStore(dir);const mail=new MailStore(dir),channel=mail.saveChannel({readOnly:true,name:'test',email:'orders@example.test',imap:{host:'imap.example.test',port:993,security:'tls',user:'orders',password:'isolated-test'}});let uid=0;t.after(()=>{rules.close();mail.close();fs.rmSync(dir,{recursive:true,force:true});});return {get rules(){return rules;},mail,template(mode='normal'){const n=++uid,d=mail.ingest(channel.id,'test',n,{subject:'Notice',scope:'',text:'Body',html:'',sender:'author@example.test',attachments:[]},Buffer.from('test '+n),1);return mail.confirm(d.id,{version:1,subject:'Notice',scope:'',useText:false,notificationMode:mode},'admin');},reopen(){rules.close();rules=new RuleStore(dir);},async call(route,body,role='admin',withMail=true){let result;await orderRuleApi({orderRules:rules,mail:withMail?{store:mail}:null,user:{username:'admin',role},route,method:'POST',body,reply:(status,value)=>{result={status,value};}});return result;}};} +test('old rules default Hui off and settings persist without accepting separate recipients',t=>{ + const f=fixture(t),old=f.rules.get('rules','bs-change').draft;assert.equal(old.huizhouEnabled,false);assert.equal(old.huizhouTemplateId,''); + const legacy={...old};delete legacy.huizhouEnabled;delete legacy.huizhouTemplateId;f.rules.put('rules',{...f.rules.get('rules',old.id),draft:legacy}); + const saved=f.rules.saveRule({...legacy,huizhouTo:['intruder@example.test'],huizhouCc:['intruder@example.test']},'admin');assert.equal(saved.huizhouEnabled,false);assert.equal(saved.huizhouTemplateId,'');assert.equal(saved.huizhouTo,undefined);assert.equal(saved.huizhouCc,undefined); + const enabled=f.rules.saveRule({...saved,huizhouEnabled:true,huizhouTemplateId:'selected',to:['owner@example.test'],cc:['copy@example.test']},'admin');f.reopen();const restored=f.rules.snapshot().rules.find(r=>r.id===old.id);assert.equal(restored.huizhouEnabled,true);assert.equal(restored.huizhouTemplateId,'selected');assert.deepEqual(restored.to,enabled.to);assert.deepEqual(restored.cc,enabled.cc); +}); +test('invalid Hui booleans and template identifiers are rejected atomically',t=>{ + const f=fixture(t),old=f.rules.get('rules','bs-change').draft; + for(const patch of [{huizhouEnabled:'true'},{huizhouEnabled:1},{huizhouEnabled:null},{huizhouTemplateId:1},{huizhouTemplateId:null},{huizhouTemplateId:'bad/id'},{huizhouTemplateId:'x'.repeat(101)}])assert.throws(()=>f.rules.saveRule({...old,...patch},'admin'),e=>e.status===400); + assert.equal(f.rules.get('rules',old.id).draft.version,old.version); +}); +test('GET projects missing legacy Hui fields as off without rewriting persisted snapshots',async t=>{ + const f=fixture(t),record=f.rules.get('rules','bs-change');delete record.draft.huizhouEnabled;delete record.draft.huizhouTemplateId;f.rules.put('rules',record);let snapshot; + await orderRuleApi({orderRules:f.rules,user:{username:'admin',role:'admin'},route:'/api/order-rules',method:'GET',reply:(status,value)=>{snapshot=value;}}); + const rule=snapshot.rules.find(r=>r.id==='bs-change');assert.equal(rule.huizhouEnabled,false);assert.equal(rule.huizhouTemplateId,'');assert.equal(f.rules.get('rules','bs-change').draft.huizhouEnabled,undefined); +}); +test('save API validates effective Hui selection including partial saves and unavailable mail',async t=>{ + const f=fixture(t),normal=f.template(),hui=f.template('huizhou'),old=f.rules.get('rules','bs-change').draft; + for(const patch of [{huizhouEnabled:true,huizhouTemplateId:''},{huizhouEnabled:true,huizhouTemplateId:normal.id},{bodyTemplateId:hui.id}])await assert.rejects(f.call('/api/order-rules/rules',{...old,...patch}),e=>e.status===409); + await assert.rejects(f.call('/api/order-rules/rules',{...old,huizhouEnabled:true,huizhouTemplateId:hui.id},'admin',false),e=>e.status===503); + const saved=(await f.call('/api/order-rules/rules',{...old,bodyTemplateId:normal.id,huizhouEnabled:true,huizhouTemplateId:hui.id})).value; + f.template('huizhou');await assert.rejects(f.call('/api/order-rules/rules',{id:saved.id,categoryId:saved.categoryId,version:saved.version,name:'partial edit'}),e=>e.status===409); + await assert.rejects(f.call('/api/order-rules/rules',{...saved,huizhouEnabled:false},'viewer'),e=>e.status===403); +}); +test('publish and resume recheck Hui templates using draft and published snapshot respectively',async t=>{ + const f=fixture(t),normal=f.template(),hui=f.template('huizhou'),{captured}=activateReferenceMapping(f.rules),old=f.rules.get('rules','bs-change').draft; + const saved=(await f.call('/api/order-rules/rules',{...old,to:['owner@example.test'],archiveDirectory:'\\\\server\\share',filenameDate:'receivedAt',bodyTemplateId:normal.id,huizhouEnabled:true,huizhouTemplateId:hui.id})).value; + f.rules.trial(saved.id,{version:saved.version,sampleId:captured.id});f.mail.db.prepare("UPDATE templates SET status='archived' WHERE id=?").run(hui.id); + await assert.rejects(f.call('/api/order-rules/rules/bs-change/publish',{version:saved.version}),e=>e.status===409);assert.equal(f.rules.get('rules',saved.id).published,null); + f.mail.db.prepare("UPDATE templates SET status='active' WHERE id=?").run(hui.id);await f.call('/api/order-rules/rules/bs-change/publish',{version:saved.version});await f.call('/api/order-rules/rules/bs-change/pause',{version:saved.version}); + const edited=f.rules.saveRule({...saved,huizhouEnabled:false},'admin'),record=f.rules.get('rules',saved.id),input={version:edited.version,publishedVersion:saved.version,activationVersion:record.activationVersion}; + f.template('huizhou');await assert.rejects(f.call('/api/order-rules/rules/bs-change/resume',input),e=>e.status===409);assert.equal(f.rules.get('rules',saved.id).published.status,'paused'); + await assert.rejects(f.call('/api/order-rules/rules/bs-change/resume',input,'admin',false),e=>e.status===503); +});