perf: optimize full interface loading and refresh paths

This commit is contained in:
abaishu0730 committed 2026-10-28 09:24:04 +08:00
1 parent 649a0df832
commit f317314a3c
57 files changed
+791 -136

No files matched your search

+6 -5
View File
@@ -4,8 +4,8 @@ window.OrderViews=(()=>{
const defaults=()=>({scope:'current',business:'orders',kind:'all',q:'',connectionId:'',from:'',to:'',page:1});
function configure(options){if(user?.username!==options.user.username)filters=defaults();({api,esc,formatDate,notify,user}=options);}
async function records(container,isActive){
filters=window.RecordState.read('records');let disposed=false,status=null,timer,statusController;const live=()=>!disposed&&isActive(),get=id=>container.querySelector('#'+id);
window.PageLifecycle?.onDispose(()=>{disposed=true;clearTimeout(timer);statusController?.abort();});
filters=window.RecordState.read('records');let disposed=false,status=null,statusController;const live=()=>!disposed&&isActive(),get=id=>container.querySelector('#'+id);
window.PageLifecycle?.onDispose(()=>{disposed=true;statusController?.abort();});
const option=(value,label,current)=>'<option value="'+esc(value)+'" '+(value===current?'selected':'')+'>'+esc(label)+'</option>';
container.innerHTML='<div class="record-monitor small text-secondary" data-monitor aria-live="polite">正在读取监听状态…</div><div class="alert alert-warning" data-record-error hidden role="alert"></div><section class="card"><div class="card-header flex-wrap gap-2"><h2 class="card-title">流程到达台账</h2><div class="btn-list ms-auto"><a href="#bpm" class="btn btn-sm">管理连接</a>'+(user.role!=='viewer'?'<button type="button" class="btn btn-primary btn-sm" id="scan-now">立即同步</button>':'')+'</div></div><div class="card-body record-filters"><div class="row g-3"><div class="col-12 col-sm-6 col-lg-4"><label class="form-label" for="arrival-query">搜索流程记录</label><input class="form-control" id="arrival-query" maxlength="200" placeholder="流水号、流程、订单标题" value="'+esc(filters.q)+'"></div><div class="col-6 col-sm-3 col-lg-2"><label class="form-label" for="arrival-scope">记录范围</label><select class="form-select" id="arrival-scope">'+option('current','现有连接',filters.scope)+option('archived','历史归档',filters.scope)+option('all','全部来源',filters.scope)+'</select></div><div class="col-6 col-sm-3 col-lg-2"><label class="form-label" for="arrival-business">业务范围</label><select class="form-select" id="arrival-business">'+option('orders','订单相关流程',filters.business)+option('all','全部 BPM 流程',filters.business)+'</select></div><div class="col-6 col-sm-8 col-lg-2"><label class="form-label" for="arrival-kind">到达类型</label><select class="form-select" id="arrival-kind">'+option('all','全部到达类型',filters.kind)+option('todo','待办到达记录',filters.kind)+option('inform','待阅到达记录',filters.kind)+'</select></div><div class="col-6 col-sm-4 col-lg-2 d-flex align-items-end"><button type="button" class="btn w-100" id="arrival-submit" data-record-query>查询</button></div></div><details class="mt-3"><summary class="small text-secondary">更多筛选:来源与日期</summary><div class="row g-3 mt-0"><div class="col-12 col-md-4"><label class="form-label" for="arrival-connection">来源连接</label><select class="form-select" id="arrival-connection"><option value="">全部来源连接</option></select></div><div class="col-6 col-md-4"><label class="form-label" for="arrival-from">起始日期</label><input class="form-control" id="arrival-from" type="date" value="'+esc(filters.from)+'"></div><div class="col-6 col-md-4"><label class="form-label" for="arrival-to">结束日期</label><input class="form-control" id="arrival-to" type="date" value="'+esc(filters.to)+'"></div></div></details></div><div data-arrival-list></div>'+window.RecordUi.footer+'</section><div class="small text-secondary mt-2">按北京时间记录到达历史 · 分类与邮件批次见 <a href="#notification-orders">通知订单</a></div>';
const detail=window.RecordUi.details(container,'流程到达详情');
@@ -16,9 +16,10 @@ window.OrderViews=(()=>{
function open(row,trigger){const f=(label,value)=>window.RecordUi.field(esc,label,value);detail.show('<dl class="record-detail-grid">'+f('流水号',row.serialNum)+f('流程',row.processName)+f('流程版本',row.processVersion)+f('节点',row.activityName)+f('到达类型',row.kind==='todo'?'待办到达记录':'待阅到达记录')+f('到达时间',formatDate(row.arrivedAt))+f('来源连接',row.origin.name)+f('来源账号',row.origin.identity||'账号未记录')+f('负责人',row.origin.owner)+f('来源状态',row.origin.status==='archived'?'历史归档':row.origin.enabled?'现有连接':'现有连接 · 已停用')+f('来源归档时间',row.origin.archivedAt?formatDate(row.origin.archivedAt):row.origin.status==='archived'?'未记录':'—')+(row.origin.missing?f('来源说明','来源信息缺失,保留原连接标识:'+row.connectionId):'')+f('首次采集',formatDate(row.firstSeenAt))+f('最近观察',formatDate(row.lastSeenAt))+f('任务标识',row.taskId)+f('完整标题',row.subject)+'</dl>',trigger);}
function draw(data){const host=container.querySelector('[data-arrival-list]');host.innerHTML=data.items.length?'<div class="table-responsive"><table class="table table-vcenter table-hover card-table record-ledger"><thead><tr><th scope="col">流水号/流程</th><th scope="col" class="record-node">节点/类型</th><th scope="col">标题摘要</th><th scope="col" class="record-source">来源</th><th scope="col" class="record-time">到达时间</th><th scope="col">详情</th></tr></thead><tbody>'+data.items.map((row,index)=>'<tr data-arrival-row><td class="record-identity"><strong>'+esc(row.serialNum||'—')+'</strong><div class="small text-secondary">'+esc(row.processName)+'</div><div class="record-inline-source small text-secondary">'+esc(row.origin.name)+(row.origin.status==='archived'?' · 历史归档':row.origin.enabled?'':' · 已停用')+'</div><div class="record-inline-time small text-secondary">'+esc(formatDate(row.arrivedAt))+'</div><div class="record-inline-summary record-summary small">'+esc(row.subject||'—')+'</div></td><td class="record-node">'+esc(row.activityName==='sysInform'?'知会':row.activityName||'—')+'<div class="small text-secondary">'+(row.kind==='todo'?'待办到达':'待阅到达')+'</div></td><td class="record-summary-cell"><div class="record-summary">'+esc(row.subject||'—')+'</div></td><td class="record-source"><div>'+esc(row.origin.name)+'</div><span class="badge bg-'+(row.origin.status==='archived'?'secondary':row.origin.enabled?'green':'yellow')+'-lt">'+(row.origin.status==='archived'?'历史归档':row.origin.enabled?'现有连接':'已停用')+'</span></td><td class="record-time small text-secondary text-nowrap">'+esc(formatDate(row.arrivedAt))+'</td><td class="record-action"><button type="button" class="btn btn-sm" data-arrival-detail="'+index+'">查看详情</button></td></tr>').join('')+'</tbody></table></div>':'<div class="empty py-5"><p class="empty-title">暂无匹配的到达记录</p><p class="empty-subtitle text-secondary">可调整日期、业务范围或查看历史归档。</p></div>';host.querySelectorAll('[data-arrival-detail]').forEach(button=>button.onclick=()=>open(data.items[Number(button.dataset.arrivalDetail)],button));sourceOptions(data.sources);monitor();}
const table=window.RecordTable.mount({view:'records',container,isActive:live,api,onCommit:next=>{filters=next;},render:draw,readDraft(){const scope=get('arrival-scope').value;return {q:get('arrival-query').value.trim(),scope,business:get('arrival-business').value,kind:get('arrival-kind').value,connectionId:filters.scope!==scope?'':get('arrival-connection').value,from:get('arrival-from').value,to:get('arrival-to').value};},writeDraft(next){for(const [field,id]of Object.entries({q:'arrival-query',scope:'arrival-scope',business:'arrival-business',kind:'arrival-kind',connectionId:'arrival-connection',from:'arrival-from',to:'arrival-to'}))get(id).value=next[field];}});
async function refresh(){clearTimeout(timer);try{statusController?.abort();statusController=new AbortController();const next=await api('/bpm-scan',undefined,{signal:statusController.signal});if(!live())return;status=next;monitor();const runs=status.runs.filter(r=>(filters.kind==='all'||(r.kind||'inform')===filters.kind)&&(!filters.connectionId||r.connectionId===filters.connectionId));if(runs[0]?.status==='error')container.querySelector('[data-monitor]').textContent+=' · 最近同步失败:'+runs[0].message;else if(runs[0]?.status==='success')container.querySelector('[data-monitor]').textContent+=' · 同步完成 '+formatDate(runs[0].finishedAt);}catch(e){if(live())error('监听状态读取失败:'+e.message);}finally{if(live())timer=setTimeout(refresh,10000);}}
if(get('scan-now'))get('scan-now').onclick=async()=>{const button=get('scan-now');button.disabled=true;try{for(const c of candidates())for(const kind of filters.kind==='all'?['todo','inform']:[filters.kind])await api('/bpm-scan/run',{connectionId:c.id,kind});if(live()){notify('只读同步已启动。');clearTimeout(timer);await refresh();}}catch(e){if(live())error(e.message+';已接受的同步请查看最新结果。');}finally{if(live())monitor();}};
await table.ready;if(!live())return;await refresh();
async function refresh(signal){try{statusController?.abort();statusController=new AbortController();const next=await api('/bpm-scan',undefined,{signal:AbortSignal.any([signal,statusController.signal]),ownerCheck:live});if(!live())return;status=next;monitor();const runs=status.runs.filter(r=>(filters.kind==='all'||(r.kind||'inform')===filters.kind)&&(!filters.connectionId||r.connectionId===filters.connectionId));if(runs[0]?.status==='error')container.querySelector('[data-monitor]').textContent+=' · 最近同步失败:'+runs[0].message;else if(runs[0]?.status==='success')container.querySelector('[data-monitor]').textContent+=' · 同步完成 '+formatDate(runs[0].finishedAt);}catch(e){if(!signal.aborted&&live())error('监听状态读取失败:'+e.message);}}
const polling=window.PageLifecycle.poll(refresh,10000,{isActive:live});
if(get('scan-now'))get('scan-now').onclick=async()=>{const button=get('scan-now');button.disabled=true;try{for(const c of candidates())for(const kind of filters.kind==='all'?['todo','inform']:[filters.kind])await api('/bpm-scan/run',{connectionId:c.id,kind});if(live()){notify('只读同步已启动。');await polling.refresh();}}catch(e){if(live())error(e.message+';已接受的同步请查看最新结果。');}finally{if(live())monitor();}};
await Promise.all([table.ready,polling.run()]);
}
return {configure,records};
})();
+11 -11
View File
@@ -15,12 +15,12 @@ window.BpmLogin=(()=>{
const status=(c,kind='account')=>{const state=observation(c,kind),[color,label]=({healthy:['green','健康'],error:['red','异常'],pending:['yellow','警告'],paused:['yellow','已暂停']})[state.status]||['yellow','待确认'];return `<span class="bpm-account-status bpm-status-${color}"><span class="bpm-status-light" aria-hidden="true"></span>${kind==='account'?'账号':'同步'} · ${label}</span>`;};
function feedback(message,type='danger'){if(!live())return;const el=$('[data-bpm-feedback]');if(el){el.hidden=false;el.className=`alert alert-${type}`;el.textContent=message;}notify(message,type);}
function release(r,{unload=false}={}){
r.closed=true;clearTimeout(r.timer);r.controller?.abort();if(r.url){URL.revokeObjectURL(r.url);r.url=null;}
r.closed=true;r.polling?.dispose();r.controller?.abort();if(r.url){URL.revokeObjectURL(r.url);r.url=null;}
if(unload){if(!r.closeRequest)r.closeRequest=fetch('/api'+route(r.id,'login/close'),{method:'POST',credentials:'same-origin',keepalive:true,headers:{'Content-Type':'application/json'},body:'{}'}).then(()=>{}).catch(()=>{});return r.closeRequest;}
if(r.release)return r.release;
r.release=(async()=>{await r.opening.catch(()=>{});await r.queue.catch(()=>{});await r.operation?.catch(()=>{});if(!r.closeRequest)r.closeRequest=api(route(r.id,'login/close'),{}).catch(()=>{});await r.closeRequest;})();return r.release;
}
const handle={dispose(options){disposed=true;++statusRevision;clearTimeout(statusTimer);container.querySelectorAll('[data-account-form]').forEach(form=>form.reset());return remote?release(remote,options):Promise.resolve();}};
const handle={dispose(options){disposed=true;++statusRevision;statusTimer?.dispose();container.querySelectorAll('[data-account-form]').forEach(form=>form.reset());return remote?release(remote,options):Promise.resolve();}};
active=handle;
const valid=r=>live()&&remote===r&&!r.closed;
function controls(r){if(!valid(r))return;container.querySelectorAll('[data-bpm-control]').forEach(el=>el.disabled=!!r.busy);const input=$('[data-bpm-input]');if(input)input.disabled=!!r.busy;}
@@ -94,14 +94,14 @@ window.BpmLogin=(()=>{
+row('投递重试',delivery.retryAt?formatDate(delivery.retryAt):'无')
+(delivery.message?row('投递说明',delivery.message):'')+'</details>';
}
async function refreshStatus(){
async function refreshStatus(signal){
if(!live())return;
try{
if(accountBusy||mutationBusy)return;const request=statusRevision,next=await api('/workspace');if(!live()||request!==statusRevision)return;
if(accountBusy||mutationBusy)return;const request=statusRevision,next=await api('/workspace',undefined,{signal,ownerCheck:live});if(!live()||request!==statusRevision)return;
const rows=next.connections||[],changed=JSON.stringify(connections.map(c=>[c.id,c.status,c.version,c.owner]))!==JSON.stringify(rows.map(c=>[c.id,c.status,c.version,c.owner]));connections=rows;
if(changed&&!remote&&!container.querySelector('[data-account-form]')&&!window.PageLifecycle?.dirty())drawCards();
else for(const c of connections){const badge=container.querySelector('[data-connection-status="'+c.id+'"]'),health=container.querySelector('[data-connection-health="'+c.id+'"]');if(badge)badge.innerHTML=status(c);if(health){const expanded=health.querySelector('details')?.open;health.innerHTML=observations(c);if(expanded)health.querySelector('details').open=true;}}
}catch{}finally{if(live())statusTimer=setTimeout(refreshStatus,5000);}
}catch{}
}
function ownerForm(c){
if(user.role!=='admin')return '';
@@ -138,21 +138,21 @@ window.BpmLogin=(()=>{
catch(error){feedback(error.message);}finally{accountControls(false);}
}
async function mutate(button,action,message){++statusRevision;mutationBusy=true;button.disabled=true;try{const id=button.dataset[action],connection=connections.find(c=>c.id===id);const result=await api(route(id,action),['enable','disable'].includes(action)?{version:connection.version||0}:{});if(!live())return;update(result,button.dataset[action]);feedback(message,'success');}catch(error){feedback(error.message);}finally{mutationBusy=false;if(live())button.disabled=false;}}
async function frame(r){
async function frame(r,signal){
if(!valid(r))return;
try{
r.controller=new AbortController();
const response=await fetch('/api'+route(r.id,'login/frame'),{credentials:'same-origin',cache:'no-store',signal:r.controller.signal});
const response=await fetch('/api'+route(r.id,'login/frame'),{credentials:'same-origin',cache:'no-store',signal:AbortSignal.any([signal,r.controller.signal])});
if(!response.ok){let message='登录画面加载失败,请重新打开窗口。';try{message=(await response.json()).error||message;}catch{}throw new Error(message);}
const blob=await response.blob();if(!valid(r))return;
const url=URL.createObjectURL(blob),old=r.url;r.url=url;const image=$('[data-bpm-frame]');image.src=url;image.hidden=false;const loading=$('[data-bpm-loading]');if(loading)loading.hidden=true;if(old)URL.revokeObjectURL(old);
}catch(error){if(valid(r)&&error.name!=='AbortError'){feedback(error.message);await close(r);return;}}
if(valid(r))r.timer=setTimeout(()=>frame(r),650);
}
async function close(r){if(remote===r)remote=null;await release(r);if(live()){$('#bpm-remote').innerHTML='';drawCards();}}
async function open(id){
if(remote||accountBusy||!live())return;
const r={id,closed:false,queue:Promise.resolve(),busy:false,failed:false,url:null,timer:null};remote=r;drawCards();
const r={id,closed:false,queue:Promise.resolve(),busy:false,failed:false,url:null};remote=r;drawCards();
r.opening=api(route(id,'login/open'),{});
try{
const session=await r.opening;if(!valid(r)){await release(r);return;}
@@ -171,7 +171,7 @@ window.BpmLogin=(()=>{
try{await r.queue;if(!valid(r))return;if(r.failed)throw Error('输入未送达,请关闭后重新打开登录窗口。');r.operation=api(route(id,'login/save'),{});const result=await r.operation;if(!valid(r))return;update(result,id);const saved=result.connection||result;feedback(saved.status==='connected'?'连接已检查并保存。':'请完成登录后再次检查。',saved.status==='connected'?'success':'warning');}
catch(error){feedback(error.message);}finally{r.busy=false;if(valid(r)){controls(r);$('[data-bpm-close]').disabled=false;$('[data-bpm-save-state]').textContent='完成登录后保存连接';}}
};
frame(r);
r.polling=window.PageLifecycle.poll(signal=>frame(r,signal),650,{isActive:()=>valid(r)});void r.polling.run();
}catch(error){if(valid(r)){remote=null;drawCards();feedback(error.message);}}
}
function bindInput(r){
@@ -199,7 +199,7 @@ window.BpmLogin=(()=>{
if(user.role==='admin')$('#connection-create').onsubmit=async event=>{event.preventDefault();const button=event.target.querySelector('button[type=submit]');button.disabled=true;try{const result=await api('/connections',{name:$('#connection-name').value.trim(),owner:$('#connection-owner').value});if(!live())return;++statusRevision;connections.unshift(result.connection||result);event.target.reset();drawCards();feedback('连接已创建。','success');}catch(error){feedback(error.message);}finally{if(live())button.disabled=false;}};
drawCards();
connections.filter(c=>c.status!=='disabled'&&authorized(c)).forEach(c=>loadAccount(c.id).then(refreshAccountSummary).catch(error=>feedback(error.message)));
statusTimer=setTimeout(refreshStatus,5000);
statusTimer=window.PageLifecycle.poll(refreshStatus,5000,{isActive:live});
await window.BpmSyncSettings?.mount($('#bpm-sync-settings'),{api,user,notify,isActive:live});
}catch(error){if(live())throw error;}
}