fix: verify BPM field compatibility across list versions

This commit is contained in:
abaishu0730 committed 2026-10-26 17:57:18 +08:00
1 parent c3e948d2e4
commit 5647891446
9 files changed
+139 -8

No files matched your search

+6 -5
View File
@@ -10,6 +10,7 @@ const {matchesScope,scopesOverlap}=require('./scopes.cjs');
const {initialNotification,ordersForMode}=require('./huizhou.cjs');
const {modeOf,delivery,updateDelivery}=require('./delivery.cjs');
const taskIdentity=require('./task-identity.cjs');
const {previewCompatible}=require('./version-compatibility.cjs');
const eligibility=require('./restricted-test.cjs');
const canonical=value=>Array.isArray(value)?value.map(canonical):value&&typeof value==='object'?Object.fromEntries(Object.keys(value).sort().map(k=>[k,canonical(value[k])])):value;
const digest=value=>crypto.createHash('sha256').update(JSON.stringify(canonical(value))).digest('hex');
@@ -60,7 +61,7 @@ class RuleStore{
saveMapping(input,actor){return require('./field-mappings.cjs').saveMapping(this,input,actor);}
checkMapping(input,actor){return require('./field-mappings.cjs').checkMapping(this,input,actor);}
activateMapping(input,actor){return require('./field-mappings.cjs').activateMapping(this,input,actor);}
capturedPreview(sampleId){const captured=this.get('capture-samples',sampleId);if(!captured||captured.provenance!=='server-provider')fail('真实捕获样本不存在。',404);const result=this.preview(captured.sample);if(result.valid){const record=this.get('rules',result.ruleId);record.trialSampleId=sampleId;this.put('rules',record);}return result;}
capturedPreview(sampleId){const captured=this.get('capture-samples',sampleId);if(!captured||captured.provenance!=='server-provider')fail('真实捕获样本不存在。',404);const result=this.preview(captured.sample);if(result.valid&&!result.adapterCompatibility){const record=this.get('rules',result.ruleId);record.trialSampleId=sampleId;this.put('rules',record);}return result;}
previewUntrusted(sample){return previewMatch(this.all('rules').map(r=>r.draft),this.adapters(),sample);}
trial(id,input){return require('./trial.cjs').trial(this,id,input);}
@@ -95,8 +96,8 @@ class RuleStore{
this.audit(actor,'保存规则草稿',record.id+' v'+record.draft.version);return {...record.draft,explanation:describeRule(record.draft)};
});}
preview(sample){
const records=this.all('rules');const result=previewMatch(records.map(r=>r.draft),this.adapters(),sample);
if(result.valid&&result.ruleId){const record=records.find(r=>r.id===result.ruleId);if(record){record.trialVersion=record.draft.version;record.trialDemo=sample.demo===true;this.put('rules',record);}}
const records=this.all('rules');const result=previewCompatible(this,records.map(r=>r.draft),this.adapters(),sample);
if(result.valid&&result.ruleId&&!result.adapterCompatibility){const record=records.find(r=>r.id===result.ruleId);if(record){record.trialVersion=record.draft.version;record.trialDemo=sample.demo===true;this.put('rules',record);}}
return result;
}
publish(id,input,actor){return this.transaction(()=>{
@@ -181,7 +182,7 @@ class RuleStore{
const id=old?.id||taskKey,sourceHash=digest(sample);
if(old){if(!taskIdentity.equivalent(old,sample))fail('相同通知任务的内容、节点或业务修订已变化,请人工核实来源证据。',409);return old;}
const active=this.matchingPublications(sample);
const result=previewMatch(active,this.adapters(),sample),rule=active.find(r=>r.id===result.ruleId);
const result=previewCompatible(this,active,this.adapters(),sample),rule=active.find(r=>r.id===result.ruleId);
const ready=this.providersReady(),enabled=rule?.status==='enabled';
if(rule)require('./restricted-test.cjs').assertRule(this,rule);
const order={id,taskKey,sourceHash,event:result.event||copy(sample),sample:copy(sample),ruleSnapshot:rule?copy(rule):null,categoryId:result.categoryId||rule?.categoryId||'',status:result.valid&&ready&&enabled?'identified':'blocked',error:result.valid?(!enabled?'该类别规则已暂停。':ready?null:'待办接入、PDF 导出和自动归档待联调。'):result.issues.join(';'),ingestedAt:this.now(),updatedAt:this.now(),archive:null,batchId:null,trace:result};
@@ -230,7 +231,7 @@ class RuleStore{
const order=this.get('orders',id);
if(!order||order.blockedByBatchId||require('./migrations.cjs').frozen(this,order)||!['blocked','identified','preparing','archived','pending'].includes(order.status))fail('仅未进入批次的待处理订单可以重新识别。',409);
const published=this.matchingPublications(order.sample);
const result=previewMatch(published,this.adapters(),order.sample),rule=published.find(r=>r.id===result.ruleId);
const result=previewCompatible(this,published,this.adapters(),order.sample),rule=published.find(r=>r.id===result.ruleId);
require('./restricted-test.cjs').assertEvent(this,order.sample);if(rule)require('./restricted-test.cjs').assertRule(this,rule);
if(!result.valid||rule?.status!=='enabled')fail(result.issues.join(';')||'对应规则尚未启用。',409);
order.event=result.event;order.ruleSnapshot=copy(rule);order.categoryId=rule.categoryId;order.trace=result;
@@ -0,0 +1,58 @@
'use strict';
const crypto=require('node:crypto');
const {isDeepStrictEqual}=require('node:util');
const {previewMatch}=require('./matching.cjs');
const {matchesScope}=require('./scopes.cjs');
const {sourcesFor}=require('./field-sources.cjs');
const {normalize}=require('./task-identity.cjs');
const hash=value=>crypto.createHash('sha256').update(JSON.stringify(value)).digest('hex');
function validCapture(capture){
return capture?.provenance==='server-provider'&&capture.sample&&capture.snapshot&&capture.processName===capture.sample.processName&&capture.processVersion===capture.sample.processVersion&&capture.snapshot.processVersion===capture.sample.processVersion&&capture.evidenceHash===hash({sample:capture.sample,snapshot:capture.snapshot});
}
function formPath(snapshot){
let sourcePath=null;
if(snapshot.sourceUrl){const url=new URL(snapshot.sourceUrl);if(url.origin!=='https://bpm.skyworthdigital.com'||url.username||url.password||url.hash)throw Error('表单来源地址未核验');sourcePath=decodeURIComponent(url.pathname);}
const value=snapshot.formPath||sourcePath;
if(typeof value!=='string'||!value.startsWith('/YZSoft/Forms/XForm/')||! /V\d+\.aspx$/i.test(value)||value.includes('\\')||value.includes('?')||value.includes('#')||value.split('/').some(p=>p==='.'||p==='..')||sourcePath&&sourcePath!==value)throw Error('完整表单路径或 V 版本不一致');
return value;
}
function currentCapture(store,sample){
const captured=store.all('capture-samples').filter(c=>validCapture(c)&&isDeepStrictEqual(normalize(c.sample),normalize(sample)));
const current=captured.find(c=>c.snapshot.purpose!=='field-mapping'&&typeof c.snapshot.html==='string'&&c.snapshot.html.trim());
if(!current)throw Error('缺少与当前待办一致的服务端完整表单捕获');
if(sample.source!=='todo'||sample.demo||sample.configurationOnly||!sample.portalSource)throw Error('仅允许真实当前待办及明确来源');
const evidence=sample.detailEvidence,entry=require('../../bpm-readonly-form.cjs').parseEntryURL(sample.detailUrl);
if(!evidence||evidence.readOnly!==true||String(evidence.tid)!==entry.tid||String(evidence.pid)!==entry.pid||String(sample.taskId)!==entry.pid||String(sample.instanceId)!==entry.tid||evidence.listProcessVersion!==sample.processVersion)throw Error('只读详情身份与原待办不一致');
const path=formPath(current.snapshot),version=path.match(/(V\d+)\.aspx$/i)[1].toUpperCase();
if(sample.formPath!==path||sample.formVersion!==version||evidence.formVersion!==version)throw Error('当前完整表单路径或 V 版本不一致');
return {capture:current,path};
}
function compatible(adapter,baseline,current,path){
if(!validCapture(baseline)||baseline.id!==adapter.sampleId||baseline.evidenceHash!==adapter.evidenceHash||baseline.processName!==adapter.processName||baseline.processVersion!==adapter.processVersion)throw Error('原适配器缺少一致的已核验样本');
if(formPath(baseline.snapshot)!==path)throw Error('原适配器与当前完整表单路径不一致');
const sources=Object.entries(sourcesFor(adapter)).filter(([,s])=>s.type==='form');
if(!sources.length)throw Error('缺少明确表单字段映射');
for(const [key,source]of sources){
const values=[baseline,current].map(c=>{const rows=c.snapshot.fields?.filter(f=>f.path===source.path);if(rows?.length!==1||!Object.hasOwn(c.sample.fields||{},source.path)||!isDeepStrictEqual(rows[0].value,c.sample.fields[source.path]))throw Error('映射字段缺失或含歧义:'+source.path);return rows[0].value;});
const scalar=v=>v===null||typeof v==='string'||typeof v==='boolean'||typeof v==='number'&&Number.isFinite(v);
if(values.some(v=>!scalar(v))||values[0]!==null&&values[1]!==null&&typeof values[0]!==typeof values[1])throw Error('映射字段类型变化:'+source.path);
if(key==='orderNo'&&values.some(v=>typeof v!=='string'||!v.trim()))throw Error('主订单号字段不是有效文本');
}
}
function previewCompatible(store,rules,adapters,sample){
const original=previewMatch(rules,adapters,sample),matches=rules.filter(r=>matchesScope(r,sample));
if(matches.length!==1)return original;
const rule=matches[0];
// An existing version, including a conflicting/unverified version, must never
// be bypassed by an older mapping.
if(adapters.some(a=>a.processName===sample.processName&&a.processVersion===sample.processVersion))return original;
const blocked=reason=>({...original,valid:false,issues:[...original.issues,'版本兼容阻塞:'+reason],checks:[...original.checks,{label:'版本兼容',ok:false,detail:reason}]});
try{
const {capture,path}=currentCapture(store,sample),candidates=adapters.filter(a=>rule.adapterIds?.includes(a.id)&&a.processName===sample.processName&&a.verified===true&&!a.reference&&a.status!=='superseded'&&!a.supersededBy),accepted=[],reasons=[];
for(const adapter of candidates)try{compatible(adapter,store.get('capture-samples',adapter.sampleId),capture,path);accepted.push(adapter);}catch(error){reasons.push(error.message);}
if(accepted.length!==1)return blocked(accepted.length?'存在多个兼容适配器,不能自动选择':reasons.join(';')||'没有规则绑定的已核验兼容适配器');
const adapter=accepted[0],result=previewMatch(rules,[...adapters.filter(a=>a.id!==adapter.id),{...adapter,processVersion:sample.processVersion}],sample);
return {...result,adapterCompatibility:{adapterId:adapter.id,baselineVersion:adapter.processVersion,currentVersion:sample.processVersion,formPath:path,baselineSampleId:adapter.sampleId,sampleId:capture.id,baselineEvidenceHash:adapter.evidenceHash,evidenceHash:capture.evidenceHash}};
}catch(error){return blocked(error.message);}
}
module.exports={previewCompatible};