208 lines
40 KiB
JavaScript
208 lines
40 KiB
JavaScript
'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'&&route!=='/assistant/management/query'&&!/^\/assistant\/providers\/[^/]+\/models$/.test(route),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 `<span class="badge bg-${color}-lt">${label}</span>`;}
|
||
function navItem(id,symbol){return `<li class="nav-item"><a class="nav-link ${currentView===id?'active':''}" href="${window.RecordState?.href(id)||'#'+id}" data-view="${id}"><span class="nav-link-icon" aria-hidden="true">${window.AppNavigation.icon(symbol)}</span><span class="nav-link-title">${id==='order-notifications'?'订单通知管理':views[id][0]}</span></a></li>`;}
|
||
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=`<span class="badge bg-yellow-lt">发现新版本 v${esc(updateState.latest.version)}</span><button type="button" class="sidebar-release-details">查看更新</button>`;
|
||
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=`<h2 id="system-update-title" class="h3">系统更新</h2><p class="text-secondary">当前版本 v${esc(updateState.currentVersion)}</p><p role="status">${esc(message)}</p>${!loading&&release?`<h3 class="h4">${esc(release.name)}</h3>${release.publishedAt?`<p class="small text-secondary">发布时间(北京时间):${esc(formatDate(release.publishedAt))}</p>`:''}<pre class="system-update-notes">${esc(release.notes||'此版本未填写更新说明。')}</pre>${release.url?`<a class="btn btn-primary" href="${esc(release.url)}" target="_blank" rel="noopener noreferrer">前往发行页面</a>`:''}<p class="small text-secondary mt-3">由部署管理员根据发行说明安排更新。</p>`:''}<form method="dialog" class="text-end mt-3"><button class="btn" type="submit">关闭</button></form>`;
|
||
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=`<div class="page"><aside class="navbar navbar-vertical navbar-expand-lg"><div class="container-fluid"><button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#sidebar-menu" aria-controls="sidebar-menu" aria-label="展开菜单"><span class="navbar-toggler-icon"></span></button><a class="navbar-brand" href="#overview"><span class="brand-mark">单</span>订单通知中心</a><div class="collapse navbar-collapse" id="sidebar-menu"><ul class="navbar-nav pt-lg-3">${window.AppNavigation.primary.map(([id,symbol])=>navItem(id,symbol)).join('')}</ul><div class="mt-auto p-3 text-secondary small sidebar-system-update"><div class="sidebar-version" id="app-version">版本 v${esc(updateState.currentVersion)}</div><button class="btn btn-sm btn-outline-secondary sidebar-update-button" id="check-updates" type="button">检查更新</button><div class="sidebar-update-status" id="update-status" aria-live="polite">正在读取更新状态…</div></div></div></div></aside><header class="navbar d-print-none"><div class="container-xl"><div class="d-flex gap-2 flex-wrap"><a class="badge bg-secondary-lt text-decoration-none" id="automation-status" href="#notification-settings" title="正在读取服务端通知状态" aria-live="polite">通知状态待确认</a></div><div class="navbar-nav flex-row order-md-last ms-auto align-items-center gap-3"><div><div class="account-name">${esc(currentUser.username)}</div><div class="small text-secondary">${roles[currentUser.role]}</div></div><a class="btn btn-sm" href="#account">修改密码</a><button class="btn btn-sm" id="logout">退出</button></div></div></header><div class="page-wrapper"><div class="page-header d-print-none"><div class="container-xl"><div class="row g-2 align-items-center"><div class="col"><nav id="view-breadcrumb" class="mb-2" aria-label="设置导航" hidden></nav><h1 class="page-title" id="view-title"></h1><div class="text-secondary mt-2" id="view-description"></div></div><div class="col-auto ms-auto"><button class="btn" id="refresh">刷新数据</button></div></div></div></div><div class="page-body"><div class="container-xl"><nav class="nav nav-segmented settings-tabs" id="settings-tabs" aria-label="页面导航" hidden></nav><div id="content"></div></div></div></div></div>`;
|
||
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 `<div class="empty-state"><div class="avatar avatar-lg bg-blue-lt mb-3">▤</div><h3>${title}</h3><p class="text-secondary">${text}</p></div>`;}
|
||
function readOnlyNote(){return currentUser.role==='admin'?'':`<div class="alert alert-info">当前账号可查看配置。修改配置请联系管理员。</div>`;}
|
||
function jobRows(jobs){return jobs.map(job=>`<tr><td><div class="fw-medium">${esc(job.metadata?.order || '未记录订单号')}</div><div class="small text-secondary">${esc(job.metadata?.serial || '')}</div></td><td>${esc(job.metadata?.project || '—')}<div class="small text-secondary">${esc(job.metadata?.model || '')}</div></td><td>${badge(job.status)}${job.error?`<div class="small text-danger mt-1">${esc(job.error)}</div>`:''}</td><td class="text-secondary small">${formatDate(job.updatedAt)}</td><td>${job.downloadable?`<a class="btn btn-sm" href="/api/jobs/${encodeURIComponent(job.jobId)}/file">下载 PDF</a>`:'—'}</td></tr>`).join('');}
|
||
function jobTable(jobs){return `<div class="table-responsive"><table class="table table-vcenter card-table"><thead><tr><th>订单 / 通知书编号</th><th>项目 / 型号</th><th>状态</th><th>更新时间</th><th></th></tr></thead><tbody>${jobRows(jobs)}</tbody></table></div>`;}
|
||
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='<button class="btn btn-sm mb-3" id="legacy-notifications-open">查看旧通知历史(只读)</button><div id="legacy-notification-history"></div>';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=`<div class="settings-width">${readOnlyNote()}<div class="alert alert-info">收件人及类别要求在 <a href="#order-rules">分类通知规则</a> 维护。按北京时间和业务日历生成发送时段,更早历史不自动补发。</div><form id="schedule-form"><div class="card"><div class="card-header"><h2 class="card-title">每日两次通知</h2><span class="badge bg-blue-lt">北京时间</span></div><div class="card-body"><div class="row g-4"><div class="col-sm-6"><label class="form-label required" for="time-first">第一个发送时间</label><input class="form-control schedule-time" id="time-first" type="time" value="${s.times[0]}" required ${disabled}></div><div class="col-sm-6"><label class="form-label required" for="time-second">第二个发送时间</label><input class="form-control schedule-time" id="time-second" type="time" value="${s.times[1]}" required ${disabled}></div><div class="col-12"><label class="form-check form-switch"><input class="form-check-input" type="checkbox" id="weekends" ${s.weekends?'checked':''} ${disabled}><span class="form-check-label">周六、周日照常发送</span></label><div class="form-hint">关闭后仅在周一至周五发送;公司调休与暂停安排可在 <a href="#calendar">业务日历</a> 中按日期覆盖。</div></div></div></div><div class="card-footer d-flex align-items-center"><span class="text-secondary small">配置供整个团队共用</span>${currentUser.role==='admin'?'<button class="btn btn-primary ms-auto" type="submit">保存发送计划</button>':''}</div></div></form></div>`;
|
||
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='<div class="alert alert-info">模板仅维护内容。有效模板选择统一在 <a href="#order-rules">分类规则</a> 保存并发布。</div><div id="mail-templates"></div><div id="category-templates"></div>';
|
||
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='<div class="alert alert-warning"><strong>模板使用情况读取失败</strong><div>'+esc(error.message)+'</div></div>';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='<section class="card mt-3"><div class="card-header"><h2 class="card-title">有效使用情况(只读)</h2></div><div class="list-group list-group-flush">'+usage.map(r=>'<div class="list-group-item text-break"><strong>'+esc(r.name||r.categoryId)+'</strong> · '+esc(r.status==='enabled'?'已启用':r.status==='paused'?'已暂停':'尚未发布')+' · 已发布版本 '+esc(r.publishedVersion||'无')+'<div class="small mt-1">普通通知:'+esc(r.publishedVersion?templateName(r.templateId)||'使用分类规则正文':'尚未发布')+(r.legacyBinding?'(旧类别关联,只读兼容)':'')+'</div><div class="small mt-1">惠州通知:'+esc(r.huizhouEnabled?templateName(r.huizhouTemplateId)||'未选择模板':'未开启')+'</div></div>').join('')+'</div></section>';
|
||
}
|
||
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=`<div class="card"><div class="card-header"><h2 class="card-title">最近操作记录</h2><span class="text-secondary ms-auto">按时间展示最近 200 条</span></div>${audit.length?`<div class="table-responsive"><table class="table card-table"><thead><tr><th>时间(北京时间)</th><th>操作人</th><th>操作</th><th>详情</th></tr></thead><tbody>${audit.slice(0,200).map(item=>`<tr><td class="small text-secondary">${formatDate(item.at)}</td><td>${esc(item.actor)}</td><td>${esc(window.WorkspaceViews.activityText(item.action))}</td><td class="audit-detail text-secondary">${esc(item.detail)}</td></tr>`).join('')}</tbody></table></div>`:empty('暂无操作记录','保存设置或导出订单后,可在这里查看。')}</div>`;}
|
||
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='<section class="card notification-configuration"><div class="card-header"><nav id="notification-config-tabs" class="nav nav-segmented settings-tabs configuration-tabs" aria-label="通知配置导航"></nav></div><div class="card-body" id="notification-config-content"></div></section>';
|
||
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?'':`<a href="#${section}" aria-label="返回${sectionTitle}">← ${sectionTitle}</a> <span class="text-secondary"> / ${esc(views[currentView][0])}</span>`;
|
||
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='<div class="card"><div class="card-body text-secondary">正在加载…</div></div>';
|
||
|
||
try{await window.AppModules.load(currentView);if(generation!==viewGeneration)return;configureLoadedViews();}catch(error){if(isActive()){container.innerHTML=`<div class="alert alert-danger" role="alert">${esc(error.message)} <button class="btn btn-sm" type="button" data-module-retry>重试加载页面</button> <button class="btn btn-sm" type="button" data-module-reload>重新加载工作台</button></div>`;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=`<div class="alert alert-danger">${esc(error.message)}</div>`;}
|
||
}
|
||
async function authScreen() {
|
||
const setup=await api('/bootstrap/status');const initialize=setup.required && setup.canSetup;
|
||
root.innerHTML=`<div class="page page-center"><div class="container-tight py-4"><div class="text-center mb-4"><span class="avatar bg-blue text-white mb-3">单</span><h1 class="h2">订单通知中心</h1><div class="text-secondary">团队协同工作台</div></div><form class="card card-md" id="login-form"><div class="card-body"><h2 class="h2 text-center mb-4">${initialize?'创建管理员账号':'登录工作台'}</h2>${setup.required && !setup.canSetup?'<div class="alert alert-info">请先由部署机在本机地址创建管理员,再为团队开通账号。</div>':''}<div class="mb-3"><label class="form-label" for="username">账号</label><input class="form-control" id="username" autocomplete="username" required ${initialize?'minlength="3" maxlength="40" pattern="[a-zA-Z0-9_.-]+"':''}></div><div class="mb-3"><label class="form-label" for="password">密码</label><input class="form-control" type="password" id="password" autocomplete="${initialize?'new-password':'current-password'}" required ${initialize?'minlength="12" maxlength="128"':''}>${initialize?'<div class="form-hint">设置至少 12 位密码,后续可在看板中创建同事账号。</div>':''}</div><div class="text-danger mb-3" id="auth-error" role="alert"></div><div class="form-footer"><button class="btn btn-primary w-100" type="submit" ${setup.required && !setup.canSetup?'disabled':''}>${initialize?'创建账号并进入':'登录'}</button></div></div></form><p class="text-center text-secondary small mt-4 login-note">${initialize?'首次设置仅允许从部署机访问。':'使用管理员分配的账号访问。'}<br>界面基于 Tabler 开源模板</p></div></div>`;
|
||
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=`<div class="container-tight py-5"><div class="alert alert-danger">${esc(error.message)}</div></div>`;});
|