'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; const views={'records-pdf':['订单与导出记录','查询PDF导出结果、文件可用性与存储归档记录'],'order-notifications':['通知总览','查看当前发送时段、待发订单及接入阻塞'],'notification-execution':['订单执行','扫描真实待办,查看归档进度与受控恢复'],'notification-orders':['通知订单','查看订单分类、归档证据及所属邮件批次'],'notification-batches':['待发批次','按发送时段检查分类汇总和冻结内容'],'notification-history':['发送记录','核对发送结果、冻结内容和人工恢复记录'],'notification-settings':['发送设置','维护发件邮箱、邮件限制与自动通知开关'],'rule-fields':['字段映射','从真实 BPM 样本选择字段,按表单版本保存对应关系'],'assistant-settings':['助手设置','配置 ZCode 运行包、模型与受控操作权限'],'business-settings':['业务设置','维护 Excel 分类规则、收件人和真实字段对应'],'system-settings':['系统设置','集中管理服务连接、运行维护和团队权限'],account:['个人账号','维护自己的登录密码与访问安全'],'order-rules':['分类通知规则','按 Excel 类别维护匹配、归档、收件人与通知正文'],health:['系统健康','查看服务守护、登录自启和各模块最近检查结果'],assistant:['ZCode 助手','对话查询运行状态、分析异常与执行受控恢复'],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(); 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; 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=await fetch('/api'+route,{signal:combined,credentials:'same-origin',keepalive:route.endsWith('/login/close'),method:hasBody?'POST':'GET',headers:hasBody?{'Content-Type':'application/json'}:{},body:hasBody?JSON.stringify(body):undefined});const result=await response.json(); if(!response.ok){if(response.status===401&¤tUser&&originActive()&&(!ownerCheck||ownerCheck())){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)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')?['/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 ``;} function shell() { root.innerHTML=`
`; document.querySelector('#logout').onclick=()=>window.PageLifecycle.guard(async()=>{++viewGeneration;await window.BpmLogin?.dispose();await api('/logout',{});currentUser=null;clearInterval(refreshTimer);await window.PageLifecycle.dispose();await boot();}); document.querySelector('#refresh').onclick=()=>window.PageLifecycle.guard(()=>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 `
▤

${title}

${text}

`;} 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{ if(window.WorkspaceViews)return await window.WorkspaceViews.overview(container,ownsResponse); await api('/workspace');if(!ownsResponse())return; container.innerHTML=empty('工作台模块未加载','请刷新页面后重试。'); }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=`
${readOnlyNote()}
收件人与抄送名单统一在 分类规则 维护。类别关联仅使用显式保存的映射,不按名称推断。
`; await window.MailViews.templates(container.querySelector('#mail-templates'),isActive);if(!isActive())return; let catalog,mail;try{[catalog,mail]=await Promise.all([api('/mail/templates/categories'),api('/mail')]);}catch(error){if(isActive())container.querySelector('#category-templates').innerHTML='
类别关联暂不可用:'+esc(error.message)+'
';return;}if(!isActive())return; const host=container.querySelector('#category-templates');host.innerHTML=`

类别模板关联

${catalog.categories.map(c=>{const binding=catalog.bindings.find(b=>b.categoryId===c.id);return `
${currentUser.role==='admin'?'':''}
来源:${binding?.templateId?'已保存类别映射':'未关联'}
`;}).join('')}
`; host.querySelectorAll('form').forEach(form=>form.onsubmit=async event=>{event.preventDefault();const binding=catalog.bindings.find(b=>b.categoryId===form.dataset.category);try{const result=await api('/mail/templates/categories',{categoryId:form.dataset.category,templateId:form.elements.templateId.value,version:binding?.version??0});if(!isActive())return;catalog.bindings=catalog.bindings.filter(b=>b.categoryId!==result.categoryId).concat(result);form.querySelector('[role="alert"]').textContent='';await window.PageLifecycle.afterSave(async()=>{const fresh=await api('/mail/templates/categories');if(isActive())catalog.bindings=fresh.bindings;},'类别模板关联已保存。',notify,isActive);}catch(error){if(isActive())form.querySelector('[role="alert"]').textContent=error.message;}}); } 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=`

最近操作记录

按时间展示最近 200 条
${audit.length?`
${audit.slice(0,200).map(item=>``).join('')}
时间(北京时间)操作人操作详情
${formatDate(item.at)}${esc(item.actor)}${esc(window.WorkspaceViews.activityText(item.action))}${esc(item.detail)}
`:empty('暂无操作记录','保存设置或导出订单后,可在这里查看。')}
`;} function viewRules(container,isActive){return window.OrderRuleViews.render(container,isActive,'rules');} async function updateAutomationStatus(isActive){ 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',undefined,{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','未通过实际检查:'+missing.join('、')+'。点击查看发送设置。'); else apply('自动通知已启用','green','通知开关已启用;实际任务、类别及批次仍按各自检查结果执行。'); }catch(error){apply('通知状态待确认','yellow',error.message+';请刷新重试。');} } 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 generation=++viewGeneration;const isActive=()=>generation===viewGeneration && !!currentUser; await window.PageLifecycle?.dispose(); await window.BpmLogin?.dispose();if(!isActive())return; const requested=window.AppNavigation.resolve(location.hash.slice(1) || 'overview');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({appIndex:historyIndex},'','#'+currentView); 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=section==='order-notifications'?'订单通知管理':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');container.innerHTML='
正在加载…
'; 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 updateAutomationStatus(isActive); 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?'创建管理员账号':'登录工作台'}

${setup.required && !setup.canSetup?'
请先由部署机在本机地址创建管理员,再为团队开通账号。
':''}
${initialize?'
设置至少 12 位密码,后续可在看板中创建同事账号。
':''}
`; 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;clearInterval(refreshTimer);await window.PageLifecycle?.dispose();await window.BpmLogin?.dispose().catch(()=>{});await boot();return true;} function enter(){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});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});shell();renderView();clearInterval(refreshTimer);refreshTimer=setInterval(()=>{if(currentUser&&!document.hidden){const statusGeneration=viewGeneration,statusUser=currentUser;void updateAutomationStatus(()=>statusGeneration===viewGeneration&&statusUser===currentUser);}if(currentUser && currentView==='overview' && !document.hidden){const generation=viewGeneration;viewOverview(document.querySelector('#content'),()=>generation===viewGeneration && !!currentUser && currentView==='overview').catch(()=>{});}},15000);} async function boot(){try{const setup=await api('/bootstrap/status');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();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=`
${esc(error.message)}
`;});