'use strict'; window.BpmLogin=(()=>{ let active=null,releasing=null,releasePending=Promise.resolve(); const statuses={disconnected:['未连接','secondary'],unchecked:['待检查','yellow'],login_required:['待登录','yellow'],connected:['已连接','green'],disabled:['已停用','secondary'],error:['检查失败','red']}; function dispose(options={}){const previous=active||releasing;active=null;if(previous){releasing=previous;releasePending=previous.dispose(options);releasePending.finally(()=>{if(releasing===previous)releasing=null;});}return releasePending;} async function mount(container,{api,esc,formatDate,notify,user,isActive=()=>true}){ await dispose(); if(!isActive())return; let disposed=false,remote=null,accountBusy=false,data,connections=[],statusTimer,statusRevision=0,mutationBusy=false; const accounts=new Map(),accountRequests=new Map(); const live=()=>!disposed&&isActive(); const $=selector=>container.querySelector(selector); const authorized=c=>user.role==='admin'||(user.role==='operator'&&c.owner===user.username); const route=(id,action)=>`/connections/${encodeURIComponent(id)}/${action}`; const status=c=>{const [label,color]=statuses[c.status]||statuses.error;return `${label}`;}; 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;} 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();}}; 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;} function enqueue(r,action){ if(!valid(r)||r.busy)return; r.queue=r.queue.then(()=>{if(valid(r)&&!r.failed)return api(route(r.id,'login/input'),action);}).catch(()=>{if(valid(r)){r.failed=true;feedback('输入未送达,请关闭后重新打开登录窗口。');}}); } function update(result,id){++statusRevision;const saved=result.connection||result;connections=connections.map(c=>c.id===id?{...c,...saved,id}:c);drawCards();} function rememberAccount(id,result){const metadata={configured:result.configured===true,username:typeof result.username==='string'?result.username:'',updatedAt:result.updatedAt||null};accounts.set(id,metadata);return metadata;} function loadAccount(id){ if(accounts.has(id))return Promise.resolve(accounts.get(id)); if(!accountRequests.has(id))accountRequests.set(id,api(route(id,'account')).then(result=>rememberAccount(id,result)).finally(()=>accountRequests.delete(id))); return accountRequests.get(id); } function accountSummary(c){const account=accounts.get(c.id);return account?(account.configured?`自动续登已开启 · ${account.username} · 按请求与会话状态维护`:'自动续登未开启'):'正在加载账号…';} function refreshAccountSummary(){if(live()){container.querySelectorAll('[data-account-summary]').forEach(el=>{const c=connections.find(c=>c.id===el.dataset.accountSummary);if(c)el.textContent=accountSummary(c);});container.querySelectorAll('[data-account]').forEach(button=>button.textContent=accounts.get(button.dataset.account)?.configured?'管理账号':'开启自动续登');}} function accountControls(busy){accountBusy=busy;if(live())container.querySelectorAll('[data-login],[data-check],[data-disable],[data-enable],[data-delete],[data-account]').forEach(el=>el.disabled=busy||!!remote);} async function editAccount(button){ const id=button.dataset.account; if(remote||accountBusy||!live())return; button.disabled=true; try{ const account=await loadAccount(id);if(!live()||!button.isConnected||remote)return; const panel=button.closest('article').querySelector('[data-account-panel]'); panel.innerHTML=`

${account.configured?'管理自动续登账号':'开启自动续登'}

${account.configured?'':''}
`; const form=panel.querySelector('form'),username=form.elements.username,password=form.elements.password; username.value=account.username;panel.hidden=false; panel.scrollIntoView({block:'nearest'});username.focus({preventScroll:true}); form.querySelector('[data-account-cancel]').onclick=()=>{form.reset();panel.innerHTML='';panel.hidden=true;}; const busy=value=>{accountControls(value);form.querySelectorAll('input,button').forEach(el=>el.disabled=value);}; let checkVersion=0; const availability=form.querySelector('[data-account-availability]'); const checkUsername=async()=>{ const value=username.value.trim(),version=++checkVersion; if(!value)return false; const result=await api(route(id,'account/check'),{username:value}); if(!live()||!form.isConnected||version!==checkVersion||value!==username.value.trim())return false; const available=result.available===true,message=available?'该账号可以使用。':'该账号已开启自动续登,请使用已有连接。'; username.setCustomValidity(available?'':message);availability.hidden=false;availability.textContent=message;availability.className='small '+(available?'text-success':'text-danger'); return available; }; username.oninput=()=>{checkVersion++;username.setCustomValidity('');availability.hidden=true;}; username.onblur=()=>{if(username.value.trim()&&!accountBusy)checkUsername().catch(()=>{if(live()&&form.isConnected){availability.hidden=false;availability.className='small text-danger';availability.textContent='账号检查失败,请保存时重试。';}});}; form.onsubmit=async event=>{ event.preventDefault();if(!live()||remote||accountBusy||!form.isConnected||!form.reportValidity()||!username.value.trim())return; const body={username:username.value.trim(),password:password.value};busy(true); try{if(!await checkUsername()){password.value='';return;}const result=await api(route(id,'account'),body);password.value='';if(!live()||!form.isConnected)return;rememberAccount(id,result);form.reset();accountControls(false);if(result.connection)update(result,id);else drawCards();const state=result.connection?.status;feedback(state==='connected'?'自动续登已开启,BPM 已连接。':state==='login_required'?'自动续登已开启,请完成登录验证。':state==='error'?'自动续登已开启,连接检查失败。':'自动续登已开启。',['login_required','error'].includes(state)?'warning':'success');} catch(error){password.value='';feedback(error.message);}finally{busy(false);} }; const clear=form.querySelector('[data-account-clear]');if(clear)clear.onclick=async()=>{ if(!live()||remote||accountBusy||!form.isConnected)return;busy(true);try{const result=await api(route(id,'account/clear'),{});password.value='';if(!live()||!form.isConnected)return;rememberAccount(id,result);form.reset();accountControls(false);drawCards();feedback('自动续登已关闭。','success');}catch(error){feedback(error.message);}finally{busy(false);} }; }catch(error){feedback(error.message);}finally{if(live()&&button.isConnected)button.disabled=false;} } function observations(c){ const health=c.health||{},state={healthy:'可用',login_required:'需要登录',forbidden:'无读取权限',error:'暂不可用',unknown:'尚未检查'},monitor={listening:'推送已连接',connecting:'正在连接',reconnecting:'正在重连',polling:'轮询兜底',login_required:'需要登录',busy:'人工登录中',paused:'已暂停',waiting:'等待就绪'}; const portal=health.portal,legacy=c.checks?.portal; const row=(label,value,at)=>'
'+label+' · '+esc(value)+''+(at?''+esc(formatDate(at))+'':'')+'
'; return row('登录会话',portal?(Date.now()-Date.parse(portal.checkedAt)>300000?'上次检查'+(state[portal.status]||'待确认'):state[portal.status]||'待确认'):legacy?.message||'尚未检查',portal?.checkedAt||c.checkedAt)+row('订单接口',state[health.todo?.status]||'尚未检查',health.todo?.checkedAt)+row('到达监听',monitor[c.monitoring?.status]||'等待就绪',c.monitoring?.lastSyncAt); } async function refreshStatus(){ if(!live())return; try{ if(accountBusy||mutationBusy)return;const request=statusRevision,next=await api('/workspace');if(!live()||request!==statusRevision)return; const rows=next.connections||[],changed=JSON.stringify(connections.map(c=>[c.id,c.status,c.version]))!==JSON.stringify(rows.map(c=>[c.id,c.status,c.version]));connections=rows; if(changed&&!remote&&!container.querySelector('[data-account-form]'))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)health.innerHTML=observations(c);} }catch{}finally{if(live())statusTimer=setTimeout(refreshStatus,5000);} } function drawCards(){ if(!live())return; container.querySelectorAll('[data-account-form]').forEach(form=>form.reset()); $('#bpm-list').innerHTML=connections.length?connections.map(c=>`

${esc(c.name)}

负责人 ${esc(c.owner||'未分配')}
${status(c)}
新版门户bpmn.skyworthdigital.com
${c.identity?`
登录账号 ${esc(c.identity)}
`:''}${c.checkedAt?`
上次检查 ${esc(formatDate(c.checkedAt))}
`:''}
${observations(c)}
${c.status!=='disabled'&&authorized(c)?`
${esc(accountSummary(c))}
`:c.status==='disabled'&&user.role==='admin'?``:''}
`).join(''):'

还没有 BPM 连接

请管理员添加连接并指定负责人。

'; container.querySelectorAll('[data-account]').forEach(button=>button.onclick=()=>editAccount(button)); container.querySelectorAll('[data-login]').forEach(button=>button.onclick=()=>open(button.dataset.login)); container.querySelectorAll('[data-check]').forEach(button=>button.onclick=()=>mutate(button,'check','连接状态已更新。')); container.querySelectorAll('[data-disable]').forEach(button=>button.onclick=()=>mutate(button,'disable','连接已停用,账号和会话已保留。')); container.querySelectorAll('[data-enable]').forEach(button=>button.onclick=()=>mutate(button,'enable','连接已启用,正在恢复检查与监听。')); container.querySelectorAll('[data-delete]').forEach(button=>button.onclick=()=>removeConnection(button)); } async function removeConnection(button){ if(remote||accountBusy||!live())return; const id=button.dataset.delete,connection=connections.find(c=>c.id===id); if(!connection||connection.status!=='disabled'||user.role!=='admin')return; if(!window.confirm('删除“'+connection.name+'”?该连接的托管账号和 Cookie 将一并清除,删除后无法恢复。'))return; ++statusRevision;accountControls(true); try{await api(route(id,'delete'),{});if(!live())return;++statusRevision;connections=connections.filter(c=>c.id!==id);accounts.delete(id);drawCards();feedback('连接已删除。','success');} 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){ 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}); 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(); r.opening=api(route(id,'login/open'),{}); try{ const session=await r.opening;if(!valid(r)){await release(r);return;} await loadAccount(id).catch(error=>feedback(error.message));if(!valid(r)){await release(r);return;} r.viewport=session.viewport; $('#bpm-remote').innerHTML=`

BPM 登录

${esc(session.host||'')}
${accounts.get(id)?.configured?'':''}

直接点击画面中的输入框即可输入。

正在加载登录画面…
10 分钟未操作自动关闭
`; bindInput(r);$('[data-bpm-close]').onclick=()=>{if(!r.busy)close(r);}; container.querySelectorAll('[data-target]').forEach(button=>button.onclick=async()=>{if(!valid(r)||r.busy)return;r.busy=true;controls(r);try{await r.queue;if(r.failed)throw Error('输入未送达,请重新打开登录窗口。');if(valid(r)){r.operation=api(route(id,'login/navigate'),{target:button.dataset.target});await r.operation;}}catch(error){feedback(error.message);}finally{r.busy=false;controls(r);}}); const fill=$('[data-bpm-fill-account]');if(fill)fill.onclick=async()=>{ if(!valid(r)||r.busy)return;r.busy=true;controls(r); try{await r.queue;if(!valid(r))return;if(r.failed)throw Error('输入未送达,请关闭后重新打开登录窗口。');r.operation=api(route(id,'login/fill-account'),{});const result=await r.operation;if(valid(r))feedback(result.message,result.filled?'success':'warning');} catch(error){feedback(error.message);}finally{r.busy=false;controls(r);} }; $('[data-bpm-save]').onclick=async()=>{ if(!valid(r)||r.busy)return;r.busy=true;controls(r);$('[data-bpm-close]').disabled=true;$('[data-bpm-save-state]').textContent='正在检查连接…'; 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); }catch(error){if(valid(r)){remote=null;drawCards();feedback(error.message);}} } function bindInput(r){ const image=$('[data-bpm-frame]'),input=$('[data-bpm-input]'),surface=image.closest('.bpm-screen');let composing=false,committed=''; const text=value=>{if(!value)return;for(let i=0;i{if(!valid(r)||r.busy||event.button!==0)return;event.preventDefault();const rect=image.getBoundingClientRect();if(!rect.width||!rect.height)return;enqueue(r,{type:'click',x:Math.max(0,Math.min(r.viewport.width-1,Math.round((event.clientX-rect.left)*r.viewport.width/rect.width))),y:Math.max(0,Math.min(r.viewport.height-1,Math.round((event.clientY-rect.top)*r.viewport.height/rect.height)))});input.style.left=`${Math.max(0,Math.min(surface.clientWidth-2,event.clientX-rect.left))}px`;input.style.top=`${Math.max(0,Math.min(surface.clientHeight-24,event.clientY-rect.top))}px`;input.focus({preventScroll:true});}; image.addEventListener('wheel',event=>{event.preventDefault();const multiplier=event.deltaMode===1?16:event.deltaMode===2?r.viewport.height:1;enqueue(r,{type:'scroll',deltaX:Math.max(-2000,Math.min(2000,Math.round(event.deltaX*multiplier))),deltaY:Math.max(-2000,Math.min(2000,Math.round(event.deltaY*multiplier)))});},{passive:false}); input.oncompositionstart=()=>{composing=true;committed='';}; input.oncompositionend=event=>{composing=false;committed=event.data||input.value;text(committed);input.value='';}; input.oninput=event=>{if(composing||event.isComposing)return;const value=event.data??input.value;if(committed&&value===committed){committed='';input.value='';return;}committed='';text(value);input.value='';}; input.onpaste=event=>{event.preventDefault();committed='';text(event.clipboardData?.getData('text/plain')||'');input.value='';}; const keydown=event=>{ if(event.isComposing||composing||event.keyCode===229)return; const keys=['Tab','Enter','Backspace','Delete','ArrowLeft','ArrowRight','ArrowUp','ArrowDown','Home','End','Escape']; if((event.ctrlKey||event.metaKey)&&event.key.toLowerCase()==='v')return; let key=keys.includes(event.key)?event.key:null; if((event.ctrlKey||event.metaKey)&&event.key.toLowerCase()==='a')key='Control+A'; if(key){event.preventDefault();committed='';enqueue(r,{type:'key',key});input.value='';}else if(event.ctrlKey||event.metaKey||event.altKey)event.preventDefault();else if(event.key.length===1){event.preventDefault();committed='';text(event.key);input.value='';} }; input.onkeydown=keydown;surface.onkeydown=event=>{if(event.target!==input)keydown(event);};surface.onpaste=event=>{if(event.target!==input)input.onpaste(event);}; } try{ data=await api('/workspace');if(!live())return;connections=data.connections||[]; container.innerHTML=`
${user.role==='admin'?`

添加 BPM 连接

`:''}
`; 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); }catch(error){if(live())throw error;} } return {mount,dispose}; })();