'use strict';
const root=document.querySelector('#app');
const esc=value=>String(value??'').replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));
const formatDate=value=>{const date=new Date(value);return value&&!Number.isNaN(date.getTime())?new Intl.DateTimeFormat('zh-CN',{timeZone:'Asia/Shanghai',dateStyle:'short',timeStyle:'medium',hour12:false}).format(date):'—';};
const roles={admin:'管理员',operator:'操作员',viewer:'只读成员'};
const statusMap={running:['处理中','blue'],success:['已完成','green'],error:['失败','red'],interrupted:['已中断','orange']};
let currentUser=null,settings=null,currentView='overview',overview=null,refreshTimer=null,viewGeneration=0,historyIndex=0,historyTransition=null,automationRevision=0,overviewRevision=0,updateRevision=0;
let updateState={status:'unavailable',currentVersion:'—',latest:null};
const views={tools:['工具','手工导出、文件查看与助手'],'records-pdf':['订单与导出记录','查询PDF导出结果、文件可用性与存储归档记录'],'order-notifications':['通知总览','查看当前发送时段、待发订单及接入阻塞'],'notification-execution':['订单执行','扫描真实待办,查看归档进度与受控恢复'],'notification-orders':['订单中心','查看订单分类、归档证据及所属邮件批次'],'notification-batches':['邮件批次','按发送时段检查分类汇总和冻结内容'],'notification-history':['发送记录','核对发送结果、冻结内容和人工恢复记录'],'notification-settings':['发送设置','维护发件邮箱、邮件限制与自动通知开关'],'rule-fields':['字段映射','采集BPM流程和节点,供分类规则选择匹配项'],'assistant-settings':['助手设置','配置 DSH 运行包、模型与受控操作权限'],'business-settings':['业务设置','维护Excel分类规则、收件人和BPM流程节点目录'],'system-settings':['系统设置','集中管理服务连接、运行维护和团队权限'],account:['个人账号','维护自己的登录密码与访问安全'],'order-rules':['分类通知规则','按 Excel 类别维护匹配、归档、收件人与通知正文'],health:['系统健康','查看服务守护、登录自启和各模块最近检查结果'],assistant:['DSH 助手','对话查询运行状态、分析异常与执行受控恢复'],storage:['存储服务器','配置 SMB 共享目录、检查连接与管理 PDF 归档'],notifications:['兼容业务通知','原来源映射、产业接口人与通知队列'],overview:['业务首页','订单处理、邮件窗口、业务阻塞与待核验'],calendar:['业务日历','按公司实际安排设置工作日、休息日与暂停日期'],exceptions:['异常待办','认领、转交和跟进异常'],bpm:['BPM 连接','管理连接及负责人'],supervisor:['运行监管','配置负责人、通知方式与重试上限'],records:['订单与导出记录','查询已经采集的订单,下载已完成的 PDF'],rules:['分类通知规则','按 Excel 类别维护匹配、归档、收件人与通知正文'],schedule:['发送计划','设置每日两个发送时间及周末安排'],templates:['邮件模板','管理模板及 Excel 类别关联;收件名单在分类规则维护'],mail:['邮箱管理','维护托管邮箱、模板收信与连接状态'],connections:['服务接入','查看各个环节的接入情况'],users:['团队账号','为局域网内的同事分配访问权限'],audit:['操作记录','查看配置变更和导出任务的处理记录']};
const pendingWrites=new Map(),pendingReads=new Map();
function mutationRegions(route){
if(route.startsWith('/assistant'))return ['assistant','health'];
if(route.startsWith('/storage'))return ['storage','records','home','orderRules','health'];
if(route.startsWith('/mail'))return ['mail','orderRules','home','health'];
if(route.startsWith('/connections')||route.startsWith('/bpm'))return ['bpm','records','orderRules','home','health'];
if(route.startsWith('/order-')||route==='/settings'||route==='/calendar'||route.startsWith('/exceptions'))return ['orderRules','home','records','bpm','health'];
if(route.startsWith('/jobs'))return ['records','storage','home','health'];
if(route.startsWith('/users'))return ['home','orderRules','records','health','bpm','assistant','storage','mail'];
return [];
}
// Share transport only while a read is pending; each caller owns cancellation and its result.
function readRequest(route,signal,user,scope){
if(signal?.aborted)return Promise.reject(signal.reason||new DOMException('Aborted','AbortError'));
let entry=pendingReads.get(route);
if(!entry||entry.user!==user||entry.scope!==scope){
const controller=new AbortController(),timeout=setTimeout(()=>controller.abort(),30000);
entry={user,scope,controller,subscribers:0,work:null};
entry.work=fetch('/api'+route,{signal:controller.signal,credentials:'same-origin',method:'GET',headers:{}}).then(async response=>({ok:response.ok,status:response.status,result:await response.json()})).finally(()=>{clearTimeout(timeout);if(pendingReads.get(route)===entry)pendingReads.delete(route);});
pendingReads.set(route,entry);
}
entry.subscribers++;
return new Promise((resolve,reject)=>{
let settled=false;
const finish=(work,value)=>{if(settled)return;settled=true;signal?.removeEventListener('abort',abort);entry.subscribers--;if(!entry.subscribers){if(pendingReads.get(route)===entry)pendingReads.delete(route);entry.controller.abort();}work(value);};
const abort=()=>finish(reject,signal.reason||new DOMException('Aborted','AbortError'));
signal?.addEventListener('abort',abort,{once:true});
entry.work.then(value=>finish(resolve,structuredClone(value)),error=>finish(reject,error));
});
}
async function api(route,body,{signal,ownerCheck,managedOutcome=false}={}) {
const originGeneration=viewGeneration,originUser=currentUser,originRevision=window.PageLifecycle?.revision;const originActive=()=>viewGeneration===originGeneration&¤tUser===originUser&&window.PageLifecycle?.revision===originRevision;const submission=window.PageLifecycle?.submission,hasBody=body!==undefined,write=hasBody&&route!=='/order-rules/field-mappings/propose',key=originGeneration+':'+originRevision+':'+route+':'+JSON.stringify(body);const pending=pendingWrites.get(key);if(write&&pending?.user===originUser)return pending.work;
if(write){pendingReads.clear();if(originUser)window.PageLifecycle?.invalidateRegion?.(mutationRegions(route));}
const work=(async()=>{const controller=new AbortController(),timeout=setTimeout(()=>controller.abort(),30000);const combined=signal?AbortSignal.any([signal,controller.signal]):controller.signal;
try {const response=hasBody?await fetch('/api'+route,{signal:combined,credentials:'same-origin',keepalive:route.endsWith('/login/close'),method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(body)}):await readRequest(route,combined,originUser,originGeneration+':'+originRevision);const result=hasBody?await response.json():response.result;
if(!response.ok){if(response.status===401&¤tUser&&originActive()&&(!ownerCheck||ownerCheck())){window.RecordState?.clear();currentUser=null;++viewGeneration;await window.PageLifecycle?.dispose();window.BpmLogin?.dispose();await boot();}throw Object.assign(Error(result.error||'操作失败,请核对输入。'),{status:response.status,outcome:'rejected'});}if(write&&originActive())window.PageLifecycle?.succeeded(submission);return result;
}catch(error){if(write&&originActive())window.PageLifecycle?.failed(submission);if(write&&(error.name==='AbortError'||error instanceof TypeError)){if(originActive()&&!managedOutcome)void verifyUncertainWrite(route,originActive);throw Object.assign(Error('结果待核实:请求超时或连接中断,正在查询状态;不会自动重试。'),{outcome:'uncertain'});}throw error;
}finally{clearTimeout(timeout);if(write){pendingReads.clear();if(currentUser===originUser&&originUser)window.PageLifecycle?.invalidateRegion?.(mutationRegions(route));}}})();if(write)pendingWrites.set(key,{user:originUser,work});try{return await work;}finally{if(write&&pendingWrites.get(key)?.work===work)pendingWrites.delete(key);}
}
async function verifyUncertainWrite(route,isActive){
const resource=route.startsWith('/order-rules/field-mappings/')||route==='/order-rules/field-samples/capture'?['/order-rules/fields','processes']:route.startsWith('/order-execution')?['/order-execution','tasks']:(route.startsWith('/order-rules/rules')||route==='/order-rules/restricted-test/apply')?['/order-rules/configuration','rules']:route.startsWith('/order-rules')?['/order-rules','rules']:route.startsWith('/assistant')?['/assistant','settings']:route.startsWith('/mail')?['/mail','channels']:route.startsWith('/storage')?['/storage','servers']:route==='/settings'?['/settings','schedule']:route==='/calendar'?['/workspace','calendar']:route.startsWith('/connections')?['/workspace','connections']:route.startsWith('/exceptions')?['/workspace','exceptions']:route.startsWith('/users')?['/users','users']:route==='/account/password'?['/me','user']:['/overview','stats'];
const panel=document.querySelector('#content');if(!isActive()||!panel)return;let alert=panel.querySelector('#operation-uncertain');if(!alert){alert=document.createElement('div');alert.id='operation-uncertain';alert.className='alert alert-warning';alert.setAttribute('role','alert');panel.prepend(alert);}const prefix='结果待核实:请求超时或连接中断;不会自动重试。';alert.textContent=prefix+' 正在查询状态。';
if(route==='/order-rules/field-samples/list'){alert.textContent='待办列表读取结果待确认,请使用读取按钮核实同次请求;系统不会归档、发信或办理节点。';return;}
const controller=new AbortController(),timeout=setTimeout(()=>controller.abort(),8000),unregister=window.PageLifecycle?.onDispose(()=>controller.abort());
try{const result=await api(resource[0],undefined,{signal:controller.signal,ownerCheck:isActive}),value=result?.[resource[1]],list=['processes','tasks','rules','channels','servers','connections','exceptions','users'].includes(resource[1]);if(!result||typeof result!=='object'||Array.isArray(result)||!value||(list?!Array.isArray(value):typeof value!=='object'||Array.isArray(value)))throw Error('状态响应缺少有效的所需数据');if(!isActive()||!alert.isConnected)return;const version=result.version??result.calendar?.version??result.settings?.version;const detail=version!==undefined?'(配置版本 '+version+')':Array.isArray(result.tasks)?'('+result.tasks.length+' 项任务)':'';alert.textContent=prefix+' 已查询最新状态'+detail+',提交结果仍需人工核对。';notify('已查询最新状态'+detail+',提交结果仍需人工核对;请勿重复提交。','warning');}
catch(error){if(isActive()&&alert.isConnected)alert.textContent=prefix+' 查询失败:'+(error.name==='AbortError'?'状态查询超时':error.message)+';结果仍待核实。';}
finally{clearTimeout(timeout);unregister?.();}
}
function notify(message,type='success') {
document.querySelector('#flash')?.remove();
const flash=document.createElement('div');flash.id='flash';flash.className='alert alert-'+type+' shadow';flash.setAttribute('role','alert');flash.textContent=message;document.body.append(flash);setTimeout(()=>flash.remove(),6500);
}
function badge(status){const [label,color]=statusMap[status] || ['待处理','secondary'];return `${label}`;}
function navItem(id,symbol){return `
${window.AppNavigation.icon(symbol)}${id==='order-notifications'?'订单通知管理':views[id][0]}`;}
function renderUpdateStatus(data){
updateState=data||updateState;
const version=document.querySelector('#app-version');if(version)version.textContent='版本 v'+(updateState.currentVersion||'—');
const status=document.querySelector('#update-status');if(!status)return;
status.className='sidebar-update-status';
if(updateState.status==='update-available'&&updateState.latest){
status.classList.add('is-update');status.innerHTML=`发现新版本 v${esc(updateState.latest.version)}`;
status.querySelector('button').onclick=()=>showUpdateDetails();
}else if(updateState.status==='current'){status.textContent='已是最新版本';}
else if(updateState.status==='none'){status.textContent='暂无可用发行版本';}
else if(updateState.status==='unavailable'){status.textContent='暂时无法检查更新';}
else status.textContent='更新状态未知';
}
function showUpdateDetails(loading=false){
let dialog=document.querySelector('#system-update-dialog');
if(!dialog){dialog=document.createElement('dialog');dialog.id='system-update-dialog';dialog.className='system-update-dialog';dialog.setAttribute('aria-labelledby','system-update-title');root.append(dialog);}
const release=updateState.latest;
const message=loading?'正在检查更新…':updateState.status==='update-available'&&release?'发现新版本 v'+release.version:({none:'暂无可用发行版本',current:'已是最新版本',unavailable:'暂时无法检查更新'}[updateState.status]||'更新状态未知');
dialog.innerHTML=`系统更新
当前版本 v${esc(updateState.currentVersion)}
${esc(message)}
${!loading&&release?`${esc(release.name)}
${release.publishedAt?`发布时间(北京时间):${esc(formatDate(release.publishedAt))}
`:''}${esc(release.notes||'此版本未填写更新说明。')}${release.url?`前往发行页面`:''}由部署管理员根据发行说明安排更新。
`:''}`;
if(!dialog.open)dialog.showModal();
}
async function checkSystemUpdate(isActive=()=>!!currentUser,{manual=false}={}){
const user=currentUser,request=++updateRevision,button=document.querySelector('#check-updates'),ownsResponse=()=>currentUser===user&&!!user&&button?.isConnected&&isActive();if(button)button.disabled=true;
const status=document.querySelector('#update-status');if(status&&manual)status.textContent='正在检查更新…';
if(manual)showUpdateDetails(true);
try{const result=await api('/update',undefined,{ownerCheck:ownsResponse});if(!ownsResponse()||request!==updateRevision)return;renderUpdateStatus(result);if(manual&&document.querySelector('#system-update-dialog')?.open)showUpdateDetails();}
catch(error){if(ownsResponse()&&request===updateRevision){updateState={...updateState,status:'unavailable',latest:null};renderUpdateStatus(updateState);if(manual&&document.querySelector('#system-update-dialog')?.open)showUpdateDetails();}}
finally{if(button&&request===updateRevision)button.disabled=false;}
}
function shell() {
root.innerHTML=`${esc(currentUser.username)}
${roles[currentUser.role]}
修改密码 `;
renderUpdateStatus(updateState);
document.querySelector('#logout').onclick=()=>window.PageLifecycle.guard(async()=>{++viewGeneration;await window.BpmLogin?.dispose();await api('/logout',{});window.RecordState.clear();currentUser=null;refreshTimer?.dispose();await window.PageLifecycle.dispose();await boot();});
document.querySelector('#check-updates').onclick=()=>checkSystemUpdate(()=>!!currentUser,{manual:true});
document.querySelector('#refresh').onclick=()=>window.PageLifecycle.guard(async()=>{void refreshTimer?.refresh().catch(()=>{});const region=({overview:'home','order-notifications':'home',health:'health',bpm:'bpm',assistant:'assistant',records:'records','records-pdf':'records','notification-orders':'records','notification-batches':'records','notification-execution':'records','notification-history':'records'})[currentView];if(region&&await window.PageLifecycle.refreshRegions(region))return;return window.RecordTable?.active?window.RecordTable.active.refresh():renderView();}).catch(error=>notify(error.message,'danger'));
document.querySelectorAll('[data-view]').forEach(link=>link.onclick=()=>{const menu=document.querySelector('#sidebar-menu');menu.classList.remove('show');if(menu.classList.contains('collapsing'))menu.addEventListener('shown.bs.collapse',()=>menu.classList.remove('show'),{once:true});document.querySelector('.navbar-toggler').setAttribute('aria-expanded','false');});
}
function empty(title,text){return ``;}
function readOnlyNote(){return currentUser.role==='admin'?'':`当前账号可查看配置。修改配置请联系管理员。
`;}
function jobRows(jobs){return jobs.map(job=>`${esc(job.metadata?.order || '未记录订单号')} ${esc(job.metadata?.serial || '')} | ${esc(job.metadata?.project || '—')} ${esc(job.metadata?.model || '')} | ${badge(job.status)}${job.error?` ${esc(job.error)} `:''} | ${formatDate(job.updatedAt)} | ${job.downloadable?`下载 PDF`:'—'} |
`).join('');}
function jobTable(jobs){return `| 订单 / 通知书编号 | 项目 / 型号 | 状态 | 更新时间 | |
${jobRows(jobs)}
`;}
async function viewOverview(container,isActive=()=>true) {
const revision=++overviewRevision,ownsResponse=()=>revision===overviewRevision&&isActive();
try{
return await window.OrderNotificationViews.render(container,ownsResponse,'workbench');
}catch(error){if(ownsResponse())throw error;}
}
function recordHistory(container,isActive){const history=document.createElement('section');history.className='mt-3';history.innerHTML='';container.append(history);history.querySelector('button').onclick=async event=>{const button=event.currentTarget;button.disabled=true;try{await window.NotificationViews.history(history.querySelector('#legacy-notification-history'),isActive);}catch(error){if(isActive())notify(error.message,'danger');}finally{if(button.isConnected)button.disabled=false;}};}
async function viewRecords(container,isActive=()=>true){await window.OrderViews.records(container,isActive);if(isActive())recordHistory(container,isActive);}
async function viewPdfRecords(container,isActive=()=>true){await window.PdfRecordViews.records(container,isActive);if(isActive())recordHistory(container,isActive);}
async function viewSchedule(container,isActive=()=>true) {
const loaded=await api('/settings');if(!isActive())return;let draft=loaded;const s=draft.schedule;const disabled=currentUser.role!=='admin'?'disabled':'';
container.innerHTML=`${readOnlyNote()}
收件人及类别要求在
分类通知规则 维护。按北京时间和业务日历生成发送时段,更早历史不自动补发。
`;
document.querySelector('#schedule-form').onsubmit=async event=>{event.preventDefault();try{const updated=await api('/settings',{version:draft.version,schedule:{...draft.schedule,times:[document.querySelector('#time-first').value,document.querySelector('#time-second').value],timezone:'Asia/Shanghai',weekends:document.querySelector('#weekends').checked}});if(!isActive())return;draft=updated;notify('发送计划已保存。');}catch(error){if(isActive())notify(error.message,'danger');}};
}
async function viewTemplates(container,isActive=()=>true){
container.innerHTML='模板仅维护内容。有效模板选择统一在
分类规则 保存并发布。
';
const usageRead=api('/order-rules/catalog').then(data=>({data}),error=>({error}));
const mail=await window.MailViews.templates(container.querySelector('#mail-templates'),isActive);if(!isActive())return;
let data;try{const result=await usageRead;if(result.error)throw result.error;data=result.data;}catch(error){if(isActive())container.querySelector('#category-templates').innerHTML='模板使用情况读取失败'+esc(error.message)+'
';return;}if(!isActive())return;
const usage=data.templateUsage||[];
if(usage.some(r=>r.legacyBinding)){
try{const legacy=await api('/mail/templates/categories');if(!isActive())return;for(const row of usage)if(row.legacyBinding)row.templateId=legacy.bindings.find(b=>b.categoryId===row.categoryId)?.templateId||'';}
catch{for(const row of usage)if(row.legacyBinding)row.templateId='旧类别关联读取失败,请核实';}
}
const templateName=id=>mail?.templates?.find(t=>t.id===id)?.subject||id;
container.querySelector('#category-templates').innerHTML=''+usage.map(r=>'
'+esc(r.name||r.categoryId)+' · '+esc(r.status==='enabled'?'已启用':r.status==='paused'?'已暂停':'尚未发布')+' · 已发布版本 '+esc(r.publishedVersion||'无')+'
普通通知:'+esc(r.publishedVersion?templateName(r.templateId)||'使用分类规则正文':'尚未发布')+(r.legacyBinding?'(旧类别关联,只读兼容)':'')+'
惠州通知:'+esc(r.huizhouEnabled?templateName(r.huizhouTemplateId)||'未选择模板':'未开启')+'
').join('')+'
';
}
async function viewAudit(container,isActive=()=>true){const [legacy,workspace]=await Promise.all([api('/audit'),api('/workspace')]);if(!isActive())return;const audit=[...legacy.audit,...workspace.audit].sort((a,b)=>new Date(b.at)-new Date(a.at));container.innerHTML=`${audit.length?`
| 时间(北京时间) | 操作人 | 操作 | 详情 |
${audit.slice(0,200).map(item=>`| ${formatDate(item.at)} | ${esc(item.actor)} | ${esc(window.WorkspaceViews.activityText(item.action))} | ${esc(item.detail)} |
`).join('')}
`:empty('暂无操作记录','保存设置或导出订单后,可在这里查看。')}
`;}
function viewRules(container,isActive){return window.OrderRuleViews.render(container,isActive,'rules');}
async function updateAutomationStatus(isActive,{signal}={}){
const request=++automationRevision,node=document.querySelector('#automation-status');if(!node||!isActive())return;
const apply=(label,color,detail)=>{if(!isActive()||request!==automationRevision||!node.isConnected)return;node.textContent=label;node.className='badge bg-'+color+'-lt text-decoration-none';node.title=detail;};
try{
const data=await api('/order-rules/status',undefined,{signal,ownerCheck:isActive});if(!isActive())return;
if(typeof data?.settings?.enabled!=='boolean')throw Error('服务端未返回有效通知开关');
const missing=Object.entries({liveTodo:'实时待办接入',pdfExport:'PDF 导出',automaticArchive:'自动归档'}).filter(([key])=>data.capabilities?.[key]!==true).map(([,label])=>label);
if(!data.settings.enabled)apply('自动通知已暂停','secondary','自动发信保持暂停;请完成类别字段、目录、邮箱与预览核验。'+(missing.length?' 待检查:'+missing.join('、'):' 点击查看发送设置。'));
else if(missing.length)apply('自动通知待核验','yellow','部分接入能力尚待核验,请到通知总览查看实际订单和阻塞详情。');
else apply('自动通知已启用','green','通知开关已启用;实际任务、类别及批次仍按各自检查结果执行。');
}catch(error){if(signal?.aborted)throw error;apply('通知状态待确认','yellow',error.message+';请刷新重试。');throw error;}
}
function configurationHost(container){
container.innerHTML='';
window.AppNavigation.renderConfiguration(container.querySelector('#notification-config-tabs'),{id:currentView,views,esc});
return container.querySelector('#notification-config-content');
}
async function renderView() {
if(!currentUser)return;
const routeId=window.RecordState.route(location.hash)||'overview',resolved=window.AppNavigation.resolve(routeId);
if(routeId!==resolved&&['notification-orders','notification-batches'].includes(resolved)){
const params=new URLSearchParams(location.hash.split('?')[1]||'');if(routeId==='notification-history'&&!params.has('scope'))params.set('scope','all');
history.replaceState(history.state,'',window.RecordState.serialize(resolved,Object.fromEntries(params)));
}
if(window.RecordState.isRecord(location.hash)&¤tView===resolved&&window.RecordTable?.active?.view===resolved){historyIndex=Number.isInteger(history.state?.appIndex)?history.state.appIndex:historyIndex;void refreshTimer?.run().catch(()=>{});return window.RecordTable.active.navigate();}
const wasRecord=['records','records-pdf'].includes(currentView);
const generation=++viewGeneration;const isActive=()=>generation===viewGeneration && !!currentUser;
await window.PageLifecycle?.dispose();
await window.BpmLogin?.dispose();if(!isActive())return;
const requested=resolved;currentView=Object.hasOwn(views,requested)?requested:'overview';
if(currentView==='users' && currentUser.role!=='admin')currentView='overview';
historyIndex=Number.isInteger(history.state?.appIndex)?history.state.appIndex:historyIndex;history.replaceState({...history.state,appIndex:historyIndex},'',window.RecordState.isRecord(location.hash)?location.hash:'#'+currentView+(['exceptions'].includes(currentView)&&location.hash.includes('?')?location.hash.slice(location.hash.indexOf('?')):''));
const section=window.AppNavigation.sectionFor(currentView);
window.AppNavigation.renderTabs(document.querySelector('#settings-tabs'),{id:currentView,user:currentUser,views,esc});
document.querySelectorAll('[data-view]').forEach(link=>{const active=link.dataset.view===(section||currentView);link.classList.toggle('active',active);if(active)link.setAttribute('aria-current','page');else link.removeAttribute('aria-current');});
const sectionTitle=views[section]?.[0];
const breadcrumb=document.querySelector('#view-breadcrumb');breadcrumb.hidden=!section||section===currentView||section==='records';breadcrumb.innerHTML=breadcrumb.hidden?'':`← ${sectionTitle} / ${esc(views[currentView][0])}`;
document.querySelector('#view-title').textContent=views[currentView][0];document.querySelector('#view-description').textContent=views[currentView][1];
const container=document.querySelector('#content');if(!(wasRecord&&['records','records-pdf'].includes(currentView)))container.innerHTML='';
try{await window.AppModules.load(currentView);if(!isActive())return;configureLoadedViews();}catch(error){if(isActive()){container.innerHTML=`${esc(error.message)}
`;container.querySelector('[data-module-retry]').onclick=()=>renderView();container.querySelector('[data-module-reload]').onclick=()=>location.reload();}return;}
const notificationSections={'order-notifications':'workbench','notification-execution':'execution','notification-orders':'orders','notification-batches':'pending','notification-history':'history','notification-settings':'settings'};
const fn={'rule-fields':(host,active)=>window.OrderRuleViews.render(host,active,'fields'),...Object.fromEntries(Object.entries(notificationSections).map(([route,section])=>[route,(host,active)=>window.OrderNotificationViews.render(host,active,section)])),'assistant-settings':window.AssistantViews?.settings,account:window.AccountViews?.account,'order-rules':window.OrderRuleViews?.render,health:window.HealthViews?.render,assistant:window.AssistantViews?.render,storage:window.StorageViews?.render,overview:viewOverview,calendar:window.WorkspaceViews?.calendar,exceptions:window.WorkspaceViews?.exceptions,bpm:window.WorkspaceViews?.bpm,records:viewRecords,'records-pdf':viewPdfRecords,schedule:viewSchedule,templates:viewTemplates,mail:window.MailViews?.accounts,users:window.AccountViews?.users,audit:viewAudit,rules:viewRules}[currentView];
void refreshTimer?.run().catch(()=>{});
try{window.PageLifecycle?.attach(container);const host=window.AppNavigation.isConfiguration(currentView)?configurationHost(container):container;await fn(host,isActive);if(isActive())window.PageLifecycle?.bind();}catch(error){if(isActive())container.innerHTML=`${esc(error.message)}
`;}
}
async function authScreen() {
const setup=await api('/bootstrap/status');const initialize=setup.required && setup.canSetup;
root.innerHTML=`${initialize?'首次设置仅允许从部署机访问。':'使用管理员分配的账号访问。'}
界面基于 Tabler 开源模板
`;
document.querySelector('#login-form').onsubmit=async event=>{event.preventDefault();const button=event.target.querySelector('button[type="submit"]');button.disabled=true;try{const result=await api(initialize?'/bootstrap':'/login',{username:document.querySelector('#username').value,password:document.querySelector('#password').value});currentUser=result.user;enter();}catch(error){document.querySelector('#auth-error').textContent=error.message;}finally{button.disabled=false;}};
}
async function passwordChanged(actorId){if(currentUser&¤tUser.id!==actorId)return false;currentUser=null;++viewGeneration;refreshTimer?.dispose();await window.PageLifecycle?.dispose();await window.BpmLogin?.dispose().catch(()=>{});await boot();return true;}
function configureLoadedViews(){window.PdfRecordViews?.configure({api,esc,formatDate,notify,user:currentUser});window.AccountViews?.configure({api,esc,formatDate,notify,user:currentUser,onPasswordChanged:passwordChanged});window.OrderRuleViews?.configure({api,esc,formatDate,notify,user:currentUser});window.OrderNotificationViews?.configure({api,esc,formatDate,notify,user:currentUser});window.HealthViews?.configure({api,esc,formatDate,user:currentUser});window.AssistantViews?.configure({api,esc,formatDate,notify,user:currentUser});window.StorageViews?.configure({api,esc,formatDate,notify,user:currentUser});window.NotificationViews?.configure({api,esc,formatDate,notify,user:currentUser});window.OrderViews?.configure({api,esc,formatDate,notify,user:currentUser});window.MailViews?.configure({api,esc,formatDate,notify,user:currentUser});window.WorkspaceViews?.configure({api,esc,formatDate,notify,user:currentUser});}
function enter(){window.PageLifecycle.configureRegions({read:(signal,region)=>api('/refresh/revisions?regions='+encodeURIComponent(region),undefined,{signal}),user:()=>currentUser});window.RecordState.configure(currentUser,({hash,push})=>{if(push&&location.hash!==hash)history.pushState({appIndex:++historyIndex},'',hash);else history.replaceState({...history.state,appIndex:historyIndex},'',hash);});configureLoadedViews();shell();refreshTimer?.dispose();const statusUser=currentUser;refreshTimer=window.PageLifecycle.regionPoll('orderRules',{refresh:signal=>updateAutomationStatus(()=>currentUser===statusUser,{signal}),onError:error=>{const node=document.querySelector('#automation-status');if(node&¤tUser===statusUser){node.textContent='通知状态待确认';node.className='badge bg-yellow-lt text-decoration-none';node.title=error.message+';请刷新重试。';}}},15000,{isActive:()=>!!currentUser&¤tUser===statusUser,owned:false});renderView();void checkSystemUpdate(()=>!!currentUser);}
async function boot(){try{currentUser=(await api('/me')).user;enter();}catch{await authScreen();}}
window.addEventListener('page-operation-error',event=>notify(event.detail.message,'danger'));
window.addEventListener('pagehide',()=>{window.BpmLogin?.dispose({unload:true});});
document.addEventListener('click',event=>{const link=event.target.closest('a[href^="#"]');if(!currentUser||!link||event.ctrlKey||event.metaKey)return;event.preventDefault();if(location.hash===link.hash&&window.RecordState.isRecord(link.hash))return;window.PageLifecycle.guard(()=>{if(location.hash!==link.hash){history.pushState({appIndex:++historyIndex},'',link.hash);}return renderView();});});
window.addEventListener('hashchange',()=>{
if(!currentUser)return;
if(historyTransition?.kind==='restore'){const target=historyTransition.target;historyTransition=null;window.PageLifecycle.guard(()=>{historyTransition={kind:'approved'};history.go(target-historyIndex);});return;}
if(historyTransition?.kind==='approved'){historyTransition=null;renderView();return;}
const target=Number.isInteger(history.state?.appIndex)?history.state.appIndex:historyIndex+1;
if(!Number.isInteger(history.state?.appIndex))history.replaceState({appIndex:target},'',location.hash);
if(!window.PageLifecycle.dirty()){renderView();return;}
if(target!==historyIndex){historyTransition={kind:'restore',target};history.go(historyIndex-target);return;}
const destination=location.hash;history.replaceState({appIndex:historyIndex},'','#'+currentView);window.PageLifecycle.guard(()=>{history.replaceState({appIndex:historyIndex},'',destination);return renderView();});
});
boot().catch(error=>{root.innerHTML=``;});