perf: streamline rule reads and unblock background discovery
This commit is contained in:
1 parent
b14fa2f4d1
commit
b17b975812
19 files changed
+263
-42
No files matched your search
@@ -1,5 +1,14 @@
|
||||
# 开发交接(2026-10-23)
|
||||
|
||||
## 2026-10-26 剩余阻塞与读取速度优化
|
||||
|
||||
- 发现屏障独立到discovery-barrier.cjs。停用来源的旧待交付/待处理线索只保留证据,不阻断无关的新批次;活动来源及未移除相关不确定任务仍严格检查。
|
||||
- 后台每30秒触发时整轮共享执行,慢采集期间不再重复排队;stop等待后台完成最终线索回执持久化。三处只读窗口的调用改为直接计算,不再构造完整规则/订单/审计快照。
|
||||
- 适配器、受限运行配置在同一次同步snapshot内复用,独立检查仍每次读取;不缓存跨请求权限、期限或可编辑批次结果。summary只计算一次收集中批次。相同只读数据、固定时钟比较,snapshot适配器读取58→1次、解密1798→31次;摘要中位耗时120.53→8.18ms,完整输出一致。数值是本机副本基准,不承诺所有页面相同比例。
|
||||
- 界面“当前生效类别”不再等同全部流程实单已验证;未覆盖流程说明局部待采样/适配。实时待办正常、零匹配订单且无失败扫描时,顶栏显示待验证;其他失败仍显示受阻,providersReady执行门槛不改。能力提示不再误称PDF为邮件附件。
|
||||
- 旧responsiveness测试补齐当前store接口,强化暂停/关闭/整批发现及零全量快照断言;真实BPM、SMTP、SMB和五天测试设置不用于测试。实际验收及本机更新以忽略目录回执为准。
|
||||
- 最终业务回归118项、未知结果/发现屏障/测试期限保护专项15项通过。独立复核发现的精简snapshot接口兼容回归已恢复可选get防护并单独复验6项;一条旧文案断言按新“当前生效”含义更新后完整重跑通过。未运行旧千项全量。
|
||||
|
||||
## 2026-10-26 审查前两项与依赖修复
|
||||
|
||||
- 原通知任务在及时启动的扫描中被接收后,持久保存intakeWindow和intakeStartedAt;慢列表读取、详情采集、归档及重启均复用原窗口,不因跨过发送后60秒而直接ignored。已接收任务最多沿用既有30分钟发送宽限,超期明确受阻留证。到达截止仍提前5分钟,不接纳任意迟到历史,不扩大已冻结批次,unknown/sent不自动重发。
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
# 逻辑阻塞与读取速度优化
|
||||
|
||||
用户要求审查剩余阻塞、提高速度并精简冗余代码。范围限定为已经复现或测量的路径,不改Excel流程/节点、不补未知历史身份,不放宽PDF归档、unknown和五天期限保护。
|
||||
|
||||
1. 复现停用来源的pending线索阻断无关批次,提取扫描屏障计算:只保留活动来源及未移除相关任务所需来源,原线索保留。
|
||||
2. 复现慢扫描期间后台定时调用重复排队,整轮后台处理共享同一promise;关闭时等待最终线索回执落库。只需窗口的调用直接计算窗口。
|
||||
3. 测量真实只读副本的重复适配器读取,采用单次同步快照上下文复用,不建立跨请求缓存。summary同一次调用复用收集中批次结果。
|
||||
4. 分开“规则已生效”“流程未采样”“运行能力待验证”与实际受阻,保留原权限和执行开关。
|
||||
5. 先失败用例后实现;进行相关回归、独立审查、同一数据/固定时钟前后输出比较。备份更新本机测试副本并核对原配置、签名、标题及测试期限。
|
||||
|
||||
基线b14fa2f。副本性能回执:output/snapshot-read-profile.json;无业务值,仅耗时、读取计数和结果一致性。未采样流程、缺失历史通知身份以及发送结果不明仍须证据或人工核验。
|
||||
+1
-1
@@ -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/dependency-compatibility.test.cjs tests/order-rules/slow-cutoff.test.cjs tests/order-rules/removed-discovery-barrier.test.cjs 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/collecting-batches.test.cjs tests/order-rules/collecting-batches-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/order-rules/snapshot-read-context.test.cjs tests/order-rules/summary.test.cjs tests/order-rules/execution-single-flight.test.cjs tests/order-rules/execution-responsiveness.test.cjs tests/order-rules/readiness-pending-ui.test.cjs tests/dependency-compatibility.test.cjs tests/order-rules/slow-cutoff.test.cjs tests/order-rules/removed-discovery-barrier.test.cjs 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/collecting-batches.test.cjs tests/order-rules/collecting-batches-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": {
|
||||
|
||||
@@ -86,7 +86,7 @@ class OrderExecutionCoordinator{
|
||||
}
|
||||
markUnavailableCaptures(rows,connection,{notAfter}={}){
|
||||
const absent=[];
|
||||
const currentWindow=this.store.snapshot().window;
|
||||
const currentWindow=upcomingWindow(this.store.clock(),this.store.schedule(),this.store.calendar());
|
||||
this.store.transaction(()=>{
|
||||
for(const task of this.store.all('execution-tasks')){
|
||||
const dueDeferred=task.step==='waiting_window'&&task.status==='identified'&&Number.isFinite(Date.parse(task.deferredUntil))&&+this.clock()>=Date.parse(task.deferredUntil);
|
||||
@@ -160,7 +160,8 @@ class OrderExecutionCoordinator{
|
||||
canRetry:this.canRetry(task,principal),status:activeStatus?task.status:order?.status||task.status,
|
||||
error:task.error||order?.error||null};
|
||||
}).reverse();
|
||||
const blockers=[...(!principal||principal.user?.role==='admin'?this.blockers:[]),...this.store.discoveryBlockers(this.store.snapshot().window?.end,allowed)];
|
||||
const window=upcomingWindow(this.store.clock(),this.store.schedule(),this.store.calendar());
|
||||
const blockers=[...(!principal||principal.user?.role==='admin'?this.blockers:[]),...this.store.discoveryBlockers(window?.end,allowed)];
|
||||
const candidates=this.store.all('execution-candidates').filter(item=>item.status==='candidate'&&allowed(item.connectionId));
|
||||
return {tasks,candidates,capabilities:clone(this.store.capabilities),fields,query,blockers};
|
||||
}
|
||||
@@ -517,7 +518,16 @@ class OrderExecutionCoordinator{
|
||||
this.store.put('execution-discoveries',{...latest,status:'complete',consumedAt:this.now()});
|
||||
}
|
||||
}
|
||||
async background(){
|
||||
background(){
|
||||
if(this.backgroundRunning)return this.backgroundRunning;
|
||||
// Slow captures can outlive the timer interval. Share the complete pass,
|
||||
// rather than queuing the same durable discoveries behind each scan.
|
||||
const operation=Promise.resolve().then(()=>this.performBackground());
|
||||
this.backgroundRunning=operation;
|
||||
operation.finally(()=>{if(this.backgroundRunning===operation)this.backgroundRunning=null;}).catch(()=>{});
|
||||
return operation;
|
||||
}
|
||||
async performBackground(){
|
||||
if(this.stopped||!this.systemPrincipal||!this.store.settings().processingEnabled)return;
|
||||
const day=new Date(this.clock().getTime()+8*3600000).toISOString().slice(0,10);
|
||||
if(!dayPolicy(day,this.settings()?.schedule||{},this.calendar()).scan)return;
|
||||
@@ -536,7 +546,7 @@ class OrderExecutionCoordinator{
|
||||
if(this.stopped||!this.store.settings().processingEnabled)return;
|
||||
}
|
||||
const last=this.store.get('execution-scans',connection.id);
|
||||
const window=this.store.snapshot().window;
|
||||
const window=upcomingWindow(this.store.clock(),this.store.schedule(),this.store.calendar());
|
||||
const cutoffDue=window?.available&&(last?.status!=='complete'||!last?.startedAt||Date.parse(last.startedAt)<Date.parse(window.end));
|
||||
const fresh=last?.status==='complete'&&+this.clock()-Date.parse(last.finishedAt)<300000;
|
||||
if(!cutoffDue&&fresh)continue;
|
||||
@@ -550,6 +560,6 @@ class OrderExecutionCoordinator{
|
||||
}
|
||||
}
|
||||
async drain(){await this.tail.catch(()=>{});}
|
||||
async stop(){this.stopped=true;clearInterval(this.timer);this.timer=null;await this.drain();}
|
||||
async stop(){this.stopped=true;clearInterval(this.timer);this.timer=null;if(this.backgroundRunning)await this.backgroundRunning.catch(()=>{});await this.drain();}
|
||||
}
|
||||
module.exports={OrderExecutionCoordinator};
|
||||
@@ -0,0 +1,23 @@
|
||||
'use strict';
|
||||
const {windowForCutoff}=require('./window.cjs');
|
||||
const eligibility=require('./restricted-test.cjs');
|
||||
function discoveryBlockers(store,cutoff,allowed=()=>true){
|
||||
if(!store.executionSources)return (store.deliveryBlockers?.(allowed)||[]).map(id=>'连接 '+id+' 本地执行线索尚未交付。');
|
||||
const window=cutoff?windowForCutoff(cutoff,store.schedule(),store.calendar()):null;
|
||||
const relevant=store.all('execution-tasks').filter(task=>!task.removedAt&&!['sent','ignored'].includes(task.status)&&(!window||eligibility.eventInWindow(store,task.row,window)));
|
||||
const sources=new Set([...store.executionSources(),...relevant.map(task=>task.connectionId)].filter(allowed));
|
||||
// Inactive sources cannot consume hints. Retain their evidence without
|
||||
// blocking unrelated work, unless a retained task still needs that source.
|
||||
const included=id=>sources.has(id);
|
||||
const blockers=(store.deliveryBlockers?.(included)||[]).filter(included).map(id=>'连接 '+id+' 本地执行线索尚未交付。');
|
||||
const pendingSources=new Set([...store.all('execution-discoveries'),...store.all('execution-discovery-runs')].filter(hint=>hint.status==='pending'&&included(hint.connectionId)).map(hint=>hint.connectionId));
|
||||
for(const id of pendingSources)blockers.push('连接 '+id+' 完整对账线索尚未处理。');
|
||||
if(store.activeDiscoveries>0)blockers.push('待办扫描尚未完成,不能冻结或发送不完整类别。');
|
||||
for(const id of sources){
|
||||
const scan=store.get('execution-scans',id);
|
||||
if(scan?.status!=='complete')blockers.push('连接 '+id+' 尚无完整成功扫描'+(scan?.error?':'+scan.error:'。'));
|
||||
else if(cutoff&&Date.parse(scan.startedAt)<Date.parse(cutoff))blockers.push('连接 '+id+' 需要截止时点之后启动的完整扫描。');
|
||||
}
|
||||
return blockers;
|
||||
}
|
||||
module.exports={discoveryBlockers};
|
||||
@@ -58,11 +58,11 @@ function currentTasks(context,user){
|
||||
const tasks=new Map();for(const task of records(context.orderRules).tasks){if(task.supersededBy||!task.orderId||!canReadConnection(context.workspace,user,task.connectionId))continue;const old=tasks.get(task.orderId);if(!old||Number(!!task.conflict)>Number(!!old.conflict)||!!task.conflict===!!old.conflict&&String(task.createdAt||'')>=String(old.createdAt||''))tasks.set(task.orderId,task);}return tasks;
|
||||
}
|
||||
const classified=(order,task)=>!order?.removedAt&&!task?.removedAt&&!!(order?.categoryId||order?.ruleSnapshot?.categoryId||order?.ruleSnapshot?.id||task?.categoryIds?.length);
|
||||
function visibleOrders(context,user){
|
||||
function visibleOrders(context,user,collectingGroups){
|
||||
const data=records(context.orderRules),tasks=currentTasks(context,user);
|
||||
const rows=data.orders.filter(o=>classified(o,tasks.get(o.id))&&canReadOrder(context.workspace,user,o)).map(o=>orderRow(o,tasks.get(o.id)));
|
||||
for(const task of data.tasks)if(!task.orderId&&!task.supersededBy&&classified(null,task)&&canReadConnection(context.workspace,user,task.connectionId))rows.push(orderRow(null,task));
|
||||
const collecting=require('./collecting-batches.cjs').list(context.orderRules).filter(b=>canReadBatch(context.workspace,user,b,context.orderRules));
|
||||
const collecting=(collectingGroups||require('./collecting-batches.cjs').list(context.orderRules)).filter(b=>canReadBatch(context.workspace,user,b,context.orderRules));
|
||||
for(const row of rows)row.collectingBatches=collecting.filter(b=>b.orderIds.includes(row.id)).map(b=>({id:b.id,subject:b.subject,cutoff:b.cutoff}));
|
||||
return rows;
|
||||
}
|
||||
@@ -128,7 +128,7 @@ async function readOrderFile(context,id,index,user){
|
||||
function summary(context,user){
|
||||
const result=context.orderRules.snapshot({includeRecords:false});
|
||||
delete result.orders;delete result.batches;delete result.audit;delete result.fields;
|
||||
const rows=visibleOrders(context,user),data=records(context.orderRules),batches=[...data.batches,...require('./collecting-batches.cjs').list(context.orderRules)].filter(b=>canReadBatch(context.workspace,user,b,context.orderRules));
|
||||
const collecting=require('./collecting-batches.cjs').list(context.orderRules),rows=visibleOrders(context,user,collecting),data=records(context.orderRules),batches=[...data.batches,...collecting].filter(b=>canReadBatch(context.workspace,user,b,context.orderRules));
|
||||
const count=(items,status)=>items.filter(i=>status.includes(i.status)).length;
|
||||
result.scans=context.orderRules.all('execution-scans').filter(s=>canReadConnection(context.workspace,user,s.connectionId||s.id)).map(s=>pick(s,['id','connectionId','status','startedAt','finishedAt','rowCount','targetCount','error']));
|
||||
result.counts={orders:rows.length,blocked:rows.filter(row=>['blocked','failed'].includes(row.status)||row.notifications?.huizhou?.status==='blocked').length,unknown:count(batches,['unknown']),activeBatches:count(batches,['collecting','prepared','sending','unknown','failed'])};
|
||||
|
||||
@@ -23,19 +23,24 @@ function evidence(store,adapter){
|
||||
const result=require('./field-mappings.cjs').evaluateMapping(store,{...adapter,version:adapter.version},captured,{relatedRules:[]});
|
||||
return result.valid;
|
||||
}
|
||||
function uncoveredFlows(store,run){
|
||||
const adapters=store.adapters();
|
||||
function uncoveredFlows(store,run,adapters=store.adapters()){
|
||||
return run.rules.flatMap(rule=>{
|
||||
const draft=store.get('rules',rule.id)?.draft;
|
||||
const processes=draft?.version===rule.version?draft.processNames:[...rule.processNames,...(run.uncovered||[]).filter(row=>row.categoryId===rule.id).map(row=>row.processName)];
|
||||
return [...new Set(processes)].filter(processName=>!adapters.some(a=>a.verified&&!a.reference&&rule.adapterIds.includes(a.id)&&a.processName===processName)).map(processName=>({categoryId:rule.id,processName}));
|
||||
});
|
||||
}
|
||||
function summary(store){const run=state(store);if(!run)return null;const period=require('./stability-period.cjs').period(store);return {id:run.id,version:run.version,enabled:run.enabled,recipient:run.recipient,archiveRoot:run.archiveRoot,channelId:run.channelId,since:run.since,ruleCount:run.rules.length,readyCount:run.rules.filter(r=>validRule(store,r,run)).length,uncovered:uncoveredFlows(store,run),...(period?{period}:{})};}
|
||||
function validRule(store,rule,run){return run.enabled&&hash(rule.adapterIds.map(id=>store.adapters().find(a=>a.id===id)))===run.adapterHashes[rule.id];}
|
||||
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;
|
||||
// A synchronous snapshot may share these reads; never retain this across calls.
|
||||
function readContext(store,adapters){
|
||||
const saved=typeof store?.get==='function'?store.get('restricted-test','main')?.value||null:null;
|
||||
const period=saved?require('./stability-period.cjs').period(store):null;
|
||||
return {run:saved&&period?.expired?{...saved,enabled:false}:saved,period,adapters:adapters??(saved?store.adapters():[])};
|
||||
}
|
||||
function summary(store,context=readContext(store)){const {run,period,adapters}=context;if(!run)return null;return {id:run.id,version:run.version,enabled:run.enabled,recipient:run.recipient,archiveRoot:run.archiveRoot,channelId:run.channelId,since:run.since,ruleCount:run.rules.length,readyCount:run.rules.filter(r=>validRule(store,r,run,adapters)).length,uncovered:uncoveredFlows(store,run,adapters),...(period?{period}:{})};}
|
||||
function validRule(store,rule,run,adapters){if(!run.enabled)return false;adapters??=store.adapters();return hash(rule.adapterIds.map(id=>adapters.find(a=>a.id===id)))===run.adapterHashes[rule.id];}
|
||||
function executionRule(store,record,context){
|
||||
const run=context?context.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,context?.adapters)?structuredClone(rule):null;
|
||||
}
|
||||
function applyDrafts(store,input,actor){
|
||||
if(actor?.role!=='admin'||!actor.username)fail('仅管理员可应用测试规则。',403);
|
||||
@@ -190,4 +195,4 @@ function admitCurrent(store,rows,actor){
|
||||
return structuredClone(entries);
|
||||
});
|
||||
}
|
||||
module.exports={state,summary,save,applyDrafts,executionRule,assertPath,assertRule,assertEvent,assertOrder,assertBatch,recordCurrentScan,admitCurrent,eventTime,orderTime,isAdmitted,eventInWindow,orderInWindow};
|
||||
module.exports={state,readContext,summary,save,applyDrafts,executionRule,assertPath,assertRule,assertEvent,assertOrder,assertBatch,recordCurrentScan,admitCurrent,eventTime,orderTime,isAdmitted,eventInWindow,orderInWindow};
|
||||
@@ -47,10 +47,10 @@ class RuleStore{
|
||||
}catch(error){try{this.db?.close();}catch{}this.vault?.destroy();throw error;}
|
||||
}
|
||||
now(){return this.clock().toISOString();}
|
||||
restrictedTest(){return require('./restricted-test.cjs').summary(this);}
|
||||
restrictedTest(context){return require('./restricted-test.cjs').summary(this,context);}
|
||||
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);}
|
||||
executionRule(record,context){return require('./restricted-test.cjs').executionRule(this,record,context);}
|
||||
providersReady(){return ['liveTodo','pdfExport','automaticArchive'].every(key=>this.capabilities[key]===true);}
|
||||
adapters(){return registry.registry(this);}
|
||||
fields(){return registry.fields(this);}
|
||||
@@ -85,7 +85,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';rule.testVersion=active?.version||null;rule.testHasDraft=!active||active.version!==rule.version;}
|
||||
const readContext=eligibility.readContext(this,adapters),restrictedTest=typeof this.restrictedTest==='function'?this.restrictedTest(readContext):null;for(const rule of rules)if(restrictedTest){const active=typeof this.executionRule==='function'?this.executionRule({id:rule.id},readContext):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(()=>{
|
||||
@@ -240,21 +240,7 @@ class RuleStore{
|
||||
this.put('orders',order);require('./migrations.cjs').synchronizeTasks(this,order);this.audit(actor,'应用当前规则重新识别',id+':'+input.note.trim());return order;
|
||||
});}
|
||||
discoveryBlockers(cutoff,allowed=()=>true){
|
||||
const blockers=(this.deliveryBlockers?.(allowed)||[]).map(id=>'连接 '+id+' 本地执行线索尚未交付。');
|
||||
if(!this.executionSources)return blockers;
|
||||
const pendingSources=new Set([...this.all('execution-discoveries'),...this.all('execution-discovery-runs')].filter(hint=>hint.status==='pending'&&allowed(hint.connectionId)).map(hint=>hint.connectionId));
|
||||
for(const id of pendingSources)blockers.push('连接 '+id+' 完整对账线索尚未处理。');
|
||||
if(this.activeDiscoveries>0)blockers.push('待办扫描尚未完成,不能冻结或发送不完整类别。');
|
||||
const window=cutoff?windowForCutoff(cutoff,this.schedule(),this.calendar()):null;
|
||||
const relevant=this.all('execution-tasks').filter(t=>!t.removedAt&&(!window||eligibility.eventInWindow(this,t.row,window)));
|
||||
const sources=new Set([...this.executionSources(),...relevant.filter(t=>!['sent','ignored'].includes(t.status)).map(t=>t.connectionId)]);
|
||||
for(const id of sources){
|
||||
if(!allowed(id))continue;
|
||||
const scan=this.get('execution-scans',id);
|
||||
if(scan?.status!=='complete')blockers.push('连接 '+id+' 尚无完整成功扫描'+(scan?.error?':'+scan.error:'。'));
|
||||
else if(cutoff&&Date.parse(scan.startedAt)<Date.parse(cutoff))blockers.push('连接 '+id+' 需要截止时点之后启动的完整扫描。');
|
||||
}
|
||||
return blockers;
|
||||
return require('./discovery-barrier.cjs').discoveryBlockers(this,cutoff,allowed);
|
||||
}
|
||||
categoryIncomplete(categoryId,window){
|
||||
return this.all('execution-tasks').some(task=>!task.removedAt&&task.categoryIds?.includes(categoryId)&&(!Number.isFinite(Date.parse(eligibility.eventTime(this,task.row)))||eligibility.eventInWindow(this,task.row,window)||this.intakeWindow(task.row)?.end===window.end)&&(task.conflict||['identified','blocked','failed','capturing','archiving'].includes(task.status)||task.status==='unknown'&&task.step!=='complete'||task.runtimeCheck?.status==='blocked'));
|
||||
|
||||
@@ -39,7 +39,7 @@ test('rule editor exposes explicit test application while drafts remain editable
|
||||
runtime.orderRules.snapshot=()=>({...original(),restrictedTest:run});
|
||||
await page.goto(base+'/#order-rules');await login(page);
|
||||
await page.getByRole('button',{name:'保存草稿',exact:true}).waitFor();
|
||||
assert.match(await page.locator('#order-rules-panel').innerText(),/受限稳定性测试:15 \/ 15 类可用/);
|
||||
assert.match(await page.locator('#order-rules-panel').innerText(),/受限稳定性测试:15 类纳入测试,15 类当前生效/);
|
||||
assert.equal(await page.getByRole('button',{name:'应用到测试',exact:true}).isEnabled(),true);
|
||||
assert.equal(await page.getByRole('button',{name:'保存草稿',exact:true}).isEnabled(),true);
|
||||
await page.getByLabel('规则名称',{exact:true}).fill('仍可编辑的草稿');await page.getByRole('button',{name:'保存草稿',exact:true}).click();await page.getByText('规则草稿已保存。',{exact:true}).waitFor();
|
||||
|
||||
@@ -11,6 +11,8 @@ function fixture(t){
|
||||
put(kind,item){if(!records.has(kind))records.set(kind,new Map());records.get(kind).set(item.id,structuredClone(item));return item;},
|
||||
transaction(work){transactionDepth++;try{return work();}finally{transactionDepth--; }},
|
||||
settings:()=>({processingEnabled,processingSince:null}),
|
||||
now:()=> '2026-10-23T02:00:00.000Z',clock:()=>new Date('2026-10-23T02:00:00Z'),
|
||||
schedule:()=>({times:['11:00','17:00'],weekends:false}),calendar:()=>[],intakeWindow:()=>null,
|
||||
snapshot(){snapshots++;return {window:{start:'2026-10-23T00:00:00Z',end:'2026-10-23T03:00:00Z',available:false}};},
|
||||
executionRule:record=>record?.draft,
|
||||
fields:()=>({samples:[],processes:[]}),discoveryBlockers:()=>[],
|
||||
@@ -32,10 +34,13 @@ test('one discovery set resolves its window once and registers every row before
|
||||
return {liveTodo:true,pdfExport:true};
|
||||
};
|
||||
await f.execution.scan({connectionId:'c1',idempotencyKey:'complete-discovery'},principal,{rows});
|
||||
assert.equal(firstProbe.snapshots,1,'the complete discovery set must use one window snapshot');
|
||||
assert.equal(firstProbe.snapshots,0,'discovery resolves its window without building a full store snapshot');
|
||||
assert.equal(new Set(firstProbe.tasks.map(task=>JSON.stringify(task.intakeWindow))).size,1,'all tasks must share the window resolved at scan start');
|
||||
assert.equal(firstProbe.tasks[0].intakeWindow.end,'2026-10-23T03:00:00.000Z');
|
||||
assert.equal(firstProbe.inTransaction,false,'external work must start after the discovery transaction');
|
||||
assert.equal(firstProbe.tasks.length,17,'all task rows must be committed before any probe or capture');
|
||||
assert.equal(firstProbe.targetCount,17);assert.equal(f.store.all('execution-tasks').length,17);
|
||||
assert.equal(f.snapshots,0,'capture absence checks and execution views must not assemble unrelated store snapshots');
|
||||
});
|
||||
for(const action of ['pause','stop'])test(`historical delivery drain yields before the second hint so an event-loop ${action} preserves pending work`,async t=>{
|
||||
const f=fixture(t);
|
||||
@@ -57,5 +62,6 @@ for(const action of ['pause','stop'])test(`historical delivery drain yields befo
|
||||
f.setProcessing(true);await f.execution.background();
|
||||
assert.equal(f.store.all('execution-discovery-runs').filter(item=>item.status==='complete').length,20);
|
||||
assert.equal(f.store.get('execution-discoveries','c1').status,'complete');
|
||||
assert.equal(f.snapshots,0,'background freshness checks must resolve only the schedule window');
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,67 @@
|
||||
'use strict';
|
||||
const test=require('node:test'),assert=require('node:assert/strict');
|
||||
const {OrderExecutionCoordinator}=require('../../src/modules/order-execution/coordinator.cjs');
|
||||
const now='2026-10-26T02:00:00.000Z';
|
||||
function deferred(){let resolve,reject;const promise=new Promise((yes,no)=>{resolve=yes;reject=no;});return {promise,resolve,reject};}
|
||||
function fixture(t){
|
||||
const records=new Map(),connection={id:'c1',owner:'admin',status:'connected'};
|
||||
const store={
|
||||
all:kind=>[...(records.get(kind)?.values()||[])].map(value=>structuredClone(value)),
|
||||
get:(kind,id)=>structuredClone(records.get(kind)?.get(id)||null),
|
||||
put(kind,value){if(!records.has(kind))records.set(kind,new Map());records.get(kind).set(value.id,structuredClone(value));},
|
||||
transaction:work=>work(),settings:()=>({processingEnabled:true}),
|
||||
clock:()=>new Date(now),schedule:()=>({times:['11:00','17:00'],weekends:false}),calendar:()=>[],
|
||||
snapshot:()=>({window:{available:false}}),
|
||||
};
|
||||
const execution=new OrderExecutionCoordinator({store,workspace:{snapshot:()=>({connections:[connection]})},archive:{},clock:()=>new Date(now),systemPrincipal:{user:{username:'admin',role:'admin'},sessionId:'isolated-test'}});
|
||||
t.after(()=>execution.stop());
|
||||
return {execution,store,notify:runId=>execution.notifyDiscovery({connectionId:connection.id,runId,rows:[],startedAt:now,finishedAt:now})};
|
||||
}
|
||||
|
||||
test('overlapping background ticks share the running discovery pass without duplicate scans',async t=>{
|
||||
const f=fixture(t),entered=deferred(),release=deferred(),calls=[];
|
||||
f.notify('first');f.notify('second');
|
||||
f.execution.scan=async(input,principal,hint)=>{
|
||||
calls.push(hint.runId);
|
||||
if(calls.length===1){entered.resolve();await release.promise;}
|
||||
f.store.put('execution-scans',{id:'c1',status:'complete',startedAt:now,finishedAt:now});
|
||||
};
|
||||
const first=f.execution.background();await entered.promise;
|
||||
const overlap=Array.from({length:4},()=>f.execution.background());
|
||||
const callsWhileBlocked=[...calls];
|
||||
// Arrivals during a pass remain durable and are processed by the next pass.
|
||||
f.notify('third');release.resolve();await Promise.all([first,...overlap]);
|
||||
assert.deepEqual(callsWhileBlocked,['first'],'a slow capture must not queue the same discovery again');
|
||||
assert.deepEqual(calls,['first','second']);
|
||||
assert.equal(f.store.all('execution-discovery-runs').find(hint=>hint.runId==='third').status,'pending');
|
||||
await f.execution.background();
|
||||
assert.deepEqual(calls,['first','second','third']);
|
||||
assert.ok(f.store.all('execution-discovery-runs').every(hint=>hint.status==='complete'));
|
||||
});
|
||||
|
||||
test('background guard releases after an unexpected failure so the next tick can recover',async t=>{
|
||||
const f=fixture(t),entered=deferred(),release=deferred();let calls=0;
|
||||
f.execution.performBackground=async()=>{calls++;entered.resolve();await release.promise;throw Error('isolated background failure');};
|
||||
const first=f.execution.background();await entered.promise;
|
||||
const second=f.execution.background();release.resolve();
|
||||
const results=await Promise.allSettled([first,second]);
|
||||
assert.equal(calls,1);assert.ok(results.every(result=>result.status==='rejected'));
|
||||
f.execution.performBackground=async()=>{calls++;};
|
||||
await f.execution.background();assert.equal(calls,2);
|
||||
});
|
||||
|
||||
test('stop waits for the background pass to persist its final discovery receipt',async t=>{
|
||||
const f=fixture(t),entered=deferred(),release=deferred();
|
||||
f.notify('shutdown');
|
||||
f.execution.scan=async()=>{entered.resolve();await release.promise;};
|
||||
const running=f.execution.background();await entered.promise;
|
||||
let stopped=false;
|
||||
const stopping=f.execution.stop().then(()=>{stopped=true;});
|
||||
// Allow a drain-only stop to resolve while its background continuation is pending.
|
||||
await new Promise(resolve=>setImmediate(resolve));
|
||||
const premature=stopped;
|
||||
release.resolve();await Promise.all([running,stopping]);
|
||||
assert.equal(premature,false,'shutdown must not close the store before final background writes');
|
||||
assert.equal(f.store.all('execution-discovery-runs')[0].status,'complete');
|
||||
assert.equal(f.store.get('execution-discoveries','c1').status,'complete');
|
||||
});
|
||||
@@ -9,6 +9,12 @@ function fixture(){
|
||||
return {orderRules:store,workspace:{recordSources:()=>[{id:'a',owner:'alice'},{id:'b',owner:'bob'}]},execution:{archive:{read:async()=>Buffer.from('%PDF-x')}}};
|
||||
}
|
||||
const user={username:'alice',role:'operator'};
|
||||
|
||||
test('summary computes dynamic collecting batches once per request and never retains a previous result',t=>{
|
||||
const c=fixture(),collecting=require('../../src/modules/order-rules/collecting-batches.cjs');let reads=0;
|
||||
t.mock.method(collecting,'list',()=>{reads++;return [];});
|
||||
summary(c,user);assert.equal(reads,1);summary(c,user);assert.equal(reads,2);
|
||||
});
|
||||
test('failed task detail exposes bounded read-only evidence only for the same authorized capture',()=>{
|
||||
const c=fixture(),task={id:'capture-failed',connectionId:'a',categoryIds:['cat'],status:'failed',step:'capture',errorCode:'FORM_STRUCTURE_UNSUPPORTED',retryPolicy:'manual',nextRetryAt:null,diagnostics:[{code:'ROW_MAPPING',table:'OrderItems',reason:'明细行关系不明确',rowCount:2,cookie:'SECRET'}],captureEvidenceId:'evidence',row:{taskId:'T1',instanceId:'I1'}};
|
||||
c.orderRules.all('execution-tasks').push(task);
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
'use strict';
|
||||
const test=require('node:test'),assert=require('node:assert/strict');
|
||||
const {orderDrivenUI}=require('../fixtures/order-driven-ui.cjs');
|
||||
test('healthy todo without matched orders shows pending verification without loosening capability gates',{timeout:60000},async t=>{
|
||||
const {page,runtime}=await orderDrivenUI(t,'#notification-settings'),s=runtime.orderRules;
|
||||
s.put('settings',{...s.get('settings','main'),enabled:true,processingEnabled:true});s.capabilities={liveTodo:true,pdfExport:false,automaticArchive:false};
|
||||
await page.getByRole('button',{name:'刷新数据',exact:true}).click();await page.getByRole('link',{name:'自动通知待验证',exact:true}).waitFor();
|
||||
assert.equal(s.providersReady(),false);assert.equal(s.settings().enabled,true);
|
||||
s.put('execution-scans',{id:'failed-source',status:'failed',error:'fixture failure'});
|
||||
await page.getByRole('button',{name:'刷新数据',exact:true}).click();await page.getByRole('link',{name:'自动通知受阻',exact:true}).waitFor();
|
||||
assert.equal(s.providersReady(),false);
|
||||
});
|
||||
@@ -13,3 +13,33 @@ test('retained live uncertain tasks and active incomplete sources still block di
|
||||
const s=fixture(false);assert.match(RuleStore.prototype.discoveryBlockers.call(s,cutoff).join(' '),/disabled-old/);
|
||||
const active=fixture();active.get=()=>null;assert.match(RuleStore.prototype.discoveryBlockers.call(active,cutoff).join(' '),/active/);
|
||||
});
|
||||
|
||||
function pendingFixture({connectionId='disabled-old',removed=true,retained=false}={}){
|
||||
const s=fixture(removed),hints=[{id:'hint',connectionId,status:'pending',rows:[]}];
|
||||
if(!retained)s.tasks.length=0;
|
||||
s.all=kind=>kind==='execution-tasks'?s.tasks:kind==='execution-discoveries'||kind==='execution-discovery-runs'?hints:[];
|
||||
s.deliveryBlockers=allowed=>[connectionId].filter(allowed);
|
||||
return {s,hints};
|
||||
}
|
||||
for(const retained of [false,true])test(`inactive pending discovery and producer delivery with ${retained?'removed unknown task':'no retained task'} do not block other sources`,()=>{
|
||||
const {s,hints}=pendingFixture({retained}),before=structuredClone(hints);
|
||||
assert.deepEqual(RuleStore.prototype.discoveryBlockers.call(s,cutoff),[]);
|
||||
assert.deepEqual(hints,before,'pending evidence must remain available for source reactivation');
|
||||
});
|
||||
test('active pending evidence and deliveries continue blocking despite a completed scan',()=>{
|
||||
const {s}=pendingFixture({connectionId:'active'}),blockers=RuleStore.prototype.discoveryBlockers.call(s,cutoff);
|
||||
assert.ok(blockers.some(message=>message.includes('本地执行线索')));
|
||||
assert.ok(blockers.some(message=>message.includes('完整对账线索')));
|
||||
});
|
||||
test('inactive source with retained uncertain task still requires pending evidence and successful scan',()=>{
|
||||
const {s}=pendingFixture({removed:false,retained:true}),blockers=RuleStore.prototype.discoveryBlockers.call(s,cutoff);
|
||||
assert.ok(blockers.some(message=>message.includes('本地执行线索')));
|
||||
assert.ok(blockers.some(message=>message.includes('完整对账线索')));
|
||||
assert.ok(blockers.some(message=>message.includes('尚无完整成功扫描')));
|
||||
assert.deepEqual(RuleStore.prototype.discoveryBlockers.call(s,cutoff,id=>id==='active'),[]);
|
||||
});
|
||||
test('standalone store without execution source registration retains producer delivery blockers',()=>{
|
||||
const {s}=pendingFixture();delete s.executionSources;
|
||||
assert.match(RuleStore.prototype.discoveryBlockers.call(s,cutoff).join(' '),/本地执行线索/);
|
||||
assert.deepEqual(RuleStore.prototype.discoveryBlockers.call(s,cutoff,()=>false),[]);
|
||||
});
|
||||
@@ -0,0 +1,55 @@
|
||||
'use strict';
|
||||
const test=require('node:test'),assert=require('node:assert/strict'),crypto=require('node:crypto');
|
||||
const {RuleStore}=require('../../src/modules/order-rules/store.cjs');
|
||||
const {seedRules}=require('../../src/modules/order-rules/catalog.cjs');
|
||||
const access=require('../../src/modules/order-rules/access.cjs');
|
||||
const canonical=v=>Array.isArray(v)?v.map(canonical):v&&typeof v==='object'?Object.fromEntries(Object.keys(v).sort().map(k=>[k,canonical(v[k])])):v;
|
||||
const hash=v=>crypto.createHash('sha256').update(JSON.stringify(canonical(v))).digest('hex');
|
||||
function fixture(){
|
||||
const store=Object.create(RuleStore.prototype),counts={},records={rules:seedRules().slice(0,2).map(draft=>({id:draft.id,draft:{...draft,adapterIds:['a','b']},published:null}))};
|
||||
let now='2026-10-26T01:00:00Z';
|
||||
records['field-adapters']=['a','b'].map((id,i)=>({id,processName:records.rules[0].draft.processNames[0],processVersion:String(i),version:1,verified:true,status:'active'}));
|
||||
records.settings=[{id:'main',enabled:true,processingEnabled:true}];
|
||||
records['stability-test']=[{id:'main',enabled:true,startedAt:'2026-10-25T01:00:00Z',endsAt:'2026-10-26T02:00:00Z'}];
|
||||
store.all=kind=>{counts['all:'+kind]=(counts['all:'+kind]||0)+1;return structuredClone(records[kind]||[]);};
|
||||
store.get=(kind,id)=>{counts['get:'+kind]=(counts['get:'+kind]||0)+1;return structuredClone(records[kind]?.find(r=>r.id===id)||null);};
|
||||
store.clock=()=>new Date(now);store.schedule=()=>({times:['11:00','17:00'],weekends:false});store.calendar=()=>[];store.capabilities={};
|
||||
const adapters=store.adapters(),rules=records.rules.map(r=>({...r.draft,status:'enabled'}));
|
||||
records['restricted-test']=[{id:'main',value:{id:'run',version:1,enabled:true,rules,adapterHashes:Object.fromEntries(rules.map(r=>[r.id,hash(r.adapterIds.map(id=>adapters.find(a=>a.id===id)))]))}}];
|
||||
const reset=()=>{for(const key of Object.keys(counts))delete counts[key];};reset();
|
||||
return {store,records,counts,reset,setTime:time=>{now=time;}};
|
||||
}
|
||||
test('one snapshot reads adapters and restricted run once while preserving standalone results',()=>{
|
||||
const f=fixture(),summary=f.store.restrictedTest(),active=f.records.rules.map(r=>f.store.executionRule(r));f.reset();
|
||||
const result=f.store.snapshot({includeRecords:false});
|
||||
assert.deepEqual(result.restrictedTest,summary);
|
||||
assert.deepEqual(result.rules.map(r=>[r.testStatus,r.testVersion]),active.map(r=>[r?'enabled':'paused',r?.version||null]));
|
||||
assert.equal(f.counts['all:field-adapters'],1);
|
||||
assert.equal(f.counts['get:restricted-test'],1);
|
||||
assert.equal(f.counts['all:orders']||0,0);
|
||||
});
|
||||
test('standalone execution checks read adapters once per rule and observe next-read changes',()=>{
|
||||
const f=fixture(),record=f.records.rules[0];assert.ok(f.store.executionRule(record));
|
||||
assert.equal(f.counts['all:field-adapters'],1);
|
||||
f.records['field-adapters'][0].version++;
|
||||
assert.equal(f.store.executionRule(record),null);
|
||||
assert.equal(f.store.snapshot({includeRecords:false}).restrictedTest.readyCount,0);
|
||||
});
|
||||
test('snapshot context expires after each call and observes the exact stability boundary',()=>{
|
||||
const f=fixture();assert.equal(f.store.snapshot({includeRecords:false}).restrictedTest.readyCount,2);
|
||||
f.setTime('2026-10-26T02:00:00Z');
|
||||
const expired=f.store.snapshot({includeRecords:false});
|
||||
assert.equal(expired.restrictedTest.enabled,false);assert.equal(expired.restrictedTest.readyCount,0);
|
||||
assert.ok(expired.rules.every(r=>r.testStatus==='paused'));assert.equal(expired.settings.processingEnabled,false);
|
||||
f.setTime('2026-10-26T01:00:00Z');f.records['restricted-test'][0].value.enabled=false;
|
||||
assert.equal(f.store.snapshot({includeRecords:false}).restrictedTest.readyCount,0);
|
||||
});
|
||||
test('snapshot reuse does not change admin/operator ownership filtering or expose private rows',()=>{
|
||||
const f=fixture();f.records.orders=[{id:'own',sample:{connectionId:'a'}},{id:'private',sample:{connectionId:'b'}}];
|
||||
f.records.batches=[{id:'own-batch',orderIds:['own']},{id:'private-batch',orderIds:['private']}];
|
||||
const sources=[{id:'a',owner:'alice'},{id:'b',owner:'bob'}],workspace={recordSources:()=>sources};
|
||||
const admin=access.publicSnapshot(f.store,workspace,{role:'admin',username:'admin'}),operator=access.publicSnapshot(f.store,workspace,{role:'operator',username:'alice'});
|
||||
assert.deepEqual(admin.orders.map(r=>r.id),['private','own']);assert.deepEqual(operator.orders.map(r=>r.id),['own']);
|
||||
assert.deepEqual(operator.batches.map(r=>r.id),['own-batch']);assert.deepEqual(operator.rules,admin.rules);
|
||||
sources[0].owner='bob';assert.equal(access.publicSnapshot(f.store,workspace,{role:'operator',username:'alice'}).orders.length,0);
|
||||
});
|
||||
@@ -78,6 +78,7 @@ async function updateAutomationStatus(isActive){
|
||||
if(typeof data?.settings?.enabled!=='boolean')throw Error('服务端未返回有效通知开关');
|
||||
const missing=Object.entries({liveTodo:'实时待办接入',pdfExport:'PDF 导出',automaticArchive:'自动归档'}).filter(([key])=>data.capabilities?.[key]!==true).map(([,label])=>label);
|
||||
if(!data.settings.enabled)apply('自动通知已暂停','secondary','自动发信保持暂停;请完成类别字段、目录、邮箱与预览核验。'+(missing.length?' 待检查:'+missing.join('、'):' 点击查看发送设置。'));
|
||||
else if(missing.length&&data.capabilities?.liveTodo===true&&data.counts?.orders===0&&!(data.scans||[]).some(scan=>scan.status==='failed'))apply('自动通知待验证','yellow','当前没有匹配订单;'+missing.join('、')+'尚待实际业务验证。匹配订单到达后按流程核验。');
|
||||
else if(missing.length)apply('自动通知受阻','yellow','未通过实际检查:'+missing.join('、')+'。点击查看发送设置。');
|
||||
else apply('自动通知已启用','green','通知开关已启用;实际任务、类别及批次仍按各自检查结果执行。');
|
||||
}catch(error){apply('通知状态待确认','yellow',error.message+';请刷新重试。');}
|
||||
|
||||
@@ -9,12 +9,12 @@
|
||||
const operationKey=(form,body)=>{const signature=JSON.stringify(body);if(form.dataset.requestSignature!==signature){form.dataset.requestSignature=signature;form.dataset.requestKey=window.PageLifecycle.requestKey();}return form.dataset.requestKey;};
|
||||
const capabilityNames={liveTodo:'实时待办接入',pdfExport:'通知书 PDF 导出',automaticArchive:'自动归档'};
|
||||
const ready=c=>Object.keys(capabilityNames).every(k=>c[k]===true);
|
||||
function capabilities(c){return `<div class="order-rule-capabilities">${Object.entries(capabilityNames).map(([key,label])=>`<div><span class="badge bg-${c[key]===true?'green':'yellow'}-lt">${c[key]===true?'已就绪':'待联调'}</span><span>${label}</span></div>`).join('')}</div>`;}
|
||||
function capabilities(c){return `<div class="order-rule-capabilities">${Object.entries(capabilityNames).map(([key,label])=>`<div><span class="badge bg-${c[key]===true?'green':'yellow'}-lt">${c[key]===true?'已就绪':'待验证'}</span><span>${label}</span></div>`).join('')}</div>`;}
|
||||
|
||||
function capabilityBlockers(c){
|
||||
const checks=[['liveTodo','实时待办接入尚未验证,不能自动采集订单。','#bpm','检查 BPM 连接'],['pdfExport','通知书 PDF 导出尚未验证,不能提供附件证据。','#rule-fields','核实真实字段'],['automaticArchive','自动归档尚未验证,不能确认文件已安全归档。','#storage','检查存储服务器']];
|
||||
const checks=[['liveTodo','实时待办接入尚未验证,不能自动采集订单。','#bpm','检查 BPM 连接'],['pdfExport','通知书 PDF 导出尚待实际验证,验证完成后才能归档。','#rule-fields','核实真实字段'],['automaticArchive','自动归档尚未验证,不能确认文件已安全归档。','#storage','检查存储服务器']];
|
||||
const missing=checks.filter(([key])=>c[key]!==true);
|
||||
return missing.length?`<div class="alert alert-warning mt-3"><strong>自动执行受阻</strong>${missing.map(([,reason,href,label])=>`<div>${esc(reason)} <a href="${href}">${label}</a></div>`).join('')}</div>`:'';
|
||||
return missing.length?`<div class="alert alert-warning mt-3"><strong>待完成的运行检查</strong>${missing.map(([,reason,href,label])=>`<div>${esc(reason)} <a href="${href}">${label}</a></div>`).join('')}</div>`:'';
|
||||
}
|
||||
return {capabilityBlockers,status,empty,table,list,operationKey,capabilities,ready};
|
||||
}};
|
||||
|
||||
@@ -23,7 +23,7 @@ window.OrderNotificationViews=(()=>{
|
||||
const card=document.createElement('section');card.className='card settings-width mb-3';container.prepend(card);
|
||||
let run=data.restrictedTest;
|
||||
function drawTest(){
|
||||
card.innerHTML=`<div class="card-header"><h2 class="card-title">受限稳定性测试</h2><span class="badge bg-yellow-lt ms-auto">${run.enabled?'测试运行中':'测试已暂停'}</span></div><div class="card-body"><p>覆盖 ${Number(run.ruleCount)} 类,当前可用 ${Number(run.readyCount)} 类。正式投产须重新检查并发布。</p><dl><dt>固定收件箱</dt><dd class="text-break">${esc(run.recipient)}</dd><dt>桌面归档目录</dt><dd class="text-break">${esc(run.archiveRoot)}</dd><dt>测试接收基线</dt><dd>${esc(formatDate(run.since))}</dd>${run.period?'<dt>测试结束(自动暂停)</dt><dd>'+esc(formatDate(run.period.endsAt))+(run.period.expired?' · 已到期':'')+'</dd>':''}</dl><p class="small text-secondary">仅处理基线后的真实通知;暂停保留测试模式,不切换为正式发送。收件箱、目录与发件通道已固定。</p>${run.uncovered?.length?`<p class="text-warning small">${run.uncovered.length} 个流程尚无可用字段版本,继续阻塞。</p><ul class="small text-warning">${run.uncovered.map(item=>`<li><span>${esc(item.processName)}</span>${item.categoryId?` <span class="text-secondary">(分类:${esc(item.categoryId)})</span>`:''}</li>`).join('')}</ul>`:''}<div role="alert"></div></div>${admin?`<div class="card-footer"><button type="button" class="btn ${run.enabled?'btn-outline-warning':'btn-primary'}">${run.enabled?'暂停测试':'恢复测试'}</button></div>`:''}`;
|
||||
card.innerHTML=`<div class="card-header"><h2 class="card-title">受限稳定性测试</h2><span class="badge bg-yellow-lt ms-auto">${run.enabled?'测试运行中':'测试已暂停'}</span></div><div class="card-body"><p>纳入测试 ${Number(run.ruleCount)} 类,当前生效 ${Number(run.readyCount)} 类。分类计数不代表全部流程已完成实单验证;正式投产须重新检查并发布。</p><dl><dt>固定收件箱</dt><dd class="text-break">${esc(run.recipient)}</dd><dt>桌面归档目录</dt><dd class="text-break">${esc(run.archiveRoot)}</dd><dt>测试接收基线</dt><dd>${esc(formatDate(run.since))}</dd>${run.period?'<dt>测试结束(自动暂停)</dt><dd>'+esc(formatDate(run.period.endsAt))+(run.period.expired?' · 已到期':'')+'</dd>':''}</dl><p class="small text-secondary">仅处理基线后的真实通知;暂停保留测试模式,不切换为正式发送。收件箱、目录与发件通道已固定。</p>${run.uncovered?.length?`<p class="text-warning small">${run.uncovered.length} 个流程待采样或适配,暂不自动处理;${run.enabled?'其他已覆盖流程继续运行。':'测试已暂停。'}</p><ul class="small text-warning">${run.uncovered.map(item=>`<li><span>${esc(item.processName)}</span>${item.categoryId?` <span class="text-secondary">(分类:${esc(item.categoryId)})</span>`:''}</li>`).join('')}</ul>`:''}<div role="alert"></div></div>${admin?`<div class="card-footer"><button type="button" class="btn ${run.enabled?'btn-outline-warning':'btn-primary'}">${run.enabled?'暂停测试':'恢复测试'}</button></div>`:''}`;
|
||||
const button=card.querySelector('button');if(button)button.onclick=async()=>{if(button.disabled)return;button.disabled=true;try{const saved=await api('/order-rules/restricted-test',{version:run.version,enabled:!run.enabled});if(isActive()&&card.isConnected){run=saved;drawTest();}}catch(error){if(isActive()&&card.isConnected)card.querySelector('[role=alert]').textContent=error.message;}finally{if(button.isConnected)button.disabled=false;}};
|
||||
}
|
||||
drawTest();
|
||||
|
||||
@@ -25,7 +25,7 @@
|
||||
let sources=sourcesFor(rule);
|
||||
const recognition=(data.catalogError?`<div class="alert alert-warning">订单读取失败:${esc(data.catalogError)}。请刷新重试,或到<a href="#notification-orders">订单执行</a>检查 BPM 连接。</div>`:'')+window.OrderRulePreview.panel(sources,{esc,operator});
|
||||
panel.innerHTML=`<div class="rule-workbench-grid"><aside class="card rule-category-directory"><div class="card-header"><div><h3 class="card-title">Excel 分类 · ${data.rules.length}</h3><div class="small text-secondary mt-1">${data.restrictedTest?Number(data.restrictedTest.readyCount)+' 类受限测试 · ':''}${data.rules.filter(r=>r.status==='enabled').length} 类正式启用 · ${data.rules.filter(r=>r.status!=='enabled').length} 类未正式启用</div></div></div><div class="card-body"><label class="visually-hidden" for="rule-category-search">搜索分类</label><input type="search" class="form-control mb-2" id="rule-category-search" placeholder="搜索分类" value="${esc(query)}"><label class="visually-hidden" for="rule-category-filter">分类状态</label><select class="form-select" id="rule-category-filter"><option value="all">全部分类</option><option value="needs">待完善</option><option value="draft">有草稿</option><option value="published">已启用</option><option value="paused">已暂停</option></select></div><div id="rule-category-list" class="rule-category-list"></div><div class="card-footer small text-secondary">开关控制已发布版本。<br>正式自动发信由通知配置单独控制。</div></aside><main class="rule-editor-column"><div class="rule-version-bar"><div><div class="small text-secondary mb-1">分类规则</div><h2 class="h3 mb-1">${esc(rule.name)}</h2><div class="small text-secondary" id="rule-version-state">草稿 v${esc(rule.version)} · 已发布 ${esc(rule.publishedVersion?'v'+rule.publishedVersion:'无')} · Excel 行 ${esc(rule.sourceRow??'—')}</div></div></div>${window.OrderRuleEditor.render(rule,data.adapters,{esc,admin,resources:data.resources,recognition})}</main></div>`;
|
||||
if(data.restrictedTest)panel.insertAdjacentHTML('afterbegin','<div class="alert alert-warning">'+(restrictedActive?'受限稳定性测试:'+Number(data.restrictedTest.readyCount)+' / '+Number(data.restrictedTest.ruleCount)+' 类可用。保存后点击“应用到测试”,新任务使用新规则;旧订单和批次保持原快照。':'受限稳定性测试已暂停。可继续维护、验证和发布草稿;这些操作不会恢复测试发送。')+(data.restrictedTest.uncovered?.length?'另有 '+Number(data.restrictedTest.uncovered.length)+' 个流程缺少字段适配,对应订单不会自动归档或发送。<ul class="small mb-2">'+data.restrictedTest.uncovered.map(item=>'<li><span>'+esc(item.processName)+'</span>'+(item.categoryId?' <span class="text-secondary">(分类:'+esc(item.categoryId)+')</span>':'')+'</li>').join('')+'</ul>':'')+'<a href="#notification-settings">查看测试设置</a></div>');
|
||||
if(data.restrictedTest)panel.insertAdjacentHTML('afterbegin','<div class="alert alert-warning">'+(restrictedActive?'受限稳定性测试:'+Number(data.restrictedTest.ruleCount)+' 类纳入测试,'+Number(data.restrictedTest.readyCount)+' 类当前生效。分类计数不代表全部流程已完成实单验证。保存后点击“应用到测试”,新任务使用新规则;旧订单和批次保持原快照。':'受限稳定性测试已暂停。可继续维护、验证和发布草稿;这些操作不会恢复测试发送。')+(data.restrictedTest.uncovered?.length?'另有 '+Number(data.restrictedTest.uncovered.length)+' 个流程待采样或适配,暂不自动处理;'+(restrictedActive?'其他已覆盖流程继续运行。':'测试已暂停。')+'<ul class="small mb-2">'+data.restrictedTest.uncovered.map(item=>'<li><span>'+esc(item.processName)+'</span>'+(item.categoryId?' <span class="text-secondary">(分类:'+esc(item.categoryId)+')</span>':'')+'</li>').join('')+'</ul>':'')+'<a href="#notification-settings">查看测试设置</a></div>');
|
||||
if(admin&&rule.publishedVersion&&!restrictedActive){
|
||||
const migration=document.createElement('section');migration.className='card mt-3';
|
||||
migration.innerHTML='<div class="card-body"><h3 class="h4">将未冻结订单迁移到已发布版本</h3><p class="small text-secondary">仅当前已发布版本。冻结、发送及结果不确定订单不改写;输出变化会要求新代归档。</p><label class="form-label">迁移依据<textarea class="form-control" minlength="5" maxlength="2000" required></textarea></label><button class="btn" data-migration-preview type="button">预览迁移</button><div data-migration-result class="mt-3"></div></div>';
|
||||
|
||||
Reference in new issue
Block a user