fix: synchronize inline rule versions without losing clean state

This commit is contained in:
abaishu0730 committed 2026-10-20 11:49:20 +08:00
1 parent 4f89c4765f
commit 26fc431d2e
2 files changed
+11 -8

No files matched your search

@@ -22,3 +22,5 @@ test('ambiguous fields can be selected directly in the rule and remain an unsave
});
test('cancelling an order clears the formal check selection and keeps the rule clean',{timeout:90000},async t=>{const {page}=await orderDrivenUI(t,'#order-rules');await page.locator('[data-rule-id="bs-change"]').click();await page.getByRole('button',{name:'选择订单 S-1',exact:true}).click();await page.locator('#rule-order-recognition').getByText('148396',{exact:true}).waitFor();await page.getByRole('button',{name:'取消选择',exact:true}).click();assert.equal(await page.locator('#order-rule-sample-source').inputValue(),'');assert.equal(await page.locator('#order-rule-preview-result').innerText(),'');assert.equal(await page.evaluate(()=>PageLifecycle.dirty()),false);});
test('inline activation synchronizes the visible rule version atomically and a clean rule remains clean',{timeout:90000},async t=>{const {page,runtime}=await orderDrivenUI(t,'#order-rules');await page.locator('[data-rule-id="bs-change"]').click();await page.getByRole('button',{name:'选择订单 S-1',exact:true}).click();await page.locator('#rule-order-recognition').getByText('148396',{exact:true}).waitFor();await page.getByRole('button',{name:'在此配置字段识别',exact:true}).click();await page.locator('#fm-save').click();await page.getByText('字段对应草稿已保存。',{exact:true}).waitFor();await page.locator('#fm-check').click();await page.getByText('识别检查完成,请核对订单与文件名。',{exact:true}).waitFor();await page.locator('#fm-confirm').check();let release,arrive;const gate=new Promise(r=>release=r),arrived=new Promise(r=>arrive=r);await page.route('**/api/order-rules',async route=>{arrive();await gate;await route.continue();});await page.locator('#fm-activate').click();await arrived;const locked=await page.getByLabel('收件人',{exact:true}).isDisabled();release();await page.getByText(/字段配置已生效,已同步规则版本/).waitFor();assert.equal(locked,true);assert.equal(await page.evaluate(()=>PageLifecycle.dirty()),false);assert.match(await page.locator('#rule-version-state').innerText(),new RegExp('草稿 v'+runtime.orderRules.get('rules','bs-change').draft.version));});
+9 -8
View File
@@ -24,7 +24,7 @@
const sourcesFor=value=>data.samples.filter(c=>c.provenance==='server-provider'&&c.sample?.demo!==true&&c.sample?.source!=='history'&&(value.processNames||[]).includes(c.processName)).map(c=>({id:'capture:'+c.id,sampleId:c.id,label:(c.sample.serialNum||'待办订单')+' · '+c.processName+' · '+formatDate(c.sample.receivedAt),processName:c.processName,sample:c.sample}));
let sources=sourcesFor(rule);
const recognition=(data.catalogError?`<div class="alert alert-warning">订单读取失败:${esc(data.catalogError)}。请刷新重试,或到<a href="#order-execution">订单执行</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.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">草稿 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>`;
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.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>`;
const form=panel.querySelector('#order-rule-editor'),owned=()=>isActive()&&panel.querySelector('#order-rule-editor')===form;
const read=()=>window.OrderRuleEditor.read(form,rule,data.adapters);let baseline,selectedSampleId=null,proposal=null,syncConflicts=[],remoteBaseline=null,proposalSources=null,inlineLoading=false;
function coverage(){
@@ -62,16 +62,17 @@
pickerController=window.FieldSamplePicker.mount(panel.querySelector('#rule-order-picker'),{api,esc,formatDate,user,isActive:owned,processNames:rule.processNames,connections:data.connections,guardSelection:apply=>window.PageLifecycle.guard(apply),onSelect:({sampleId})=>selectSample(sampleId),feedback});
const editable=['name','archiveDirectory','subjectPrefix','intro','signature','filenameDate','scopes','to','cc','attachPdf','bodyTemplateId','adapterIds'];
function applyValues(value){for(const k of ['name','archiveDirectory','subjectPrefix','intro','signature','filenameDate'])form.elements.namedItem(k).value=value[k]||'';for(const k of ['to','cc'])form.elements.namedItem(k).value=(value[k]||[]).join('\n');form.elements.namedItem('attachPdf').checked=value.attachPdf;form.elements.namedItem('bodyTemplateId').value=value.bodyTemplateId??(form.querySelector('option[value="__legacy__"]')?'__legacy__':'');scopeController.setScopes(value.scopes||[]);resourceController?.setDirectory?.(value.archiveDirectory||'');}
async function syncAfterMapping(){proposalSources=null;
const local=read(),base=JSON.parse(baseline),fresh=await api('/order-rules');if(!owned())return;const remote=fresh.rules.find(r=>r.id===rule.id);if(!remote)throw Error('分类已不可用,页面输入已保留');const fields=await api('/order-rules/fields');if(!owned())return;data.adapters=fields.adapters||data.adapters;data.fieldProcesses=fields.processes||[];remote.scopes=window.OrderRuleScopes.scopesFor(remote);remote.adapterIds=window.OrderRuleEditor.adaptersFor(remote,data.adapters);const merged={...remote};syncConflicts=[];
for(const k of editable){const changedLocal=JSON.stringify(local[k])!==JSON.stringify(base[k]),changedRemote=JSON.stringify(remote[k])!==JSON.stringify(base[k]);if(changedLocal&&changedRemote&&JSON.stringify(local[k])!==JSON.stringify(remote[k]))syncConflicts.push(k);if(changedLocal)merged[k]=local[k];}
Object.assign(rule,remote);remoteBaseline=structuredClone(remote);baseline=JSON.stringify(remote);applyValues(merged);changed();if(syncConflicts.length){feedback('字段配置已生效;以下分类字段同时被修改:'+syncConflicts.join('、')+'。页面值已保留,解决冲突后再保存。','warning');drawSyncConflicts();}else feedback('字段配置已生效,已同步规则版本;未保存的分类输入已保留。');
}
async function syncAfterMapping(){return mutate(async()=>{proposalSources=null;
const local=read(),base=JSON.parse(baseline),fresh=await api('/order-rules');if(!owned())return;const remote=fresh.rules.find(r=>r.id===rule.id);if(!remote)throw Error('分类已不可用,页面输入已保留');const fields=await api('/order-rules/fields?view=directory');if(!owned())return;data.adapters=fields.adapters||data.adapters;data.fieldProcesses=fields.processes||[];remote.scopes=window.OrderRuleScopes.scopesFor(remote);remote.adapterIds=window.OrderRuleEditor.adaptersFor(remote,data.adapters);
Object.assign(rule,remote);applyValues(remote);const normalized=read(),merged={...normalized};syncConflicts=[];
for(const k of editable){const changedLocal=JSON.stringify(local[k])!==JSON.stringify(base[k]),changedRemote=JSON.stringify(normalized[k])!==JSON.stringify(base[k]);if(changedLocal&&changedRemote&&JSON.stringify(local[k])!==JSON.stringify(normalized[k]))syncConflicts.push(k);if(changedLocal)merged[k]=local[k];}
remoteBaseline=structuredClone(normalized);baseline=JSON.stringify(normalized);applyValues(merged);panel.querySelector('#rule-version-state').textContent='草稿 v'+rule.version+' · 已发布 '+(rule.publishedVersion?'v'+rule.publishedVersion:'无')+' · Excel 行 '+(rule.sourceRow??'—');changed();if(syncConflicts.length){feedback('字段配置已生效;以下分类字段同时被修改:'+syncConflicts.join('、')+'。页面值已保留,解决冲突后再保存。','warning');drawSyncConflicts();}else feedback('字段配置已生效,已同步规则版本;未保存的分类输入已保留。');
},{mappingSync:true});}
function drawSyncConflicts(){const host=panel.querySelector('#rule-order-scope');const old=host.querySelector('[data-sync-conflicts]');old?.remove();if(!syncConflicts.length)return;const box=document.createElement('div');box.dataset.syncConflicts='';box.className='alert alert-warning';box.innerHTML=syncConflicts.map(k=>'<div>'+esc(k)+':<button type="button" class="btn btn-sm" data-keep="'+esc(k)+'">保留页面值</button><button type="button" class="btn btn-sm" data-remote="'+esc(k)+'">采用服务器值</button></div>').join('');host.append(box);box.querySelectorAll('button').forEach(b=>b.onclick=()=>{const k=b.dataset.keep||b.dataset.remote;if(b.dataset.remote){const value=read();value[k]=remoteBaseline[k];applyValues(value);}syncConflicts=syncConflicts.filter(f=>f!==k);changed();drawSyncConflicts();});}
async function openInline(nextSources){if(!selectedSampleId){feedback('请先选择真实订单。','warning');return;}if(nextSources){proposalSources=structuredClone(nextSources);requestProposal();}if(inlineController){if(nextSources)inlineController.setSources(nextSources);return;}if(inlineLoading)return;inlineLoading=true;const id=selectedSampleId,host=panel.querySelector('#rule-inline-mapping');host.hidden=false;try{const next=await window.FieldMappingViews.render(host,{api,esc,formatDate,user,isActive:()=>owned()&&selectedSampleId===id,feedback,initialSampleId:id,embedded:true,onActivated:syncAfterMapping,onSourcesChanged:sources=>{proposalSources=sources;requestProposal();}});if(!owned()||selectedSampleId!==id){next?.dispose();return;}inlineController=next;if(nextSources)inlineController?.setSources(nextSources);}catch(error){if(owned())feedback(error.message,'danger');}finally{inlineLoading=false;}}
const inlineOpen=panel.querySelector('#rule-inline-open');if(inlineOpen)inlineOpen.onclick=()=>openInline();
async function mutate(work){
if(saving||!owned())return false;saving=true;form.setAttribute('aria-busy','true');
async function mutate(work,{mappingSync=false}={}){
if(saving||!owned())return false;if(!mappingSync&&panel.querySelector('#rule-inline-mapping #fm-editor[aria-busy=true]')){feedback('字段操作尚未完成,请等待核实后再修改分类。','warning');return false;}saving=true;form.setAttribute('aria-busy','true');
const locked=[...panel.querySelectorAll('input,select,textarea,button'),container.querySelector('#rule-import-open')].filter(e=>e&&!e.disabled);locked.forEach(e=>e.disabled=true);
try{return await work();}finally{saving=false;form.removeAttribute('aria-busy');if(form.isConnected){locked.forEach(e=>{if(e.isConnected)e.disabled=false;});const publish=form.querySelector('#order-rule-publish');if(publish)publish.disabled=dirty;}const open=container.querySelector('#rule-import-open');if(open?.isConnected)open.disabled=false;}
}