diff --git a/tests/app/web-closure-review-ui.test.cjs b/tests/app/web-closure-review-ui.test.cjs new file mode 100644 index 0000000..75e9bed --- /dev/null +++ b/tests/app/web-closure-review-ui.test.cjs @@ -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:'
正文
'}));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);}); diff --git a/web/app.js b/web/app.js index 516906f..bd7c2c9 100644 --- a/web/app.js +++ b/web/app.js @@ -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&¤tUser===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&¤tUser){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&¤tUser&&(!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); diff --git a/web/modules/mail/view.js b/web/modules/mail/view.js index 548d58e..36e6c34 100644 --- a/web/modules/mail/view.js +++ b/web/modules/mail/view.js @@ -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=`向托管邮箱发送 [模板][产品线]发信标题,新版本将在这里等待确认。未填写产品线时作为默认模板。
{{产品线}}、{{订单号}}、{{日期}}、{{订单列表}}| 标题 / 范围 | 来源 | |
|---|---|---|
${esc(t.subject)} ${esc(t.scope||'默认模板')} · ${stateBadge(t)} · ${t.attachmentCount} 个附件 | ${esc(data.channels.find(c=>c.id===t.channelId)?.name||'旧模板草稿')} ${esc(t.sender)} ${formatDate(t.createdAt)} |
| 标题 / 范围 | 来源 | |
|---|---|---|
${esc(t.subject)} ${esc(t.scope||'默认模板')} · ${stateBadge(t)} · ${t.attachmentCount} 个附件 | ${esc(data.channels.find(c=>c.id===t.channelId)?.name||'旧模板草稿')} ${esc(t.sender)} ${formatDate(t.createdAt)} |
扫描只采集待办并建立执行任务;BPM 节点由人工办理。受阻原因与重试结果以服务器任务状态为准。
只读账号可查看任务,不能扫描或重试。
'}| 任务 | 状态 / 原因 | 操作 |
|---|---|---|
| ${esc(t.orderNo||t.title||t.id)} ${esc(t.processName||'')} · v${esc(t.version)} ${formatDate(t.updatedAt||t.createdAt)} | ${esc(({failed:'失败',blocked:'受阻',unknown:'结果待核实',archived:'已归档',sent:'已提交邮件服务器'})[t.status]||t.status)} ${esc(t.error||t.reason||t.blockedReason||'')} | ${admin&&t.status==='failed'?``:t.status==='unknown'?'须先人工核验结果':'—'} |
| 暂无任务。先检查实际接入能力与连接权限。 | ||
扫描只采集待办并建立执行任务;BPM 节点由人工办理。受阻原因与重试结果以服务器任务状态为准。
只读账号可查看任务,不能扫描或重试。
'}| 任务 | 状态 / 原因 | 操作 |
|---|
${esc(b.text||'')}