(() => { 'use strict'; let api,esc,formatDate,notify,user; async function render(container,isActive=()=>true,section='rules'){ const tab=section==='fields'?'fields':'rules',admin=user.role==='admin',operator=user.role!=='viewer'; const {empty}=window.OrderNotificationShared.create({esc}); container.innerHTML=`
${tab==='rules'?'按 Excel 分类维护,使用真实 BPM 订单检查':'维护BPM实际采集的流程与节点'}
${admin&&tab==='rules'?'':''}
`; const panel=container.querySelector('#order-rules-panel'); let data={rules:[],adapters:[],samples:[],resources:{}},selectedId,dirty=false,revision=0,trialRevision=0,controller,resourceController,importController,unregister,query='',filter='all',saving=false,refreshCurrent=reload,switchCurrent,mutationCurrent,scopeController; const sampleCache=new Map(),processKey=value=>JSON.stringify([...new Set(value.processNames||[])].sort());let sampleController,sampleRequest=0,refreshControls=()=>{}; const feedback=(message,type='success')=>{if(!isActive())return;const node=container.querySelector('#order-rules-feedback');node.textContent=message;node.className='alert alert-'+type;}; async function action(button,work){if(button.disabled)return false;const owner=panel.firstElementChild;button.disabled=true;try{return await work();}catch(error){if(isActive()&&panel.firstElementChild===owner)feedback(error.message,'danger');return false;}finally{if(button.isConnected)button.disabled=false;}} async function reload(){ if(!isActive())return false;const request=++revision;++trialRevision; if(tab==='fields'){controller?.dispose?.();const next=await window.OrderExecutionViews.fields(panel,{api,esc,formatDate,user,isActive:()=>isActive()&&request===revision,feedback});if(isActive()&&request===revision)controller=next;return true;} const snapshot=await api('/order-rules/configuration'); if(!isActive()||request!==revision)return false; if(!Array.isArray(snapshot.rules)||!Array.isArray(snapshot.adapters))throw Error('规则配置响应无效,请刷新重试。'); const resources=snapshot.resources||{},previous=data.resources;data={...snapshot,scopeCatalog:snapshot.scopeCatalog||[],resources:{templates:resources.templates??previous.templates??[],bindings:resources.bindings??previous.bindings??[],servers:resources.servers??previous.servers??[],errors:Object.entries(resources.errors||{}).map(([kind,message])=>({kind:kind==='servers'?'storage':'mail',message}))}};sampleCache.clear();dirty=false;draw();return true; } function restrictedNotice(){const restrictedActive=data.restrictedTest?.enabled===true;return data.restrictedTest?'
'+(restrictedActive?'受限稳定性测试:'+Number(data.restrictedTest.ruleCount)+' 类纳入测试,'+Number(data.restrictedTest.readyCount)+' 类当前生效。分类计数不代表全部流程已完成实单验证。保存后点击“应用到测试”,新任务使用新规则;旧订单和批次保持原快照。':'受限稳定性测试已暂停。可继续维护、验证和发布草稿;这些操作不会恢复测试发送。')+(data.restrictedTest.uncovered?.length?'另有 '+Number(data.restrictedTest.uncovered.length)+' 个流程待采样或适配,暂不自动处理;'+(restrictedActive?'其他已覆盖流程继续运行。':'测试已暂停。')+'':'')+'查看测试设置
':'';} function draw(){ unregister?.();resourceController?.dispose();scopeController?.dispose();sampleController?.abort();++sampleRequest;++trialRevision; if(!data.rules.length){panel.innerHTML=`
${empty('暂无分类规则,请先导入经确认的 Excel 分类。')}
`;return;} const rule=data.rules.find(r=>r.id===selectedId)||data.rules[0],restrictedActive=data.restrictedTest?.enabled===true;selectedId=rule.id; const sourcesFor=value=>(sampleCache.get(processKey(value))||[]).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=window.OrderRulePreview.panel(sources,{esc,operator,lazy:true,loaded:sampleCache.has(processKey(rule))}); panel.innerHTML=`
分类规则

${esc(rule.name)}

草稿 v${esc(rule.version)} · 已发布 ${esc(rule.publishedVersion?'v'+rule.publishedVersion:'无')} · Excel 行 ${esc(rule.sourceRow??'—')}
${window.OrderRuleEditor.render(rule,data.adapters,{esc,admin,resources:data.resources,recognition})}
`; if(data.restrictedTest)panel.insertAdjacentHTML('afterbegin',restrictedNotice()); if(admin&&rule.publishedVersion&&!restrictedActive){ const migration=document.createElement('section');migration.className='card mt-3'; migration.innerHTML='

将未冻结订单迁移到已发布版本

仅当前已发布版本。冻结、发送及结果不确定订单不改写;输出变化会要求新代归档。

'; panel.querySelector('.rule-editor-column').append(migration); const preview=migration.querySelector('[data-migration-preview]');preview.onclick=()=>action(preview,async()=>{ const note=migration.querySelector('textarea').value.trim();if(note.length<5)throw Error('请填写至少5字迁移依据。'); const body={version:rule.publishedVersion,note,idempotencyKey:window.PageLifecycle.requestKey()},path='/order-rules/rules/'+encodeURIComponent(rule.id)+'/migration/'; const result=await api(path+'preview',body);if(!isActive()||!migration.isConnected)return; const host=migration.querySelector('[data-migration-result]');host.innerHTML='

可迁移 '+result.items.length+' 项;排除 '+result.excluded.length+' 项。

'+result.items.map(i=>'

'+esc(i.id)+' · '+(i.archiveChanged?'需要重新归档':'保留归档证据')+'

').join('')+result.excluded.map(i=>'

'+esc(i.id)+' · '+esc(i.reason)+'

').join('')+''; host.querySelector('button').onclick=event=>action(event.currentTarget,async()=>{await api(path+'apply',body);if(isActive()){host.textContent='迁移已应用,请到订单中心核对处理与归档状态。';}}); }); } const form=panel.querySelector('#order-rule-editor'),owned=()=>isActive()&&panel.querySelector('#order-rule-editor')===form; if(admin&&restrictedActive){form.querySelector('#order-rule-publish').textContent='应用到测试';panel.querySelector('#rule-version-state').textContent='草稿 v'+rule.version+' · 当前测试 '+(rule.testVersion?'v'+rule.testVersion:'未应用')+' · Excel 行 '+(rule.sourceRow??'—');} const read=()=>window.OrderRuleEditor.read(form,rule,data.adapters);let baseline; function coverage(value=read()){ const missing=value.processNames.filter(p=>!data.adapters.some(a=>a.processName===p&&a.verified&&!a.reference&&value.adapterIds.includes(a.id))); const host=panel.querySelector('#rule-field-coverage');host.textContent=data.catalogError?'识别接口状态暂不可用。':rule.mappingIssue?'识别接口已变化,需重新验证。':missing.length?'识别接口待配置:'+missing.length+' 个流程。':'已有生效识别接口;实际订单仍按版本检查。'; const link=document.createElement('a');link.href='#rule-fields';link.textContent='字段映射';link.className='ms-2';host.append(link); } function changed(){ if(!owned())return;const value=read();++trialRevision;dirty=JSON.stringify(value)!==baseline; panel.querySelector('#order-rule-explanation-title').textContent=dirty?'查看当前配置的处理说明(尚未保存)':'查看已保存规则的处理说明'; panel.querySelector('#order-rule-explanation').textContent=window.OrderRuleEditor.describe(value); panel.querySelector('#order-rule-dirty').textContent=dirty?'有未保存的修改。保存后请重新检查识别结果,再发布。':''; panel.querySelector('#order-rule-preview-result').innerHTML='

配置已变化,请重新检查。

'; const publish=panel.querySelector('#order-rule-publish');if(publish)publish.disabled=dirty||saving;coverage(value);refreshSources(value); } const catalog=data.scopeCatalog; if(data.scopeError)panel.querySelector('#rule-scopes').insertAdjacentHTML('afterbegin','
字段映射目录读取失败:'+esc(data.scopeError)+'。请刷新重试;未加载时不能新增匹配项。
'); scopeController=window.OrderRuleScopes.bind(panel.querySelector('#rule-scopes'),{catalog,processes:data.scopeProcesses,esc,admin,onChange:changed}); resourceController=window.OrderRuleResources.bind(form,data.resources,{api,esc,owned,changed,admin});baseline=JSON.stringify(read());coverage(); const source=panel.querySelector('#order-rule-sample-source'); let currentProcessKey=processKey(rule),samplePending=false; const sampleLoad=panel.querySelector('#order-rule-samples-load'),sampleState=panel.querySelector('#rule-recognition-load-state'); function sampleControls(){const loaded=sampleCache.has(currentProcessKey);source.disabled=saving||samplePending||!loaded;sampleLoad.disabled=saving||samplePending||!JSON.parse(currentProcessKey).length;const check=panel.querySelector('#order-rule-preview');if(check)check.disabled=saving||samplePending||!sources.length;} refreshControls=()=>{if(!owned())return;sampleControls();const publish=form.querySelector('#order-rule-publish');if(publish)publish.disabled=dirty||saving;}; function refreshSources(value=read(),force=false){const key=processKey(value);if(!force&&key===currentProcessKey)return;currentProcessKey=key;sampleController?.abort();++sampleRequest;samplePending=false;const next=sourcesFor(value),selected=source.value;sources=next;const loaded=sampleCache.has(key),empty=panel.querySelector('#rule-recognition-empty');empty.hidden=!!sources.length;empty.querySelector('strong').textContent=loaded?'本类别还没有真实订单可检查':'尚未读取本类别已采集的订单';empty.querySelector('p').innerHTML=loaded?'先在订单执行中采集 BPM 待办,再回到这里读取。':'点击“读取已采集订单”选择本类别的真实通知,再检查识别结果。';source.innerHTML=''+sources.map(a=>'').join('');source.value=sources.some(a=>a.id===selected)?selected:sources[0]?.id||'';sampleState.textContent=loaded?'已读取本类别采集记录。':'验证时读取,编辑规则无需等待。';sampleControls();choose();} async function loadSamples(){if(samplePending||saving||!owned())return;const key=currentProcessKey,request=++sampleRequest;sampleController?.abort();const abort=new AbortController();sampleController=abort;samplePending=true;sampleControls();sampleState.textContent='正在读取已采集订单…'; try{const params=new URLSearchParams();for(const name of JSON.parse(key))params.append('process',name);const result=await api('/order-rules/configuration/samples?'+params,undefined,{signal:abort.signal,ownerCheck:owned});if(!owned()||request!==sampleRequest||key!==currentProcessKey)return;if(!Array.isArray(result.samples))throw Error('采集订单响应无效。');sampleCache.set(key,result.samples);refreshSources(read(),true);} catch(error){if(owned()&&request===sampleRequest&&error.name!=='AbortError')sampleState.textContent='读取失败:'+error.message+';可再次点击读取重试。';} finally{if(owned()&&request===sampleRequest){samplePending=false;sampleControls();}} } sampleLoad.onclick=loadSamples; function choose(){++trialRevision;panel.querySelector('#order-rule-adapter').innerHTML=window.OrderRulePreview.adapter(sources.find(a=>a.id===source.value),{esc});panel.querySelector('#order-rule-preview-result').replaceChildren();} source.value=sources[0]?.id||'';source.onchange=choose;choose();sampleControls(); function updateVersion(){ const testing=data.restrictedTest?.enabled===true;panel.querySelector('#rule-version-state').textContent=testing?'草稿 v'+rule.version+' · 当前测试 '+(rule.testVersion?'v'+rule.testVersion:'未应用')+' · Excel 行 '+(rule.sourceRow??'—'):'草稿 v'+rule.version+' · 已发布 '+(rule.publishedVersion?'v'+rule.publishedVersion:'无')+' · Excel 行 '+(rule.sourceRow??'—'); const notice=panel.querySelector('#rule-restricted-state'),html=restrictedNotice();if(html){if(notice){const template=document.createElement('template');template.innerHTML=html;notice.innerHTML=template.content.firstElementChild.innerHTML;}else panel.insertAdjacentHTML('afterbegin',html);}else notice?.remove(); const publish=form.querySelector('#order-rule-publish');if(publish)publish.textContent=testing?'应用到测试':'发布此版本';panel.querySelector('.rule-version-bar h2').textContent=rule.name; panel.querySelector('.rule-category-directory .card-header .small').textContent=(data.restrictedTest?Number(data.restrictedTest.readyCount)+' 类受限测试 · ':'')+data.rules.filter(r=>r.status==='enabled').length+' 类正式启用 · '+data.rules.filter(r=>r.status!=='enabled').length+' 类未正式启用'; } function applyReceipt(result,{normalize=false}={}){ if(!result||!result.id||!Number.isSafeInteger(result.version))throw Error('写入已返回,但规则状态回执不完整;请刷新核对,勿重复提交。'); const {restrictedTest,...value}=result,target=data.rules.find(item=>item.id===value.id);if(!target)throw Error('规则目录已变化,请刷新核对。');Object.assign(target,value);if(Object.hasOwn(result,'restrictedTest')){data.restrictedTest=restrictedTest;if(!restrictedTest)for(const item of data.rules){delete item.testStatus;delete item.testVersion;delete item.testHasDraft;}else if(!restrictedTest.enabled)for(const item of data.rules){item.testStatus='paused';item.testVersion=null;item.testHasDraft=true;}} if(target===rule){ if(normalize){for(const name of ['name','archiveDirectory','subjectPrefix','intro','filenameDate','productLine']){const input=form.elements.namedItem(name);if(input&&rule[name]!==undefined)input.value=rule[name];}for(const name of ['to','cc'])form.elements.namedItem(name).value=(rule[name]||[]).join('\n');if(JSON.stringify(window.OrderRuleScopes.read(form))!==JSON.stringify(window.OrderRuleScopes.scopesFor(rule)))scopeController.setScopes(window.OrderRuleScopes.scopesFor(rule));resourceController.setDirectory(rule.archiveDirectory);} updateVersion();coverage();const issues=panel.querySelector('#rule-validation-issues');issues.innerHTML=rule.validationIssues?.length?'
启用前待完善
':''; } drawList(); } async function mutate(work){ if(saving||!owned())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;});refreshControls();const open=container.querySelector('#rule-import-open');if(open?.isConnected)open.disabled=false;} } refreshCurrent=()=>mutate(reload);mutationCurrent=mutate; async function save(){ if(!owned()||!form.reportValidity())return false;const value=read(); return mutate(async()=>{try{const result=await api('/order-rules/rules',value);if(!owned())return true;applyReceipt(result,{normalize:true});baseline=JSON.stringify(read());dirty=false;++trialRevision;panel.querySelector('#order-rule-dirty').textContent='';panel.querySelector('#order-rule-explanation-title').textContent='查看已保存规则的处理说明';panel.querySelector('#order-rule-explanation').textContent=window.OrderRuleEditor.describe(read());panel.querySelector('#order-rule-preview-result').innerHTML='

草稿已保存,请重新检查当前版本。

';feedback('规则草稿已保存。');return true;}catch(error){if(owned())feedback(error.message,'danger');return false;}}); } unregister=window.PageLifecycle.register({dirty:()=>owned()&&dirty,save:admin?save:null}); if(admin){ form.onkeydown=event=>{if(event.key==='Enter'&&!event.isComposing&&event.target.tagName==='INPUT'&&event.target.closest('#rule-scopes'))event.preventDefault();};form.oninput=form.onchange=event=>{if(!event.target.matches('.ts-control input,[data-scope-process],[data-scope-node]')&&!['order-rule-sample-source','rule-storage-server','rule-storage-folder'].includes(event.target.id))changed();};form.onsubmit=event=>{event.preventDefault();return save();}; panel.querySelector('#order-rule-publish').onclick=event=>action(event.currentTarget,async()=>{if(dirty||saving)throw Error('请先保存当前修改,再应用或发布。');return mutate(async()=>{const testing=data.restrictedTest?.enabled===true,result=await api(testing?'/order-rules/restricted-test/apply':'/order-rules/rules/'+encodeURIComponent(rule.id)+'/publish',testing?{version:data.restrictedTest.version,rules:[{id:rule.id,version:rule.version}]}:{version:rule.version});if(!owned())return;if(testing){if(!Array.isArray(result.rules))throw Error('应用已返回,请刷新核对测试状态。');data.restrictedTest=result.restrictedTest??Object.fromEntries(Object.entries(result).filter(([key])=>key!=='rules'));for(const row of result.rules)applyReceipt(row);updateVersion();}else applyReceipt(result);baseline=JSON.stringify(read());feedback(testing?'规则已应用到测试,新任务使用当前规则;旧订单和批次保持不变。':'规则版本已发布。自动执行仍由全局设置与接入状态控制。');});}); } if(operator)panel.querySelector('#order-rule-preview').onclick=event=>action(event.currentTarget,async()=>{ if(saving||!form.reportValidity())return;const request=++trialRevision,evidence=sources.find(a=>a.id===source.value);if(!evidence)throw Error('请选择已采集的真实 BPM 订单。'); const body={version:rule.version,...(admin?{draft:read()}:{}),sampleId:evidence.sampleId}; let result;try{result=await api('/order-rules/rules/'+encodeURIComponent(rule.id)+'/trial',body);}catch(error){if(owned()&&request===trialRevision)throw error;return;} if(!owned()||request!==trialRevision)return;panel.querySelector('#order-rule-preview-result').innerHTML=window.OrderRulePreview.result(result,{esc,ruleName:read().name}); }); function drawList(){ const filtered=data.rules.filter(r=>(r.name+' '+r.categoryId).toLocaleLowerCase().includes(query.toLocaleLowerCase())&&(filter==='all'||filter==='needs'&&r.validationIssues?.length||filter==='draft'&&r.hasDraft||filter==='published'&&r.status==='enabled'||filter==='paused'&&r.status==='paused')); panel.querySelector('#rule-category-list').innerHTML=filtered.map(r=>`
${r.testStatus?(r.testStatus==='enabled'?'受限测试中':'测试已暂停'):(r.status==='enabled'?'已启用':r.status==='paused'?'已暂停':'未启用')}
`).join('')||'

没有符合条件的类别,请调整搜索或筛选。

'; panel.querySelectorAll('[data-rule-id]').forEach(button=>button.onclick=()=>{if(button.dataset.ruleId===selectedId||saving)return;window.PageLifecycle.guard(()=>{dirty=false;selectedId=button.dataset.ruleId;draw();});}); switchCurrent=async id=>{if(dirty){dirty=false;draw();return switchCurrent(id);}const current=data.rules.find(r=>r.id===id);if(!current.publishedVersion){dirty=false;selectedId=id;draw();feedback('此分类尚未发布。请先保存草稿,在第04步检查真实订单,再发布启用。','warning');return;}await mutate(async()=>{try{const op=current.status==='enabled'?'pause':'resume',result=await api('/order-rules/rules/'+encodeURIComponent(id)+'/'+op,{version:current.version,publishedVersion:current.publishedVersion,activationVersion:current.activationVersion||0});if(!owned())return;applyReceipt(result);baseline=JSON.stringify(read());feedback(op==='pause'?'此规则已暂停。':'已启用已发布版本,未发布草稿保持不变。');}catch(error){if(owned())feedback(error.message,'danger');}});}; panel.querySelectorAll('[data-rule-toggle]').forEach(toggle=>toggle.onchange=()=>{const id=toggle.dataset.ruleToggle;toggle.checked=data.rules.find(r=>r.id===id).status==='enabled';if(!admin||saving)return;window.PageLifecycle.guard(()=>switchCurrent(id));}); } const search=panel.querySelector('#rule-category-search'),state=panel.querySelector('#rule-category-filter');state.value=filter;search.oninput=()=>{query=search.value;drawList();};state.onchange=()=>{filter=state.value;drawList();};drawList(); const directory=panel.querySelector('#rule-category-list'),active=directory.querySelector('[aria-current]');if(active){const row=active.closest('.rule-category-item').getBoundingClientRect(),list=directory.getBoundingClientRect();directory.scrollTop+=row.top-list.top-(directory.clientHeight-row.height)/2;} } if(admin&&tab==='rules')importController=window.OrderRuleImport.bind(container,{api,esc,active:isActive,reload,feedback,guard:work=>window.PageLifecycle.guard(work),mutate:work=>mutationCurrent(work)}); container.querySelector('#order-rule-refresh').onclick=event=>window.PageLifecycle.guard(()=>action(event.currentTarget,()=>refreshCurrent())); window.PageLifecycle.onDispose(()=>{revision++;trialRevision++;sampleRequest++;sampleController?.abort();controller?.dispose?.();resourceController?.dispose();importController?.dispose();scopeController?.dispose();unregister?.();});await reload(); } window.OrderRuleViews={configure:helpers=>({api,esc,formatDate,notify,user}=helpers),render}; })();