feat: simplify category rule configuration and add safe Excel import
This commit is contained in:
1 parent
fbe39c8267
commit
3846e1598c
31 files changed
+437
-123
No files matched your search
@@ -87,7 +87,7 @@ async function main(options = {}) {
|
||||
orderRules=new RuleStore(path.join(stateDir,'order-rules'),{schedule:()=>store.settings().schedule,calendar:()=>workspace.meta('calendar').overrides});
|
||||
orderProvider=new BpmOrderProvider({manager:bpmSessions});orderArchive=new OrderArchiveProvider({storage,outputDir,journal:orderRules});
|
||||
orderExecution=new OrderExecutionCoordinator({store:orderRules,workspace,provider:orderProvider,archive:orderArchive,mail,dashboard:store,settings:()=>store.settings(),calendar:()=>workspace.meta('calendar').overrides,systemPrincipal:custodian.principal});
|
||||
orderDispatcher=new OrderRuleDispatcher({store:orderRules,mail,settings:()=>store.settings(),calendar:()=>workspace.meta('calendar').overrides,providersReady:()=>{const cap=orderExecution.snapshot().capabilities;return ['liveTodo','pdfExport','automaticArchive'].every(key=>cap?.[key]===true);},templateResolver:categoryId=>mailStore.categoryTemplate(categoryId),attachmentReader:file=>orderArchive.read(file)});
|
||||
orderDispatcher=new OrderRuleDispatcher({store:orderRules,mail,settings:()=>store.settings(),calendar:()=>workspace.meta('calendar').overrides,providersReady:()=>{const cap=orderExecution.snapshot().capabilities;return ['liveTodo','pdfExport','automaticArchive'].every(key=>cap?.[key]===true);},templateResolver:(categoryId,rule)=>require('../modules/mail/rule-template.cjs').ruleTemplate(mailStore,categoryId,rule),attachmentReader:file=>orderArchive.read(file)});
|
||||
assistantStore=new AssistantStore(path.join(stateDir,'assistant'));assistantStore.recover();assistant=new AssistantService({store:assistantStore,runtime:new ZcodeRuntime({stateDir:path.join(stateDir,'assistant','runtime')}),dashboard:store,workspace,scanner,storage});
|
||||
health=new RuntimeHealth({stateDir,startedAt,instanceId:watchdog.instanceId,workspace,scanner,storage,mail,execution:orderExecution});
|
||||
await bpmSessions.migrateAccounts(workspace.snapshot().connections);
|
||||
|
||||
@@ -21,6 +21,11 @@ function createAssets(){
|
||||
'/storage-preview.css':{path:path.join(webRoot,'modules/storage/preview.css'),type:'text/css',preview:true},
|
||||
'/order-rules-editor.js':{path:path.join(webRoot,'modules/order-rules/editor.js'),type:'text/javascript'},
|
||||
'/order-rules-scopes.js':{path:path.join(webRoot,'modules/order-rules/scope-editor.js'),type:'text/javascript'},
|
||||
'/order-rules-resources.js':{path:path.join(webRoot,'modules/order-rules/resources.js'),type:'text/javascript'},
|
||||
'/order-rules-import.js':{path:path.join(webRoot,'modules/order-rules/import-view.js'),type:'text/javascript'},
|
||||
'/order-rules-import-worker.js':{path:path.join(webRoot,'modules/order-rules/import-worker.js'),type:'text/javascript'},
|
||||
'/order-rules-import-parser.js':{path:path.join(webRoot,'modules/order-rules/import-parser.js'),type:'text/javascript'},
|
||||
'/vendor/sheetjs.js':{path:require.resolve('xlsx/dist/xlsx.full.min.js'),type:'text/javascript'},
|
||||
'/order-rules-preview.js':{path:path.join(webRoot,'modules/order-rules/preview.js'),type:'text/javascript'},
|
||||
'/order-execution.js':{path:path.join(webRoot,'modules/order-rules/execution.js'),type:'text/javascript'},
|
||||
'/order-notifications-shared.js':{path:path.join(webRoot,'modules/order-notifications/shared.js'),type:'text/javascript'},
|
||||
|
||||
@@ -40,7 +40,7 @@ function createDashboard({store,outputDir,workspace,bpmSessions,mail,scanner,sto
|
||||
if(await storageApi({storage,workspace,user,url,route,method:request.method,body,request,response,reply,trustedProxy}))return;
|
||||
if(await notificationApi({notifications,workspace,user,route,method:request.method,body,reply}))return;
|
||||
if(await orderExecutionApi({execution:orderExecution,orderRules,dispatcher:orderDispatcher,workspace,user,sessionId:token,route,method:request.method,body,reply}))return;
|
||||
if(await orderRuleApi({orderRules,mail,workspace,user,route,method:request.method,body,reply}))return;
|
||||
if(await orderRuleApi({orderRules,mail,workspace,user,route,method:request.method,body,reply,response}))return;
|
||||
if(await assistantApi({assistant,workspace,user,sessionId:token,route,method:request.method,body,request,reply,trustedProxy}))return;
|
||||
if(workspaceApi({workspace,store,user,route,method:request.method,body,reply,bpmSessions}))return;
|
||||
if(await dashboardApi({store,outputDir,workspace,mail,scanner,storage,orderRules,user,route,request,response,body,reply,fail}))return;
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
'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});
|
||||
return template;
|
||||
}
|
||||
module.exports={ruleTemplate};
|
||||
@@ -1,9 +1,13 @@
|
||||
'use strict';
|
||||
const {fail}=require('./validation.cjs');
|
||||
async function orderRuleApi({orderRules,mail,workspace,user,route,method,body,reply}){
|
||||
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,orderRules.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;
|
||||
}
|
||||
if(method!=='POST')fail('没有找到此规则操作。',404);
|
||||
if(user.role==='viewer')fail('只读成员不能编辑规则或提交样本。',403);
|
||||
const actor=user.username;
|
||||
@@ -22,7 +26,12 @@ async function orderRuleApi({orderRules,mail,workspace,user,route,method,body,re
|
||||
}
|
||||
if(user.role!=='admin')fail('仅管理员可维护规则、批次与发送设置。',403);
|
||||
let result;
|
||||
if(route==='/api/order-rules/rules')result=orderRules.saveRule(body,actor);
|
||||
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);}
|
||||
result=orderRules.saveRule(body,actor);
|
||||
}
|
||||
else if(route==='/api/order-rules/settings'){
|
||||
if(body?.enabled){if(!mail)fail('发件邮箱服务未启动。',409);const channel=mail.store.publicChannel(body.channelId);if(!channel.state.smtp)fail('请先验证发件邮箱 SMTP。',409);}
|
||||
result=orderRules.saveSettings(body,actor);
|
||||
@@ -32,10 +41,12 @@ async function orderRuleApi({orderRules,mail,workspace,user,route,method,body,re
|
||||
if(!window?.available||Date.parse(body.cutoff)!==Date.parse(window.end))fail('仅能在配置的发送时点整理本时段订单;更早历史不补发。',409);
|
||||
result=orderRules.prepare(body.cutoff,actor,window);
|
||||
}else{
|
||||
const rule=/^\/api\/order-rules\/rules\/([\w-]+)\/(publish|pause)$/.exec(route);
|
||||
const rule=/^\/api\/order-rules\/rules\/([\w-]+)\/(publish|pause|resume)$/.exec(route);
|
||||
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=>k!=='version'))fail('请提供当前草稿版本。');if(rule[2]==='publish'){const record=orderRules.get('rules',rule[1]);if(!record?.trialSampleId||!orderRules.get('capture-samples',record.trialSampleId))fail('发布前必须选择服务端真实采集样本完成试运行。',409);}result=orderRules[rule[2]](rule[1],body,actor);}
|
||||
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);}
|
||||
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);}
|
||||
else fail('没有找到此规则操作。',404);
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
'use strict';
|
||||
async function template(store){
|
||||
const Excel=require('exceljs'),book=new Excel.Workbook(),sheet=book.addWorksheet('分类规则');
|
||||
sheet.columns=['类别编号','分类名称','订单评审流程','电子流状态','流程节点配对','服务器存档地址','邮件命名','收件人','抄送人','附带PDF','文件名日期'].map(header=>({header,width:['收件人','流程节点配对'].includes(header)?60:28}));
|
||||
const dates={appDate:'申请日期',receivedAt:'接收日期',archiveDate:'归档日期'};
|
||||
for(const {draft:r}of store.all('rules'))sheet.addRow([r.id,r.name,r.processNames.join('/'),r.nodeNames.join('/'),require('./scopes.cjs').scopesFor(r).map(s=>s.processName+' → '+s.nodeName).join('\n'),r.archiveDirectory,r.subjectPrefix,r.to.join('\n'),r.cc.join('\n'),r.attachPdf?'是':'否',dates[r.filenameDate]||'']);
|
||||
sheet.views=[{state:'frozen',ySplit:1}];sheet.getRow(1).font={bold:true};sheet.eachRow(row=>row.alignment={vertical:'top',wrapText:true});sheet.autoFilter='A1:K1';
|
||||
return Buffer.from(await book.xlsx.writeBuffer());
|
||||
}
|
||||
module.exports={template};
|
||||
@@ -0,0 +1,59 @@
|
||||
'use strict';
|
||||
const crypto=require('node:crypto');
|
||||
const {validateRule,addresses,fail}=require('./validation.cjs');
|
||||
const split=value=>String(value||'').split(/[\n/+]/).map(v=>v.trim().replace(/^[“"「]|[”"」]$/g,'')).filter(Boolean);
|
||||
function recipients(value){
|
||||
const text=String(value||'').trim();if(!text)return [];if(!text.includes('@'))fail('收件人未识别到有效邮箱');
|
||||
const parsed=require('nodemailer/lib/addressparser')(text.replace(/[,;\n]/g,',')),values=[];
|
||||
const collect=items=>{for(const item of items){if(item.group)collect(item.group);else values.push(item.address);}};collect(parsed);
|
||||
if(!values.length)fail('收件人未识别到有效邮箱');return addresses(values);
|
||||
}
|
||||
function previewImport(store,input,actor){
|
||||
if(!input||Object.keys(input).some(k=>k!=='rows')||!Array.isArray(input.rows)||input.rows.length<2||input.rows.length>201||input.rows.some(r=>!Array.isArray(r)||r.length>20||r.some(c=>typeof c!=='string'&&typeof c!=='number'||String(c).length>20000)))fail('请导入不超过 200 行、20 列的分类表格。');
|
||||
const headers=input.rows[0].map(v=>String(v).trim());if(new Set(headers.filter(Boolean)).size!==headers.filter(Boolean).length)fail('Excel 列名重复,请检查表头。');
|
||||
for(const name of ['订单评审流程','电子流状态','邮件命名','收件人'])if(!headers.includes(name))fail('缺少 Excel 列:'+name);
|
||||
const originals=store.all('rules'),rows=[],seen=new Set();
|
||||
input.rows.slice(1).forEach((cells,index)=>{
|
||||
const get=name=>String(cells[headers.indexOf(name)]??'').trim();if(!cells.some(c=>String(c).trim()))return;
|
||||
const row={sourceRow:index+2,name:get('分类名称'),issues:[],warnings:[],changes:[]};rows.push(row);
|
||||
try{
|
||||
const explicit=get('类别编号'),subject=get('邮件命名'),name=row.name||subject.match(/^[【\[](.+?)[】\]]/)?.[1];
|
||||
const matches=explicit?originals.filter(r=>r.id===explicit):originals.filter(r=>r.draft.name===name||r.draft.subjectPrefix===subject.match(/^[【\[].+?[】\]]/)?.[0]);
|
||||
if(matches.length>1)fail('类别名称或主题对应多条规则,请用类别编号明确选择');const record=matches[0];
|
||||
if(!record)fail('未找到对应类别,请使用模板中的类别编号或现有分类名称');
|
||||
if(seen.has(record.id))fail('此类别在 Excel 中重复');seen.add(record.id);row.id=record.id;row.name=record.draft.name;
|
||||
const old=record.draft,processes=split(get('订单评审流程')),nodes=split(get('电子流状态'));if(!processes.length||!nodes.length)fail('流程名和节点名不能为空');
|
||||
const prefix=subject.match(/^[【\[].+?[】\]]/)?.[0]||subject;
|
||||
let scopes=processes.flatMap(processName=>nodes.map(nodeName=>({processName,nodeName})));
|
||||
if(get('流程节点配对'))scopes=get('流程节点配对').split('\n').filter(v=>v.trim()).map(v=>{const pair=v.split('→').map(s=>s.trim());if(pair.length!==2||!pair.every(Boolean))fail('流程节点配对请按“流程名 → 节点名”每行一对填写');return {processName:pair[0],nodeName:pair[1]};});
|
||||
const candidate={...old,name:get('分类名称')||old.name,sourceRow:index+2,subjectPrefix:prefix,to:recipients(get('收件人')),scopes};
|
||||
if(headers.includes('抄送人'))candidate.cc=recipients(get('抄送人'));
|
||||
if(headers.includes('服务器存档地址'))candidate.archiveDirectory=get('服务器存档地址');
|
||||
if(headers.includes('文件名日期')){const dates={'申请日期':'appDate','接收日期':'receivedAt','归档日期':'archiveDate','':'',appDate:'appDate',receivedAt:'receivedAt',archiveDate:'archiveDate'};if(!Object.hasOwn(dates,get('文件名日期')))fail('文件名日期只支持申请日期、接收日期或归档日期');candidate.filenameDate=dates[get('文件名日期')];}
|
||||
if(headers.includes('附带PDF')){const value=get('附带PDF');if(!['是','否','true','false'].includes(value))fail('附带PDF请填写是或否');candidate.attachPdf=['是','true'].includes(value);}
|
||||
else if(headers.includes('邮件正文')){const value=get('邮件正文');if(/附件[::].*PDF/i.test(value))candidate.attachPdf=true;else if(/摘要信息/.test(value))candidate.attachPdf=false;else row.warnings.push('邮件正文描述未自动转换,保留原附件设置');}
|
||||
candidate.adapterIds=[...new Set([...old.adapterIds,...store.adapters().filter(a=>a.verified&&processes.includes(a.processName)).filter(a=>!store.adapters().some(b=>b.id!==a.id&&b.verified&&b.processName===a.processName&&b.processVersion===a.processVersion)).map(a=>a.id)])];
|
||||
Object.assign(candidate,validateRule(candidate,old),{version:old.version});row.candidate=candidate;row.version=old.version;row.recipientCount=candidate.to.length;
|
||||
const labels={name:'分类名称',subjectPrefix:'邮件主题',to:'收件人',cc:'抄送人',archiveDirectory:'归档目录',attachPdf:'PDF附件',filenameDate:'文件名日期',scopes:'流程与节点',adapterIds:'BPM识别配置'};
|
||||
for(const [key,label]of Object.entries(labels))if(JSON.stringify(old[key])!==JSON.stringify(candidate[key]))row.changes.push(label);
|
||||
if(!candidate.archiveDirectory.startsWith('\\\\'))row.warnings.push('表内仅有目录名称,请在第03步选择存储服务器和目录');
|
||||
if(!get('流程节点配对')&&processes.length>1&&nodes.length>1)row.warnings.push('此行多个流程共用多个节点,按所有组合导入,请在第01步检查配对');
|
||||
if(!candidate.filenameDate)row.warnings.push('文件名日期仍待选择');
|
||||
}catch(error){row.issues.push(error.message);}
|
||||
});
|
||||
if(!rows.length)fail('表格没有可导入的分类行');
|
||||
const id=crypto.randomUUID(),canCommit=rows.every(r=>!r.issues.length),plan={id,actor,createdAt:store.now(),canCommit,rows};
|
||||
store.put('rule-imports',plan);return publicPlan(plan);
|
||||
}
|
||||
function publicPlan(plan){return {id:plan.id,canCommit:plan.canCommit,rows:plan.rows.map(({candidate,...row})=>row)};}
|
||||
function commitImport(store,input,actor){return store.transaction(()=>{
|
||||
if(!input||Object.keys(input).some(k=>k!=='id')||typeof input.id!=='string')fail('请选择已检查的导入预览');
|
||||
const plan=store.get('rule-imports',input.id);if(!plan||plan.actor!==actor)fail('导入预览不存在,请重新选择文件',404);
|
||||
if(plan.result)return plan.result;
|
||||
if(Date.parse(store.now())-Date.parse(plan.createdAt)>30*60000)fail('导入预览已过期,请重新选择文件',409);
|
||||
if(!plan.canCommit)fail('请修复 Excel 中的问题后重新导入',409);
|
||||
const prepared=plan.rows.map(row=>{const record=store.get('rules',row.id);return {record,rule:validateRule(row.candidate,record?.draft)};});
|
||||
for(const {record,rule}of prepared){store.put('rule-history',{id:record.id+':'+record.draft.version,rule:record.draft,at:store.now(),actor});record.draft=rule;record.trialVersion=null;record.trialDemo=null;record.trialSampleId=null;store.put('rules',record);}
|
||||
plan.result={id:plan.id,count:prepared.length};store.put('rule-imports',plan);store.audit(actor,'Excel 导入分类草稿',String(prepared.length)+' 类');return plan.result;
|
||||
});}
|
||||
module.exports={previewImport,commitImport};
|
||||
@@ -63,7 +63,7 @@ class RuleStore{
|
||||
this.put('settings',{...input,id:'main',version:old.version+1});this.audit(actor,'保存分类通知设置',input.enabled?'已启用':'已暂停');return this.settings();
|
||||
});}
|
||||
snapshot(){
|
||||
const rules=this.all('rules').map(record=>({...record.draft,status:record.published?.status||'draft',hasDraft:!record.published||record.draft.version!==record.published.version,publishedVersion:record.published?.version||null,trialVersion:record.trialVersion,explanation:describeRule(record.draft),validationIssues:publicationIssues(record.draft,this.adapters())}));
|
||||
const rules=this.all('rules').map(record=>({...record.draft,status:record.published?.status||'draft',activationVersion:record.activationVersion||0,hasDraft:!record.published||record.draft.version!==record.published.version,publishedVersion:record.published?.version||null,trialVersion:record.trialVersion,explanation:describeRule(record.draft),validationIssues:publicationIssues(record.draft,this.adapters())}));
|
||||
return {rules,adapters:this.adapters(),orders:this.all('orders').reverse(),batches:this.all('batches').reverse(),settings:this.settings(),audit:this.all('audit').slice(-100).reverse(),capabilities:copy(this.capabilities),window:upcomingWindow(this.clock(),this.schedule(),this.calendar())};
|
||||
}
|
||||
saveRule(input,actor){return this.transaction(()=>{
|
||||
@@ -86,14 +86,27 @@ class RuleStore{
|
||||
const overlaps=this.all('rules').filter(r=>r.id!==id&&r.published?.status==='enabled'&&scopesOverlap(r.published,record.draft));
|
||||
if(overlaps.length)issues.push('与已启用规则存在流程和节点冲突:'+overlaps.map(r=>r.draft.name).join('、'));
|
||||
if(issues.length)fail(issues.join(';'),409);
|
||||
record.published={...copy(record.draft),status:'enabled',publishedAt:this.now()};this.put('rules',record);
|
||||
record.published={...copy(record.draft),status:'enabled',publishedAt:this.now()};record.publicationSampleId=record.trialSampleId;record.publicationAdaptersHash=digest(record.published.adapterIds.map(id=>this.adapters().find(a=>a.id===id)));record.activationVersion=(record.activationVersion||0)+1;this.put('rules',record);
|
||||
this.put('rule-history',{id:record.id+':'+record.draft.version,rule:copy(record.published),at:this.now(),actor});this.audit(actor,'发布规则',id+' v'+record.draft.version);
|
||||
return this.snapshot().rules.find(r=>r.id===id);
|
||||
});}
|
||||
pause(id,input,actor){return this.transaction(()=>{
|
||||
const record=this.get('rules',id);if(!record)fail('规则不存在。',404);
|
||||
if(input?.version!==record.draft.version)fail('规则已变化,请刷新。',409);
|
||||
if(record.published)record.published.status='paused';this.put('rules',record);this.audit(actor,'暂停规则',id);return this.snapshot().rules.find(r=>r.id===id);
|
||||
if(input.activationVersion!==undefined&&input.activationVersion!==(record.activationVersion||0))fail('启停状态已变化,请刷新。',409);
|
||||
if(record.published)record.published.status='paused';record.activationVersion=(record.activationVersion||0)+1;this.put('rules',record);this.audit(actor,'暂停规则',id);return this.snapshot().rules.find(r=>r.id===id);
|
||||
});}
|
||||
resume(id,input,actor){return this.transaction(()=>{
|
||||
const record=this.get('rules',id);if(!record?.published)fail('此分类尚未发布,请先保存并检查真实订单,再发布启用。',409);
|
||||
if(input?.version!==record.draft.version||input.publishedVersion!==record.published.version||input.activationVersion!==(record.activationVersion||0))fail('规则或启停状态已变化,请刷新。',409);
|
||||
const sample=this.get('capture-samples',record.publicationSampleId||record.trialSampleId||'');
|
||||
const issues=publicationIssues(record.published,this.adapters());
|
||||
if(record.publicationAdaptersHash!==digest(record.published.adapterIds.map(id=>this.adapters().find(a=>a.id===id))))issues.push('BPM 信息识别配置已变化,请重新检查并发布');
|
||||
if(!sample||sample.provenance!=='server-provider'||!previewMatch([record.published],this.adapters(),sample.sample).valid)issues.push('已发布版本需要重新检查真实订单识别结果');
|
||||
const overlaps=this.all('rules').filter(r=>r.id!==id&&r.published?.status==='enabled'&&scopesOverlap(r.published,record.published));
|
||||
if(overlaps.length)issues.push('与其他启用分类的流程节点冲突');
|
||||
if(issues.length)fail(issues.join(';'),409);
|
||||
record.published.status='enabled';record.activationVersion=(record.activationVersion||0)+1;this.put('rules',record);this.audit(actor,'启用已发布规则',id+' v'+record.published.version);return this.snapshot().rules.find(r=>r.id===id);
|
||||
});}
|
||||
matchingPublications(sample){
|
||||
const rules=this.all('rules').filter(r=>r.published).map(r=>r.published);
|
||||
@@ -197,7 +210,7 @@ class RuleStore{
|
||||
let error=!published||published.status!=='enabled'?'该类别规则已暂停。':null;
|
||||
if(!error&&orders.some(o=>o.status!=='pending'))error='本类别存在字段、文件或归档尚未准备完成的订单。';
|
||||
let snapshot;
|
||||
if(!error)try{snapshot=buildBatch(rule,orders,cutoff,{maxMessageBytes:this.settings().maxMessageBytes,window});snapshot=applyBodyTemplate(snapshot,this.templateResolver?.(rule.categoryId),orders,this.settings().maxMessageBytes);}catch(cause){error=cause.message;}
|
||||
if(!error)try{snapshot=buildBatch(rule,orders,cutoff,{maxMessageBytes:this.settings().maxMessageBytes,window});snapshot=applyBodyTemplate(snapshot,this.templateResolver?.(rule.categoryId,rule),orders,this.settings().maxMessageBytes);}catch(cause){error=cause.message;}
|
||||
if(error){for(const order of orders){order.error=error;this.put('orders',order);}continue;}
|
||||
const batch={...snapshot,id:crypto.randomUUID(),version:1,status:'prepared',createdAt:this.now(),ruleSnapshot:copy(rule),channelId:this.settings().channelId,error:null};
|
||||
this.put('batches',batch);
|
||||
|
||||
@@ -16,7 +16,7 @@ function effects(rule,event,store){
|
||||
const file={name:result.filename,path:result.path,size:0,sha256:'0'.repeat(64),kind:'pdf'};
|
||||
const order={id:'simulation',event,ruleSnapshot:rule,status:'pending',archive:{archivedAt:store.now(),files:[file]}};
|
||||
const cutoff=new Date(Math.max(Date.parse(event.receivedAt),Date.parse(store.now()))).toISOString();
|
||||
const snapshot=applyBodyTemplate(buildBatch(rule,[order],cutoff,{maxMessageBytes:store.settings().maxMessageBytes}),store.templateResolver?.(rule.categoryId),[order],store.settings().maxMessageBytes);
|
||||
const snapshot=applyBodyTemplate(buildBatch(rule,[order],cutoff,{maxMessageBytes:store.settings().maxMessageBytes}),store.templateResolver?.(rule.categoryId,rule),[order],store.settings().maxMessageBytes);
|
||||
result.mail={subject:snapshot.subject,text:snapshot.text,to:snapshot.to,cc:snapshot.cc,attachments:snapshot.attachments.map(f=>f.name),template:snapshot.template||null};
|
||||
}catch(error){result.issues.push(error.message);}
|
||||
return result;
|
||||
|
||||
@@ -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'];
|
||||
const fields=['id','version','name','categoryId','processNames','nodeNames','adapterIds','archiveDirectory','filenameDate','subjectPrefix','intro','signature','to','cc','attachPdf','sourceRow','bodyTemplateId'];
|
||||
function addresses(values){
|
||||
if(!Array.isArray(values)||values.length>500)fail('收件名单格式无效。');
|
||||
return [...new Set(values.map(v=>{
|
||||
@@ -14,6 +14,7 @@ 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]]));
|
||||
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);
|
||||
rule.processNames=[...new Set(rule.scopes.map(row=>row.processName))];
|
||||
@@ -45,4 +46,4 @@ function publicationIssues(rule,adapters){
|
||||
if(rule.adapterIds.some(id=>!adapters.some(a=>a.id===id)))issues.push('包含不存在的字段适配器');
|
||||
return issues;
|
||||
}
|
||||
module.exports={fail,validateRule,publicationIssues};
|
||||
module.exports={fail,validateRule,publicationIssues,addresses};
|
||||
Reference in new issue
Block a user