fix: connect Excel rule activation to the existing test workflow
This commit is contained in:
1 parent
18a2e4eda7
commit
8b2339ec81
17 files changed
+309
-40
No files matched your search
@@ -34,7 +34,11 @@ async function orderRuleApi({orderRules,mail,workspace,user,route,method,body,re
|
||||
result=orderRules.saveRestrictedTest(body,user);
|
||||
}
|
||||
else 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,{mail});
|
||||
else if(route==='/api/order-rules/import/commit')result=require('./import.cjs').commitImport(orderRules,body,actor,{mail,user});
|
||||
else if(route==='/api/order-rules/restricted-test/apply'){
|
||||
for(const item of Array.isArray(body?.rules)?body.rules:[]){const record=orderRules.get('rules',item?.id);if(record)checkTemplates(mail,record.draft);}
|
||||
result=orderRules.applyRestrictedDrafts(body,user);
|
||||
}
|
||||
else if(route==='/api/order-rules/rules'){
|
||||
const old=orderRules.get('rules',body?.id)?.draft;
|
||||
if(old)checkTemplates(mail,validateRule(body,old));
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
'use strict';
|
||||
async function template(store){
|
||||
const Excel=require('exceljs'),book=new Excel.Workbook(),sheet=book.addWorksheet('分类规则');
|
||||
// This endpoint only needs the in-memory workbook API. The vendor bundle
|
||||
// preserves formatting without hundreds of synchronous cold file loads.
|
||||
const Excel=require('exceljs/dist/exceljs.min.js'),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]||'']);
|
||||
|
||||
@@ -2,7 +2,9 @@
|
||||
const crypto=require('node:crypto');
|
||||
const {validateRule,addresses,fail}=require('./validation.cjs');
|
||||
const {checkTemplates}=require('./template-validation.cjs');
|
||||
const split=value=>String(value||'').split(/[\n/+]/).map(v=>v.trim().replace(/^[“"「]|[”"」]$/g,'')).filter(Boolean);
|
||||
// Match the authoritative source-workbook reader's canonical text, without
|
||||
// treating different business node names as aliases.
|
||||
const split=value=>String(value||'').normalize('NFKC').split(/[\n/+]/).map(v=>v.trim().replace(/^[“”"'「」]+|[“”"'「」]+$/g,'').trim()).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=[];
|
||||
@@ -26,15 +28,17 @@ function previewImport(store,input,actor){
|
||||
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]};});
|
||||
if(get('流程节点配对'))scopes=get('流程节点配对').split('\n').filter(v=>v.trim()).map(v=>{const pair=v.split('→').map(s=>s.normalize('NFKC').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('邮件正文描述未自动转换,保留原附件设置');}
|
||||
if(headers.includes('附带PDF')){const value=get('附带PDF');if(!['是','否','true','false'].includes(value))fail('附带PDF请填写是或否');if(['是','true'].includes(value))row.warnings.push('PDF 仅归档,不附在通知邮件中;已忽略表内的附带PDF要求');}
|
||||
else if(headers.includes('邮件正文')){const value=get('邮件正文');if(/PDF/i.test(value))row.warnings.push('PDF 仅归档,不附在通知邮件中;正文继续使用分类模板和BPM摘要');else if(!/摘要信息/.test(value))row.warnings.push('邮件正文描述未自动转换,保留原分类模板和摘要设置');}
|
||||
candidate.attachPdf=false;
|
||||
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;
|
||||
row.preview={scopes:structuredClone(candidate.scopes),subjectPrefix:candidate.subjectPrefix,archiveDirectory:candidate.archiveDirectory,to:[...candidate.to],cc:[...candidate.cc],attachPdf:false};
|
||||
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步选择存储服务器和目录');
|
||||
@@ -43,19 +47,21 @@ function previewImport(store,input,actor){
|
||||
}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};
|
||||
const test=store.restrictedTest?.();
|
||||
const id=crypto.randomUUID(),canCommit=rows.every(r=>!r.issues.length),plan={id,actor,createdAt:store.now(),canCommit,rows,...test?.enabled?{testVersion:test.version}:{}};
|
||||
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,{mail}={}){return store.transaction(()=>{
|
||||
if(!input||Object.keys(input).some(k=>k!=='id')||typeof input.id!=='string')fail('请选择已检查的导入预览');
|
||||
function publicPlan(plan){return {id:plan.id,canCommit:plan.canCommit,...plan.testVersion!==undefined?{testVersion:plan.testVersion}:{},rows:plan.rows.map(({candidate,...row})=>row)};}
|
||||
function commitImport(store,input,actor,{mail,user}={}){return store.transaction(()=>{
|
||||
if(!input||Object.keys(input).some(k=>!['id','applyToTest'].includes(k))||typeof input.id!=='string'||input.applyToTest!==undefined&&typeof input.applyToTest!=='boolean')fail('请选择已检查的导入预览');
|
||||
const plan=store.get('rule-imports',input.id);if(!plan||plan.actor!==actor)fail('导入预览不存在,请重新选择文件',404);
|
||||
if(plan.result)return plan.result;
|
||||
if(plan.result){if(Boolean(input.applyToTest)!==Boolean(plan.result.applied))fail('此预览已按其他方式导入,请重新预览。',409);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 {rule}of prepared)checkTemplates(mail,rule);
|
||||
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;
|
||||
if(input.applyToTest){if(plan.testVersion===undefined)fail('此预览没有有效的测试版本,请重新预览。',409);store.applyRestrictedDrafts({version:plan.testVersion,rules:prepared.map(({record,rule})=>({id:record.id,version:rule.version}))},user);}
|
||||
plan.result={id:plan.id,count:prepared.length,...input.applyToTest?{applied:true}:{}};store.put('rule-imports',plan);store.audit(actor,'Excel 导入分类草稿',String(prepared.length)+' 类');return plan.result;
|
||||
});}
|
||||
module.exports={previewImport,commitImport};
|
||||
@@ -29,6 +29,43 @@ function executionRule(store,record){
|
||||
const run=state(store);if(!run)return record?.published||null;
|
||||
const rule=run.rules.find(r=>r.id===record?.id);return rule&&validRule(store,rule,run)?structuredClone(rule):null;
|
||||
}
|
||||
function applyDrafts(store,input,actor){
|
||||
if(actor?.role!=='admin'||!actor.username)fail('仅管理员可应用测试规则。',403);
|
||||
return store.transaction(()=>{
|
||||
const run=state(store);
|
||||
if(!run?.enabled||!input||Object.keys(input).some(k=>!['version','rules'].includes(k))||input.version!==run.version)fail('测试配置已变化或已暂停,请刷新。',409);
|
||||
if(!Array.isArray(input.rules)||!input.rules.length||input.rules.length>100||new Set(input.rules.map(r=>r?.id)).size!==input.rules.length)fail('请选择唯一的规则版本。');
|
||||
const next=structuredClone(run),adapters=store.adapters();
|
||||
for(const item of input.rules){
|
||||
if(!item||Object.keys(item).some(k=>!['id','version'].includes(k))||typeof item.id!=='string'||!/^[\w-]{1,100}$/.test(item.id)||!Number.isSafeInteger(item.version))fail('规则版本格式无效。');
|
||||
const record=store.get('rules',item.id),index=next.rules.findIndex(r=>r.id===item.id);
|
||||
if(!record||record.draft.version!==item.version||index<0)fail('规则已变化或不在当前测试范围,请刷新。',409);
|
||||
const draft=record.draft,binding=next.rules[index];
|
||||
if(run.rules[index].version!==draft.version){
|
||||
const unfinished=order=>order?.ruleSnapshot?.testRunId===run.id&&['normal','huizhou'].some(mode=>{const value=require('./delivery.cjs').delivery(order,mode);return value&&!value.batchId&&!['sent','ignored','unknown','not_applicable','disabled','empty'].includes(value.status);});
|
||||
const pending=store.all('orders').some(order=>order.categoryId===item.id&&unfinished(order));
|
||||
const tasks=store.all('execution-tasks').some(task=>{
|
||||
if(!task.categoryIds?.includes(item.id)||['sent','ignored'].includes(task.status))return false;
|
||||
const order=task.orderId&&store.get('orders',task.orderId);return !order||unfinished(order);
|
||||
});
|
||||
if(pending||tasks)fail('此类别仍有旧规则订单或未完成任务,请先完成或人工处理后再应用新版本。',409);
|
||||
}
|
||||
const selected=adapters.filter(a=>a.verified&&!a.reference&&draft.adapterIds.includes(a.id)&&draft.processNames.includes(a.processName)&&evidence(store,a));
|
||||
if(!selected.length)fail('规则缺少已核实的字段适配:'+draft.name,409);
|
||||
const rule={...structuredClone(draft),status:'enabled',to:[run.recipient],cc:[],attachPdf:false,archiveDirectory:binding.archiveDirectory,productLine:draft.productLine||binding.productLine,testRunId:run.id,testSince:run.since,testArchiveRoot:run.archiveRoot,adapterIds:selected.map(a=>a.id),scopes:structuredClone(scopesFor(draft))};
|
||||
const covered=rule.processNames.filter(p=>selected.some(a=>a.processName===p));
|
||||
const issues=publicationIssues({...rule,processNames:covered},adapters);if(issues.length)fail(issues.join(';'),409);
|
||||
assertPath(store,rule.archiveDirectory,run);next.rules[index]=rule;next.adapterHashes[rule.id]=hash(rule.adapterIds.map(id=>adapters.find(a=>a.id===id)));
|
||||
}
|
||||
for(let i=0;i<next.rules.length;i++)for(let j=i+1;j<next.rules.length;j++)if(require('./scopes.cjs').scopesOverlap(next.rules[i],next.rules[j]))fail('分类存在相同流程和节点,不能应用。',409);
|
||||
next.uncovered=next.rules.flatMap(rule=>rule.processNames.filter(p=>!adapters.some(a=>rule.adapterIds.includes(a.id)&&a.processName===p)).map(processName=>({categoryId:rule.id,processName})));
|
||||
// Keep the previous approved versions for existing tasks and frozen batches.
|
||||
// The current execution snapshot alone changes; identities and baseline do not.
|
||||
store.put('restricted-test-history',{id:run.id+':'+run.version,value:run});next.version++;
|
||||
store.put('restricted-test',{id:'main',value:next});store.audit(actor.username,'应用Excel分类到测试',input.rules.map(r=>r.id+' v'+r.version).join(','));
|
||||
return {applied:true,count:input.rules.length,test:summary(store)};
|
||||
});
|
||||
}
|
||||
function save(store,input,actor){
|
||||
if(actor?.role!=='admin'||!actor.username)fail('仅管理员可以维护受限测试。',403);
|
||||
return store.transaction(()=>{
|
||||
@@ -66,7 +103,11 @@ function save(store,input,actor){
|
||||
function assertRule(store,rule,run=state(store)){
|
||||
if(!run){if(rule?.testRunId)fail('测试配置不存在,禁止按正式规则继续执行。',409);return;}
|
||||
if(!run.enabled||rule?.testRunId!==run.id||rule.testArchiveRoot!==run.archiveRoot)fail('受限测试已暂停或执行快照不一致。',409);
|
||||
const frozen=run.rules.find(r=>r.id===rule.id);if(frozen&&(!validRule(store,frozen,run)||hash(frozen)!==hash(rule)))fail('受限测试字段或规则快照已变化。',409);
|
||||
const frozen=run.rules.find(r=>r.id===rule.id);
|
||||
if(frozen?(!validRule(store,frozen,run)||hash(frozen)!==hash(rule)):state(store)?.id===run.id){
|
||||
const approved=store.all('restricted-test-history').some(row=>row.value?.id===run.id&&row.value.rules.some(previous=>previous.id===rule.id&&validRule(store,previous,row.value)&&hash(previous)===hash(rule)));
|
||||
if(!approved)fail('受限测试字段或规则快照已变化。',409);
|
||||
}
|
||||
if(rule.to?.length!==1||rule.to[0]!==run.recipient||rule.cc?.length)fail('受限测试收件人必须为固定QQ且无抄送。',409);
|
||||
assertPath(store,rule.archiveDirectory,run);
|
||||
}
|
||||
@@ -137,4 +178,4 @@ function admitCurrent(store,rows,actor){
|
||||
return structuredClone(entries);
|
||||
});
|
||||
}
|
||||
module.exports={state,summary,save,executionRule,assertPath,assertRule,assertEvent,assertOrder,assertBatch,recordCurrentScan,admitCurrent,eventTime,orderTime,isAdmitted,eventInWindow,orderInWindow};
|
||||
module.exports={state,summary,save,applyDrafts,executionRule,assertPath,assertRule,assertEvent,assertOrder,assertBatch,recordCurrentScan,admitCurrent,eventTime,orderTime,isAdmitted,eventInWindow,orderInWindow};
|
||||
@@ -48,6 +48,7 @@ class RuleStore{
|
||||
now(){return this.clock().toISOString();}
|
||||
restrictedTest(){return require('./restricted-test.cjs').summary(this);}
|
||||
saveRestrictedTest(input,actor){return require('./restricted-test.cjs').save(this,input,actor);}
|
||||
applyRestrictedDrafts(input,actor){return require('./restricted-test.cjs').applyDrafts(this,input,actor);}
|
||||
executionRule(record){return require('./restricted-test.cjs').executionRule(this,record);}
|
||||
providersReady(){return ['liveTodo','pdfExport','automaticArchive'].every(key=>this.capabilities[key]===true);}
|
||||
adapters(){return registry.registry(this);}
|
||||
@@ -83,7 +84,7 @@ class RuleStore{
|
||||
queryRevision(){return Number(this.db.prepare('SELECT total_changes() AS revision').get().revision);}
|
||||
snapshot({includeRecords=true}={}){
|
||||
const adapters=this.adapters(),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,mappingIssue:record.mappingIssue||null,explanation:describeRule(record.draft),validationIssues:publicationIssues(record.draft,adapters)}));
|
||||
const restrictedTest=typeof this.restrictedTest==='function'?this.restrictedTest():null;for(const rule of rules)if(restrictedTest){const active=typeof this.executionRule==='function'?this.executionRule({id:rule.id}):null;rule.testStatus=active?'enabled':'paused';}
|
||||
const restrictedTest=typeof this.restrictedTest==='function'?this.restrictedTest():null;for(const rule of rules)if(restrictedTest){const active=typeof this.executionRule==='function'?this.executionRule({id:rule.id}):null;rule.testStatus=active?'enabled':'paused';rule.testVersion=active?.version||null;rule.testHasDraft=!active||active.version!==rule.version;}
|
||||
return {rules,restrictedTest,adapters,orders:includeRecords?this.all('orders').reverse():[],batches:includeRecords?this.all('batches').reverse():[],settings:this.settings(),audit:includeRecords?this.all('audit').slice(-100).reverse():[],capabilities:copy(this.capabilities),window:upcomingWindow(this.clock(),this.schedule(),this.calendar())};
|
||||
}
|
||||
saveRule(input,actor){return this.transaction(()=>{
|
||||
|
||||
Reference in new issue
Block a user