fix(web): address lifecycle and execution review findings

This commit is contained in:
abaishu0730 committed 2026-10-19 13:09:18 +08:00
1 parent 5c7ce76f5d
commit 3037f7f7ac
6 files changed
+56 -19

No files matched your search

+14
View File
@@ -0,0 +1,14 @@
'use strict';
const {test}=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs/promises'),os=require('node:os'),path=require('node:path');
const {startTestDashboard,login}=require('../fixtures/dashboard-runtime.cjs'),{loadPlaywright,browserOptions}=require('../../src/platform/browser.cjs');
async function fixture(t,hash='schedule'){const dir=await fs.mkdtemp(path.join(os.tmpdir(),'closure-review-')),runtime=await startTestDashboard({stateDir:dir}),browser=await loadPlaywright().chromium.launch(browserOptions());t.after(async()=>{await browser.close();await runtime.close();await fs.rm(dir,{recursive:true,force:true});});const page=await browser.newPage({viewport:{width:1440,height:1000}});page.setDefaultTimeout(6000);await page.goto('http://127.0.0.1:'+runtime.server.address().port+'/#'+hash);await login(page);return {page,runtime};}
test('a successful delayed save commits only submitted inputs and later edits remain dirty',{timeout:45000},async t=>{const {page}=await fixture(t);await page.locator('#schedule-form').waitFor();let release,arrive;const arrived=new Promise(r=>arrive=r),gate=new Promise(r=>release=r);await page.route('**/api/settings',async route=>{if(route.request().method()==='GET')return route.continue();const response=await route.fetch();arrive();await gate;return route.fulfill({response});});await page.locator('#time-first').fill('09:11');await page.getByRole('button',{name:'保存发送计划',exact:true}).click();await arrived;await page.locator('#time-first').fill('09:12');release();await page.getByText('发送计划已保存。',{exact:true}).waitFor();assert.equal(await page.evaluate(()=>PageLifecycle.dirty()),true);await page.getByRole('link',{name:'业务日历',exact:true}).first().click();await page.getByRole('dialog',{name:'未保存的修改'}).waitFor();assert.equal(await page.locator('#time-first').inputValue(),'09:12');});
for(const destination of ['internal','route'])test('Save and Continue preserves currentTarget for rule settings: '+destination,{timeout:45000},async t=>{const {page}=await fixture(t,'order-rules');await page.getByRole('button',{name:'设置',exact:true}).click();await page.locator('#order-rule-settings').waitFor();const input=page.locator('#order-rule-settings [name=maxSize]');await input.fill('12');const posts=[];await page.route('**/api/order-rules/settings',async route=>{posts.push(route.request().postDataJSON());return route.continue();});if(destination==='internal')await page.getByRole('button',{name:'工作台',exact:true}).click();else await page.getByRole('link',{name:'发送计划',exact:true}).first().click();await page.getByRole('button',{name:'保存并继续',exact:true}).click();if(destination==='internal')await page.getByRole('heading',{name:'本时段范围',exact:true}).waitFor();else await page.locator('#schedule-form').waitFor();assert.equal(posts.length,1);assert.equal(posts[0].maxMessageBytes,12582912);});
async function mailFixture(page){const drafts=['t1','t2'].map((id,i)=>({id,version:1,status:'pending',subject:'模板'+(i+1),scope:'',channelId:'mail1',sender:'fixture@example.test',attachmentCount:0,attachments:[],text:'正文'}));await page.route('**/api/mail',route=>route.fulfill({json:{channels:[],templates:drafts,receipts:[],sends:[]}}));await page.route('**/api/mail/templates/categories',route=>route.fulfill({json:{categories:[],bindings:[]}}));await page.route(/\/api\/mail\/templates\/t[12]$/,route=>route.fulfill({json:drafts.find(d=>route.request().url().endsWith('/'+d.id))}));await page.route('**/api/mail/templates/*/preview',route=>route.fulfill({contentType:'text/html',body:'<p>正文</p>'}));return drafts;}
test('switching a dirty template supports stay discard and save before selecting another',{timeout:45000},async t=>{const {page}=await fixture(t);const drafts=await mailFixture(page);let saved;await page.route('**/api/mail/templates/t1/confirm',route=>{saved=route.request().postDataJSON();drafts[0].status='active';drafts[0].subject=saved.subject;return route.fulfill({json:{ok:true}});});await page.getByRole('link',{name:'邮件模板',exact:true}).click();await page.locator('[data-template=t1]').click();await page.locator('#template-subject').fill('未保存模板一');await page.locator('[data-template=t2]').click();await page.getByRole('button',{name:'留在此页',exact:true}).click();assert.equal(await page.locator('#template-subject').inputValue(),'未保存模板一');await page.locator('[data-template=t2]').click();await page.getByRole('button',{name:'放弃并继续',exact:true}).click();await page.waitForFunction(()=>document.querySelector('#template-subject')?.value==='模板2');await page.locator('[data-template=t1]').click();await page.locator('#template-subject').fill('保存模板一');await page.locator('[data-template=t2]').click();await page.getByRole('button',{name:'保存并继续',exact:true}).click();await page.waitForFunction(()=>document.querySelector('#template-subject')?.value==='模板2');assert.equal(saved.subject,'保存模板一');});
test('failed uncertain-result readback stays uncertain and never claims state was queried',{timeout:45000},async t=>{const {page}=await fixture(t);await page.locator('#schedule-form').waitFor();let posts=0,reads=0;await page.route('**/api/settings',route=>{if(route.request().method()==='POST'){posts++;return route.abort('timedout');}reads++;return route.fulfill({status:503,json:{error:'State unavailable'}});});await page.locator('#time-first').fill('10:01');await page.getByRole('button',{name:'保存发送计划',exact:true}).click();await page.waitForFunction(()=>document.querySelector('#operation-uncertain')?.textContent.includes('查询失败'));const text=await page.locator('#operation-uncertain').innerText();assert.match(text,/结果待核实/);assert.doesNotMatch(text,/已查询最新状态/);assert.equal(posts,1);assert.equal(reads,1);});
test('delayed readback cannot notify after leaving its originating page',{timeout:45000},async t=>{const {page}=await fixture(t);await page.locator('#schedule-form').waitFor();let release,arrive;const gate=new Promise(r=>release=r),arrived=new Promise(r=>arrive=r);await page.route('**/api/settings',async route=>{if(route.request().method()==='POST')return route.abort('timedout');arrive();await gate;return route.fulfill({json:{version:2,schedule:{times:['09:00','17:00']}}});});await page.locator('#time-first').fill('10:02');await page.getByRole('button',{name:'保存发送计划',exact:true}).click();await arrived;await page.getByRole('link',{name:'系统设置',exact:true}).click();await page.getByRole('button',{name:'放弃并继续',exact:true}).click();await page.getByRole('heading',{name:'BPM 连接',exact:true}).first().waitFor();await page.evaluate(()=>document.querySelector('#flash')?.remove());release();await page.waitForTimeout(250);assert.equal(await page.locator('#flash').count(),0);assert.equal(await page.locator('#operation-uncertain').count(),0);});
test('execution refreshes after actions and on visible refresh while retaining other task notes',{timeout:45000},async t=>{const {page}=await fixture(t,'order-rules');let tasks=[{id:'t1',connectionId:'c1',status:'failed',version:1,error:'失败一'},{id:'t2',connectionId:'c1',status:'failed',version:1,error:'失败二'}],gets=0;const retried=[];await page.route('**/api/order-execution',route=>{gets++;return route.fulfill({json:{tasks,capabilities:{},fields:{samples:[],adapters:[]}}});});await page.route('**/api/order-execution/tasks/t1/retry',route=>{retried.push(route.request().postDataJSON());tasks[0]={...tasks[0],version:2,error:'再次失败'};return route.fulfill({json:{ok:true}});});await page.route('**/api/order-execution/scan',route=>{tasks.push({id:'new1',status:'archived',version:1,title:'新扫描任务'});return route.fulfill({json:{ok:true}});});await page.getByRole('button',{name:'订单执行',exact:true}).click();await page.locator('[data-execution-retry=t2] textarea').fill('保留另一任务的处理依据');await page.locator('[data-execution-retry=t1] textarea').fill('核实恢复后再次尝试');await page.locator('[data-execution-retry=t1] button').click();await page.getByText('再次失败',{exact:true}).waitFor();assert.equal(await page.locator('[data-execution-retry=t2] textarea').inputValue(),'保留另一任务的处理依据');await page.locator('[data-execution-retry=t1] textarea').fill('核实恢复后第二次尝试');await page.locator('[data-execution-retry=t1] button').click();await page.getByText('重试请求已提交,请核对任务状态。',{exact:true}).waitFor();assert.deepEqual(retried.map(r=>r.version),[1,2]);await page.getByLabel('扫描连接',{exact:true}).selectOption('c1');await page.getByRole('button',{name:'扫描待办',exact:true}).click();await page.locator('[data-execution-task=new1]').waitFor();assert.match(await page.locator('[data-execution-task=new1]').innerText(),/新扫描任务/);tasks[0]={...tasks[0],version:3,status:'archived',error:''};await page.getByRole('button',{name:'刷新时段与状态',exact:true}).click();await page.waitForFunction(()=>!document.querySelector('[data-execution-retry=t1]'));assert.equal(await page.locator('[data-execution-retry=t2] textarea').inputValue(),'保留另一任务的处理依据');assert.ok(gets>=5);});
test('rerendering rule saves lock editable fields until the saved response has replaced the form',{timeout:45000},async t=>{const {page}=await fixture(t,'order-rules');await page.getByRole('button',{name:'通知规则',exact:true}).click();let release,arrive;const gate=new Promise(r=>release=r),arrived=new Promise(r=>arrive=r);await page.route('**/api/order-rules/rules',async route=>{const response=await route.fetch();arrive();await gate;return route.fulfill({response});});await page.getByLabel('规则名称',{exact:true}).fill('提交中的草稿');await page.getByRole('button',{name:'保存草稿',exact:true}).click();await arrived;assert.equal(await page.getByLabel('规则名称',{exact:true}).isDisabled(),true);release();await page.getByText('规则草稿已保存。',{exact:true}).waitFor();assert.equal(await page.getByLabel('规则名称',{exact:true}).isDisabled(),false);assert.equal(await page.getByLabel('规则名称',{exact:true}).inputValue(),'提交中的草稿');assert.equal(await page.evaluate(()=>PageLifecycle.dirty()),false);});
test('invalid readback payload is rejected even when HTTP succeeds',{timeout:45000},async t=>{const {page}=await fixture(t);await page.locator('#schedule-form').waitFor();await page.route('**/api/settings',route=>route.request().method()==='POST'?route.abort('timedout'):route.fulfill({json:{schedule:'not a schedule'}}));await page.locator('#time-first').fill('10:03');await page.getByRole('button',{name:'保存发送计划',exact:true}).click();await page.waitForFunction(()=>document.querySelector('#operation-uncertain')?.textContent.includes('查询失败'));assert.doesNotMatch(await page.locator('#operation-uncertain').innerText(),/已查询最新状态/);});
test('uncertain calendar write reads its workspace calendar rather than overview',{timeout:45000},async t=>{const {page}=await fixture(t,'calendar');await page.locator('#day-note').waitFor();let reads=0;await page.route('**/api/calendar',route=>route.abort('timedout'));await page.route('**/api/workspace',route=>{reads++;return route.fulfill({json:{calendar:{version:8,overrides:[]}}});});await page.locator('#day-note').fill('隔离测试日历安排');await page.getByRole('button',{name:'应用到此日期',exact:true}).click();await page.getByRole('button',{name:'保存日历',exact:true}).click();await page.waitForFunction(()=>document.querySelector('#operation-uncertain')?.textContent.includes('配置版本 8'));assert.equal(reads,1);});
+13 -4
View File
@@ -7,15 +7,24 @@ const statusMap={running:['处理中','blue'],success:['已完成','green'],erro
let currentUser=null,settings=null,currentView='overview',overview=null,refreshTimer=null,viewGeneration=0,historyIndex=0,historyTransition=null;
const views={'assistant-settings':['助手设置','配置 ZCode 运行包、模型与受控操作权限'],'business-settings':['业务设置','集中维护订单分类、发送时间和收件规则'],'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}={}) {
const submission=window.PageLifecycle?.submission,write=body!==undefined,key=route+':'+JSON.stringify(body);if(write&&pendingWrites.has(key))return pendingWrites.get(key);
async function api(route,body,{signal,ownerCheck}={}) {
const originGeneration=viewGeneration,originUser=currentUser,originRevision=window.PageLifecycle?.revision;const originActive=()=>viewGeneration===originGeneration&&currentUser===originUser&&window.PageLifecycle?.revision===originRevision;const submission=window.PageLifecycle?.submission,write=body!==undefined,key=route+':'+JSON.stringify(body);if(write&&pendingWrites.has(key))return pendingWrites.get(key);
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:write?'POST':'GET',headers:write?{'Content-Type':'application/json'}:{},body:write?JSON.stringify(body):undefined});const result=await response.json();
if(!response.ok){if(response.status===401&&currentUser){currentUser=null;++viewGeneration;await window.PageLifecycle?.dispose();window.BpmLogin?.dispose();await boot();}throw Error(result.error||'操作失败,请核对输入。');}if(write)window.PageLifecycle?.succeeded(submission);return result;
}catch(error){if(write)window.PageLifecycle?.failed(submission);if(write&&(error.name==='AbortError'||error instanceof TypeError)){const readRoute=route.startsWith('/order-execution')?'/order-execution':route.startsWith('/order-rules')?'/order-rules':route.startsWith('/assistant')?'/assistant':route.startsWith('/mail')?'/mail':route==='/settings'?'/settings':'/overview';const panel=document.querySelector('#content');let uncertain=panel?.querySelector('#operation-uncertain');if(panel&&!uncertain){uncertain=document.createElement('div');uncertain.id='operation-uncertain';uncertain.className='alert alert-warning';uncertain.setAttribute('role','alert');panel.prepend(uncertain);}if(uncertain)uncertain.textContent='结果待核实:请求超时或连接中断,正在查询状态;不会自动重试。';fetch('/api'+readRoute,{credentials:'same-origin'}).then(r=>r.json()).then(()=>{if(uncertain?.isConnected)uncertain.textContent+=' 已查询最新状态,请核对操作结果;请勿重复提交。';notify('已查询最新状态,请核对操作结果;请勿重复提交。','warning');}).catch(()=>{});throw Error('结果待核实:请求超时或连接中断,正在查询状态;不会自动重试。');}throw error;
if(!response.ok){if(response.status===401&&currentUser&&(!ownerCheck||ownerCheck())){currentUser=null;++viewGeneration;await window.PageLifecycle?.dispose();window.BpmLogin?.dispose();await boot();}throw Error(result.error||'操作失败,请核对输入。');}if(write)window.PageLifecycle?.succeeded(submission);return result;
}catch(error){if(write)window.PageLifecycle?.failed(submission);if(write&&(error.name==='AbortError'||error instanceof TypeError)){if(originActive())void verifyUncertainWrite(route,originActive);throw Error('结果待核实:请求超时或连接中断,正在查询状态;不会自动重试。');}throw error;
}finally{clearTimeout(timeout);}})();if(write)pendingWrites.set(key,work);try{return await work;}finally{if(write)pendingWrites.delete(key);}
}
async function verifyUncertainWrite(route,isActive){
const resource=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+' 正在查询状态。';
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=['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);
+1 -1
View File
@@ -20,7 +20,7 @@ window.MailViews=(()=>{
async function templates(container,isActive=()=>true){
const data=await api('/mail');if(!isActive())return;const admin=user.role==='admin';let filter='pending',detailRevision=0;
container.innerHTML=`<div class="card mb-3"><div class="card-header flex-wrap gap-3"><h2 class="card-title">发信模板</h2><div class="ms-auto"><a class="btn btn-sm" href="#mail">邮箱管理</a></div></div><div class="card-body"><p class="mb-2">向托管邮箱发送 <code>[模板][产品线]发信标题</code>,新版本将在这里等待确认。未填写产品线时作为默认模板。</p><div class="small text-secondary">可用变量:<code>{{产品线}}</code>、<code>{{订单号}}</code>、<code>{{日期}}</code>、<code>{{订单列表}}</code></div></div><div class="card-footer"><label class="form-label" for="template-filter">模板状态</label><select class="form-select" id="template-filter">${Object.entries(labels).map(([v,label])=>`<option value="${v}">${label}(${data.templates.filter(t=>t.status===v).length})</option>`).join('')}</select></div><div id="mail-template-list"></div></div><div id="mail-template-detail"></div>`;
const draw=()=>{const items=data.templates.filter(t=>t.status===filter);container.querySelector('#mail-template-list').innerHTML=items.length?`<div class="table-responsive"><table class="table card-table"><thead><tr><th>标题 / 范围</th><th>来源</th><th></th></tr></thead><tbody>${items.map(t=>`<tr><td><div class="fw-medium">${esc(t.subject)}</div><div class="small text-secondary mt-1">${esc(t.scope||'默认模板')} · ${stateBadge(t)} · ${t.attachmentCount} 个附件</div></td><td class="small">${esc(data.channels.find(c=>c.id===t.channelId)?.name||'旧模板草稿')}<div class="text-secondary">${esc(t.sender)}<br>${formatDate(t.createdAt)}</div></td><td><button class="btn btn-sm" data-template="${t.id}">${t.status==='pending'?'预览并确认':'查看版本'}</button></td></tr>`).join('')}</tbody></table></div>`:'<div class="card-body text-center text-secondary py-4">暂无'+labels[filter]+'模板</div>';container.querySelectorAll('[data-template]').forEach(b=>b.onclick=()=>action(b,()=>detail(b.dataset.template)));};draw();container.querySelector('#template-filter').onchange=event=>{filter=event.target.value;draw();};
const draw=()=>{const items=data.templates.filter(t=>t.status===filter);container.querySelector('#mail-template-list').innerHTML=items.length?`<div class="table-responsive"><table class="table card-table"><thead><tr><th>标题 / 范围</th><th>来源</th><th></th></tr></thead><tbody>${items.map(t=>`<tr><td><div class="fw-medium">${esc(t.subject)}</div><div class="small text-secondary mt-1">${esc(t.scope||'默认模板')} · ${stateBadge(t)} · ${t.attachmentCount} 个附件</div></td><td class="small">${esc(data.channels.find(c=>c.id===t.channelId)?.name||'旧模板草稿')}<div class="text-secondary">${esc(t.sender)}<br>${formatDate(t.createdAt)}</div></td><td><button class="btn btn-sm" data-template="${t.id}">${t.status==='pending'?'预览并确认':'查看版本'}</button></td></tr>`).join('')}</tbody></table></div>`:'<div class="card-body text-center text-secondary py-4">暂无'+labels[filter]+'模板</div>';container.querySelectorAll('[data-template]').forEach(b=>b.onclick=()=>window.PageLifecycle.guard(()=>action(b,()=>detail(b.dataset.template))));};draw();container.querySelector('#template-filter').onchange=event=>{filter=event.target.value;draw();};
async function detail(id){const revision=++detailRevision,t=await api('/mail/templates/'+id);if(!isActive()||revision!==detailRevision)return;const pending=t.status==='pending',host=container.querySelector('#mail-template-detail');host.innerHTML=`<form class="card mb-3" id="template-review"><div class="card-header gap-2"><h3 class="card-title">模板预览</h3>${stateBadge(t)}<button type="button" class="btn btn-sm ms-auto" id="template-close">关闭</button></div><div class="card-body"><div class="small text-secondary mb-3">来源:${esc(t.sender)} · ${formatDate(t.date||t.createdAt)}<br>原主题:${esc(t.sourceSubject||t.subject)}</div>${t.notes?.length?`<div class="alert alert-info">${t.notes.map(esc).join('<br>')}</div>`:''}${t.channelId==='legacy'?`<div class="mb-3"><label class="form-label" for="legacy-channel">使用邮箱</label><select class="form-select" id="legacy-channel" required><option value="">请选择托管邮箱</option>${data.channels.filter(c=>!c.readOnly).map(c=>`<option value="${c.id}">${esc(c.name)}</option>`).join('')}</select></div>`:''}<div class="row g-3 mb-3"><div class="col-md-8"><label class="form-label" for="template-subject">发信标题</label><input class="form-control" id="template-subject" value="${esc(t.subject)}" required maxlength="300" ${pending&&admin?'':'disabled'}></div><div class="col-md-4"><label class="form-label" for="template-scope">适用产品线</label><input class="form-control" id="template-scope" value="${esc(t.scope)}" maxlength="80" placeholder="留空为默认模板" ${pending&&admin?'':'disabled'}></div></div><iframe class="mail-preview" title="邮件正文预览" sandbox src="/api/mail/templates/${id}/preview"></iframe>${pending&&admin?`<div class="mt-3"><label class="form-check"><input class="form-check-input" id="template-use-text" type="checkbox"><span class="form-check-label">改用纯文本正文</span></label><div id="template-text-editor" hidden><label class="form-label mt-2" for="template-text">纯文本正文</label><textarea class="form-control" id="template-text" rows="7" maxlength="20000">${esc(t.text)}</textarea><div class="form-hint">确认后使用这里的正文,附件继续保留。</div></div></div>`:''}<div class="mt-3"><h4 class="mb-2">附件(${t.attachments.length})</h4><ul class="list-unstyled mb-0">${t.attachments.map((a,i)=>`<li class="mb-1">${admin?`<a href="/api/mail/templates/${id}/attachments/${i}" download>${esc(a.filename)}</a>`:esc(a.filename)} <span class="text-secondary small">${Math.ceil(a.size/1024)} KB${a.inline?' · 内嵌图片':''}</span></li>`).join('')||'<li class="text-secondary small">无附件</li>'}</ul></div><div class="text-danger mt-3" id="template-error" role="alert"></div></div><div class="card-footer btn-list">${admin&&t.channelId!=='legacy'?`<a class="btn btn-sm" href="/api/mail/templates/${id}/source" download>下载原邮件</a>`:''}${pending&&admin?'<button type="button" class="btn btn-outline-secondary ms-auto" id="template-reject">忽略此模板</button><button type="submit" class="btn btn-primary">确认生效</button>':''}${t.status==='active'&&admin?'<button type="button" class="btn btn-primary ms-auto" id="template-test">发送测试到本邮箱</button>':''}</div></form>`;host.scrollIntoView({block:'start',behavior:'smooth'});host.querySelector('#template-close').onclick=()=>{detailRevision++;host.replaceChildren();};
if(pending&&admin){host.querySelector('#template-use-text').onchange=e=>host.querySelector('#template-text-editor').hidden=!e.target.checked;host.querySelector('#template-review').onsubmit=async e=>{e.preventDefault();const button=e.submitter;button.disabled=true;try{const useText=host.querySelector('#template-use-text').checked;await api(`/mail/templates/${id}/confirm`,{version:t.version,subject:host.querySelector('#template-subject').value,scope:host.querySelector('#template-scope').value,useText,...(useText?{text:host.querySelector('#template-text').value}:{}),...(t.channelId==='legacy'?{channelId:host.querySelector('#legacy-channel').value}:{})});if(isActive()){await templates(container,isActive);notify('模板已确认生效。');}}catch(error){if(isActive())host.querySelector('#template-error').textContent=error.message;}finally{if(button.isConnected)button.disabled=false;}};host.querySelector('#template-reject').onclick=e=>action(e.target,async()=>{await api(`/mail/templates/${id}/reject`,{version:t.version});if(isActive()){await templates(container,isActive);notify('模板已忽略。');}});}
host.querySelector('#template-test')?.addEventListener('click',e=>{const c=data.channels.find(c=>c.id===t.channelId);if(!confirm(`使用此模板发送一封测试邮件到 ${c.email}?`))return;action(e.target,async()=>{await api(`/mail/channels/${t.channelId}/test`,{templateId:id});notify('测试邮件已提交至邮件服务器。');});});
+3 -3
View File
@@ -7,10 +7,10 @@ window.PageLifecycle=(()=>{
function bind(){if(!host)return;for(const form of host.querySelectorAll('form')){
if(forms.has(form)||form.dataset.lifecycle==='custom'||form.id==='assistant-compose'||!form.onsubmit||!form.querySelector('button[type="submit"]'))continue;
const state={baseline:snapshot(form),busy:false,failed:false,sensitive:/password|^user-form$/.test(form.id)||!!form.querySelector('input[type="password"]')||form.matches('[data-rule-resend],[data-rule-resolve],[data-rule-recheck],[data-execution-retry],#execution-scan,#exception-action,#storage-archive-form,#storage-folder-form'),save:null};forms.set(form,state);const original=form.onsubmit;
form.onsubmit=async event=>{event.preventDefault();if(state.busy)return;state.busy=true;state.failed=false;state.committed=false;form.setAttribute('aria-busy','true');const previous=activeSubmission;activeSubmission=state;
try{await original.call(form,event);if(!state.failed&&state.committed)state.baseline=snapshot(form);}catch(error){state.failed=true;window.dispatchEvent(new CustomEvent('page-operation-error',{detail:error}));}finally{state.busy=false;form.removeAttribute('aria-busy');activeSubmission=previous;}
form.onsubmit=async event=>{event.preventDefault();if(state.busy)return;state.busy=true;state.failed=false;state.committed=false;state.submitted=snapshot(form);form.setAttribute('aria-busy','true');const previous=activeSubmission;activeSubmission=state;
const locked=[...form.querySelectorAll('input,select,textarea')].filter(field=>!field.disabled);let restore=false;try{const work=original.call(form,event);if(form.id!=='schedule-form'&&work&&typeof work.then==='function'){restore=true;for(const field of locked)field.disabled=true;}await work;}catch(error){state.failed=true;window.dispatchEvent(new CustomEvent('page-operation-error',{detail:error}));}finally{if(restore&&form.isConnected)for(const field of locked)field.disabled=false;if(!state.failed&&state.committed)state.baseline=state.sensitive?snapshot(form):state.submitted;state.busy=false;form.removeAttribute('aria-busy');activeSubmission=previous;}
};
state.save=async()=>{if(!form.reportValidity())return false;const button=form.querySelector('button[type="submit"]');if(button.disabled||state.busy)return false;await form.onsubmit({preventDefault(){},target:form,submitter:button});return !state.failed&&(!form.isConnected||state.committed&&snapshot(form)===state.baseline);};
state.save=async()=>{if(!form.reportValidity())return false;const button=form.querySelector('button[type="submit"]');if(button.disabled||state.busy)return false;await form.onsubmit({preventDefault(){},target:form,currentTarget:form,submitter:button});return !state.failed&&(!form.isConnected||state.committed&&snapshot(form)===state.baseline);};
}
for(const [form] of forms)if(!form.isConnected)forms.delete(form);
}
+21 -7
View File
@@ -4,13 +4,27 @@
const key=(form,body)=>{const signature=JSON.stringify(body);if(form.dataset.requestSignature!==signature){form.dataset.requestSignature=signature;form.dataset.requestKey=window.PageLifecycle.requestKey();}return form.dataset.requestKey;};
async function execution(host,{api,esc,formatDate,user,isActive,feedback}){
const data=await api('/order-execution');if(!isActive())return;
const operator=user.role!=='viewer',admin=user.role==='admin';
const workspace=await api('/workspace').catch(()=>({connections:[]}));if(!isActive())return;
const connections=(workspace.connections||[]).filter(c=>admin||c.owner===user.username),tasks=data.tasks||[];for(const t of tasks)if(admin&&t.connectionId&&!connections.some(c=>c.id===t.connectionId))connections.push({id:t.connectionId,name:t.connectionId});
const run=async(form,route,body,message)=>{const button=form.querySelector('button[type=submit]');if(button.disabled)return;button.disabled=true;try{await api(route,body);if(isActive()){form.reset();delete form.dataset.requestKey;delete form.dataset.requestSignature;feedback(message);}}catch(error){if(isActive())feedback(error.message,'danger');}finally{if(button.isConnected)button.disabled=false;}};
host.innerHTML=`<div class="card mb-3"><div class="card-header"><h3 class="card-title">订单执行与恢复</h3></div><div class="card-body"><p>扫描只采集待办并建立执行任务;BPM 节点由人工办理。受阻原因与重试结果以服务器任务状态为准。</p><div class="small mb-3">${Object.entries(data.capabilities||{}).map(([name,value])=>`${esc(({liveTodo:'实时待办',pdfExport:'PDF 导出',automaticArchive:'自动归档'})[name]||name)}:${esc(typeof value==='boolean'?(value?'已就绪':'未就绪'):value?.reason||value?.message||'待核实')}`).join(' · ')}</div>${operator?`<form id="execution-scan"><label for="execution-connection" class="form-label">扫描连接</label><div class="d-flex gap-2"><select class="form-select" id="execution-connection" name="connectionId" required><option value="">请选择有权访问的连接</option>${connections.map(c=>`<option value="${esc(c.id)}">${esc(c.name||c.id)}</option>`).join('')}</select><button class="btn btn-primary" type="submit">扫描待办</button></div></form>`:'<p class="text-secondary">只读账号可查看任务,不能扫描或重试。</p>'}</div></div><div class="card"><div class="card-header"><h3 class="card-title">持久执行任务</h3></div><div class="table-responsive"><table class="table card-table"><thead><tr><th>任务</th><th>状态 / 原因</th><th>操作</th></tr></thead><tbody>${tasks.map(t=>`<tr><td class="text-break">${esc(t.orderNo||t.title||t.id)}<div class="small text-secondary">${esc(t.processName||'')} · v${esc(t.version)}<br>${formatDate(t.updatedAt||t.createdAt)}</div></td><td>${esc(({failed:'失败',blocked:'受阻',unknown:'结果待核实',archived:'已归档',sent:'已提交邮件服务器'})[t.status]||t.status)}<div class="small text-danger">${esc(t.error||t.reason||t.blockedReason||'')}</div></td><td>${admin&&t.status==='failed'?`<form data-execution-retry="${esc(t.id)}"><label class="form-label" for="retry-${esc(t.id)}">任务重试依据</label><textarea class="form-control mb-2" id="retry-${esc(t.id)}" name="note" required minlength="5" maxlength="2000"></textarea><button class="btn btn-sm" type="submit">重试失败任务</button></form>`:t.status==='unknown'?'须先人工核验结果':'—'}</td></tr>`).join('')||'<tr><td colspan="3" class="text-secondary">暂无任务。先检查实际接入能力与连接权限。</td></tr>'}</tbody></table></div></div>`;
const scan=host.querySelector('#execution-scan');if(scan)scan.onsubmit=e=>{e.preventDefault();return run(scan,'/order-execution/scan',{connectionId:scan.elements.connectionId.value,idempotencyKey:key(scan,{connectionId:scan.elements.connectionId.value})},'扫描请求已提交,请核对任务状态。');};
host.querySelectorAll('[data-execution-retry]').forEach(form=>form.onsubmit=e=>{e.preventDefault();const task=tasks.find(t=>t.id===form.dataset.executionRetry);return run(form,'/order-execution/tasks/'+encodeURIComponent(task.id)+'/retry',{version:task.version,idempotencyKey:key(form,{version:task.version,note:form.elements.note.value}),note:form.elements.note.value},'重试请求已提交,请核对任务状态。');});
const operator=user.role!=='viewer',admin=user.role==='admin',workspace=await api('/workspace').catch(()=>({connections:[]}));if(!isActive())return;
let tasks=data.tasks||[],refreshRevision=0;
const connections=(workspace.connections||[]).filter(c=>admin||c.owner===user.username);for(const task of tasks)if(admin&&task.connectionId&&!connections.some(c=>c.id===task.connectionId))connections.push({id:task.connectionId,name:task.connectionId});
const summary=task=>`${esc(task.orderNo||task.title||task.id)}<div class="small text-secondary">${esc(task.processName||'')} · v${esc(task.version)}<br>${formatDate(task.updatedAt||task.createdAt)}</div>`;
const state=task=>`${esc(({failed:'失败',blocked:'受阻',unknown:'结果待核实',archived:'已归档',sent:'已提交邮件服务器'})[task.status]||task.status)}<div class="small text-danger">${esc(task.error||task.reason||task.blockedReason||'')}</div>`;
const retry=task=>`<form data-execution-retry="${esc(task.id)}"><label class="form-label" for="retry-${esc(task.id)}">任务重试依据</label><textarea class="form-control mb-2" id="retry-${esc(task.id)}" name="note" required minlength="5" maxlength="2000"></textarea><button class="btn btn-sm" type="submit">重试失败任务</button></form>`;
host.innerHTML=`<div class="card mb-3"><div class="card-header"><h3 class="card-title">订单执行与恢复</h3></div><div class="card-body"><p>扫描只采集待办并建立执行任务;BPM 节点由人工办理。受阻原因与重试结果以服务器任务状态为准。</p><div class="small mb-3">${Object.entries(data.capabilities||{}).map(([name,value])=>`${esc(({liveTodo:'实时待办',pdfExport:'PDF 导出',automaticArchive:'自动归档'})[name]||name)}:${esc(typeof value==='boolean'?(value?'已就绪':'未就绪'):value?.reason||value?.message||'待核实')}`).join(' · ')}</div>${operator?`<form id="execution-scan"><label for="execution-connection" class="form-label">扫描连接</label><div class="d-flex gap-2"><select class="form-select" id="execution-connection" name="connectionId" required><option value="">请选择有权访问的连接</option>${connections.map(c=>`<option value="${esc(c.id)}">${esc(c.name||c.id)}</option>`).join('')}</select><button class="btn btn-primary" type="submit">扫描待办</button></div></form>`:'<p class="text-secondary">只读账号可查看任务,不能扫描或重试。</p>'}</div></div><div class="card"><div class="card-header"><h3 class="card-title">持久执行任务</h3></div><div class="table-responsive"><table class="table card-table"><thead><tr><th>任务</th><th>状态 / 原因</th><th>操作</th></tr></thead><tbody id="execution-tasks"></tbody></table></div></div>`;
async function refresh(){const revision=++refreshRevision,fresh=await api('/order-execution');if(!isActive()||revision!==refreshRevision)return;tasks=fresh.tasks||[];drawTasks();}
const run=async(form,route,body,message)=>{const button=form.querySelector('button[type=submit]');if(button.disabled)return;button.disabled=true;try{await api(route,body);if(!isActive())return;form.reset();delete form.dataset.requestKey;delete form.dataset.requestSignature;await refresh();if(isActive())feedback(message);}catch(error){if(isActive())feedback(error.message,'danger');}finally{if(button.isConnected)button.disabled=false;}};
function bindRetry(form){form.onsubmit=event=>{event.preventDefault();const task=tasks.find(task=>task.id===form.dataset.executionRetry);if(!task||task.status!=='failed')return;return run(form,'/order-execution/tasks/'+encodeURIComponent(task.id)+'/retry',{version:task.version,idempotencyKey:key(form,{version:task.version,note:form.elements.note.value}),note:form.elements.note.value},'重试请求已提交,请核对任务状态。');};}
function drawTasks(){if(!isActive())return;const body=host.querySelector('#execution-tasks');body.querySelector('[data-execution-empty]')?.remove();const existing=new Map([...body.querySelectorAll('[data-execution-task]')].map(row=>[row.dataset.executionTask,row]));
for(const task of tasks){let row=existing.get(task.id);if(!row){row=document.createElement('tr');row.dataset.executionTask=task.id;row.innerHTML='<td data-task-summary></td><td data-task-state></td><td data-task-action></td>';body.append(row);}existing.delete(task.id);row.querySelector('[data-task-summary]').innerHTML=summary(task);row.querySelector('[data-task-state]').innerHTML=state(task);const action=row.querySelector('[data-task-action]'),form=action.querySelector('form');
if(admin&&task.status==='failed'){if(!form||!form.querySelector('button[type=submit]')){action.innerHTML=retry(task);bindRetry(action.querySelector('form'));}}
else if(form?.elements.note?.value.trim()){form.querySelector('button')?.remove();form.onsubmit=e=>e.preventDefault();let note=form.querySelector('[data-state-changed]');if(!note){note=document.createElement('div');note.dataset.stateChanged='1';note.className='small text-secondary';form.append(note);}note.textContent='任务状态已更新,原输入保留;当前不可重试。';}
else action.textContent=task.status==='unknown'?'须先人工核验结果':'—';
}
for(const row of existing.values()){if(row.querySelector('textarea')?.value.trim()){row.querySelector('[data-task-state]').textContent='任务已不在当前列表;原输入保留。';row.querySelector('button')?.remove();}else row.remove();}
if(!body.children.length)body.innerHTML='<tr data-execution-empty><td colspan="3" class="text-secondary">暂无任务。先检查实际接入能力与连接权限。</td></tr>';
}
const scan=host.querySelector('#execution-scan');if(scan)scan.onsubmit=event=>{event.preventDefault();return run(scan,'/order-execution/scan',{connectionId:scan.elements.connectionId.value,idempotencyKey:key(scan,{connectionId:scan.elements.connectionId.value})},'扫描请求已提交,请核对任务状态。');};
drawTasks();return {refresh};
}
async function fields(host,{api,esc,user,isActive,feedback}){
const data=await api('/order-rules/fields');if(!isActive())return;const admin=user.role==='admin',samples=data.samples||[];
+4 -4
View File
@@ -13,7 +13,7 @@
async function render(container,isActive=()=>true){
const [snapshot,mail]=await Promise.all([api('/order-rules'),api('/mail').catch(()=>({channels:[]}))]);if(!isActive())return;
const data={rules:[],adapters:[],orders:[],batches:[],audit:[],settings:{},capabilities:{},...snapshot},admin=user.role==='admin',operator=user.role!=='viewer';
let tab='workbench',selectedId=data.rules[0]?.id,dirty=false,refreshing=false,timer,panelRevision=0,tabRevision=0;
let tab='workbench',selectedId=data.rules[0]?.id,dirty=false,refreshing=false,timer,panelRevision=0,tabRevision=0,executionController=null;
container.innerHTML=`<div class="order-rules"><div id="order-rule-state" class="alert alert-${data.settings.enabled?'success':'info'}">分类通知${data.settings.enabled?'已启用':'自动执行已暂停'}。按 Excel 类别汇总,本时段内同类别订单合并一封,更早历史不补发;通知与更改单独归类,BPM 节点由人工办理。</div><div class="order-rule-tabs mb-3" role="group" aria-label="规则中心页面">${Object.entries(tabs).map(([id,label])=>`<button class="btn ${id===tab?'btn-primary':''}" type="button" data-rule-tab="${id}">${label}</button>`).join('')}</div><div class="d-flex flex-wrap gap-2 align-items-center mb-3"><span class="small text-secondary" id="order-rule-updated" aria-live="polite">时段与运行状态每 15 秒刷新</span><button class="btn btn-sm ms-auto" type="button" id="order-rule-refresh">刷新时段与状态</button></div><div id="order-rules-feedback" role="alert" aria-live="polite"></div><div id="order-rules-panel"></div></div>`;
const panel=container.querySelector('#order-rules-panel');
const feedback=(message,type='success')=>{if(!isActive())return;const node=container.querySelector('#order-rules-feedback');node.textContent=message;node.className='alert alert-'+type;};
@@ -21,7 +21,7 @@
async function reload(){const fresh=await api('/order-rules');if(!isActive())return false;Object.assign(data,fresh);syncState();dirty=false;draw();return true;}
function syncState(){const node=container.querySelector('#order-rule-state');node.className='alert alert-'+(data.settings.enabled?'success':'info');node.textContent='分类通知'+(data.settings.enabled?'已启用':'自动执行已暂停')+'。按 Excel 类别汇总,本时段内同类别订单合并一封,更早历史不补发;通知与更改单独归类,BPM 节点由人工办理。';}
function keepInputs(){return window.PageLifecycle?.dirty()||['fields','execution'].includes(tab)||dirty||tab==='rules'||tab==='settings'||[...panel.querySelectorAll('textarea')].some(input=>input.value.trim());}
async function refreshStatus(){if(refreshing)return;refreshing=true;try{const fresh=await api('/order-rules');if(!isActive())return;Object.assign(data,fresh);syncState();container.querySelector('#order-rule-updated').textContent='时段与状态更新于 '+formatDate(new Date().toISOString());if(!keepInputs())draw();}finally{refreshing=false;}}
async function refreshStatus(){if(refreshing)return;refreshing=true;try{const fresh=await api('/order-rules');if(!isActive())return;Object.assign(data,fresh);syncState();container.querySelector('#order-rule-updated').textContent='时段与状态更新于 '+formatDate(new Date().toISOString());if(tab==='execution'&&executionController)await executionController.refresh();if(!keepInputs())draw();}finally{refreshing=false;}}
function ordersTable(orders){return table(['订单 / 类别','状态与原因','接收时间'],orders.map(o=>`<tr><td><strong>${esc(o.orderNo||o.event?.orderNo||'订单号未提供')}</strong><div class="small text-secondary">${esc(data.rules.find(r=>r.categoryId===o.categoryId)?.name||o.categoryId||'未分类')}</div><details class="mt-2"><summary class="small">查看订单信息</summary><div class="small order-rule-record mt-2">流程:${esc(o.processName||o.event?.processName||'—')}<br>节点:${esc(o.nodeName||o.event?.nodeName||'—')}<br>流程实例:${esc(o.instanceId||o.event?.instanceId||'—')}<br>任务:${esc(o.taskId||o.event?.taskId||'—')}<br>来源版本:${esc(o.revision||o.event?.revision||'—')}<br>规则版本:${esc(o.ruleVersion??'—')}<br>数量:${esc(o.quantity??o.event?.quantity??'—')}<br>${esc(o.brief||o.event?.brief||'')}</div></details></td><td>${status(o.status)}${o.error||o.reason?`<div class="small text-danger mt-2">${esc(o.error||o.reason)}</div>`:''}${admin&&!o.batchId&&['pending','blocked'].includes(o.status)?`<details class="mt-3"><summary class="small">按当前发布规则重新核对</summary><form data-rule-recheck="${esc(o.id)}" class="mt-2"><p class="small text-secondary">重新匹配会清除原归档证据,需重新校验和归档;更早历史仍不补发。</p><label class="form-label" for="rule-recheck-${esc(o.id)}">重新核对依据</label><textarea class="form-control mb-2" id="rule-recheck-${esc(o.id)}" name="note" rows="2" required minlength="5" maxlength="2000"></textarea><button class="btn btn-sm" type="submit">重新核对此订单</button></form></details>`:''}</td><td class="small text-secondary">${formatDate(o.receivedAt||o.event?.receivedAt||o.createdAt)}</td></tr>`),'暂无订单记录。样本预览不会创建订单。');}
function batchesTable(batches,pending){return table(['类别 / 主题','订单与收件人','状态'],batches.map(b=>`<tr><td><strong>${esc(b.subject||b.categoryId)}</strong><div class="small text-secondary mt-1">${esc(b.categoryId)} · ${formatDate(b.createdAt)}</div><details class="mt-2"><summary class="small">查看冻结内容</summary><div class="order-rule-record small mt-2">业务时段:${formatDate(b.windowStart)} 至 ${formatDate(b.windowEnd||b.cutoff)}<br>收件人:${esc(list(b.to))}<br>抄送:${esc(list(b.cc))}<br>附件:${esc((b.attachments||[]).map(a=>a.name||a.filename).join('、')||'无')}<pre class="notification-brief mt-2">${esc(b.text||'')}</pre></div></details></td><td class="small">${esc(list(b.orderNos||b.orderIds))}<div class="text-secondary mt-2">${esc(list(b.to))}</div></td><td>${status(b.status)}${b.error?`<div class="small text-danger mt-2">${esc(b.error)}</div>`:''}${b.status==='failed'&&admin?`<form class="mt-3" data-rule-resend="${esc(b.id)}"><p class="small text-secondary">人工补发沿用原冻结内容和收件人。</p><label class="form-label" for="resend-${esc(b.id)}">人工补发依据</label><textarea class="form-control mb-2" id="resend-${esc(b.id)}" name="note" required minlength="5" maxlength="2000"></textarea><button class="btn btn-sm" type="submit">人工补发此失败批次</button></form>`:''}${b.status==='unknown'&&admin?`<form class="mt-3" data-rule-resolve="${esc(b.id)}"><label class="form-label" for="rule-resolution-${esc(b.id)}">人工核验结论</label><select class="form-select mb-2" id="rule-resolution-${esc(b.id)}" name="resolution"><option value="sent">已核实邮件服务器接受</option><option value="retry">已核实未发送,允许重试</option></select><label class="form-label" for="rule-resolution-note-${esc(b.id)}">核验依据</label><textarea class="form-control mb-2" id="rule-resolution-note-${esc(b.id)}" name="note" rows="2" required minlength="5" maxlength="2000"></textarea><button class="btn btn-sm" type="submit">保存核验结论</button></form>`:''}</td></tr>`),pending?'暂无待发批次':'暂无发送记录');}
function windowInfo(){const w=data.window;return w&&Number.isFinite(Date.parse(w.start))&&Number.isFinite(Date.parse(w.end))&&Date.parse(w.start)<Date.parse(w.end)?w:null;}
@@ -53,8 +53,8 @@
if(admin)panel.querySelector('form').onsubmit=e=>{e.preventDefault();const form=e.currentTarget;return action(e.submitter,async()=>{await api('/order-rules/settings',{version:config.version,channelId:form.elements.channelId.value,maxMessageBytes:Math.round(Number(form.elements.maxSize.value)*1048576),enabled:canEnable&&form.elements.enabled.checked});if(await reload())feedback('分类通知设置已保存。');});};
}
function draw(){
if(!isActive())return;const drawnRevision=++panelRevision,drawnTab=tab;
if(tab==='workbench')drawWorkbench();else if(tab==='rules')drawRules();else if(tab==='settings')drawSettings();else if(tab==='execution'||tab==='fields'){panel.innerHTML=empty('正在加载…');window.OrderExecutionViews[tab](panel,{api,esc,formatDate,user,isActive:()=>isActive()&&panelRevision===drawnRevision&&tab===drawnTab,feedback}).catch(error=>{if(!isActive()||panelRevision!==drawnRevision)return;panel.innerHTML=empty('数据加载未完成,请刷新重试。');feedback(error.message,'danger');});}
if(!isActive())return;const drawnRevision=++panelRevision,drawnTab=tab;executionController=null;
if(tab==='workbench')drawWorkbench();else if(tab==='rules')drawRules();else if(tab==='settings')drawSettings();else if(tab==='execution'||tab==='fields'){panel.innerHTML=empty('正在加载…');window.OrderExecutionViews[tab](panel,{api,esc,formatDate,user,isActive:()=>isActive()&&panelRevision===drawnRevision&&tab===drawnTab,feedback}).then(controller=>{if(isActive()&&panelRevision===drawnRevision)executionController=controller;}).catch(error=>{if(!isActive()||panelRevision!==drawnRevision)return;panel.innerHTML=empty('数据加载未完成,请刷新重试。');feedback(error.message,'danger');});}
else if(tab==='orders')panel.innerHTML=`<div class="card"><div class="card-header"><h3 class="card-title">订单记录 · ${data.orders.length}</h3></div>${ordersTable(data.orders)}</div>`;
else if(tab==='pending')panel.innerHTML=`${windowCard(true)}${windowOrders()}<div class="card"><div class="card-header"><h3 class="card-title">本时段待发批次</h3></div>${batchesTable(data.batches.filter(b=>{const w=windowInfo();return w&&['prepared','sending','unknown','failed'].includes(b.status)&&Date.parse(b.windowStart)===Date.parse(w.start)&&Date.parse(b.windowEnd||b.cutoff)===Date.parse(w.end);}),true)}</div>`;
else if(tab==='history')panel.innerHTML=`<div class="alert alert-info">“已提交邮件服务器”表示 SMTP 接受,不代表最终送达。结果不明的批次须人工核实。</div><div class="card mb-3"><div class="card-header"><h3 class="card-title">发送记录</h3></div>${batchesTable(data.batches.filter(b=>['sent','cancelled','failed','unknown'].includes(b.status)),false)}</div><div class="card"><div class="card-header"><h3 class="card-title">规则与执行操作记录</h3></div>${table(['时间','操作人 / 操作','说明'],data.audit.map(a=>`<tr><td class="small">${formatDate(a.at||a.createdAt)}</td><td>${esc(a.actor?.username||a.actor||'系统')}<div class="small text-secondary">${esc(a.action)}</div></td><td class="small text-break">${esc(typeof a.detail==='object'?JSON.stringify(a.detail):a.detail||a.note||'')}</td></tr>`),'暂无操作记录')}</div>`;