feat: unify order workbench and stable paged evidence views

This commit is contained in:
abaishu0730 committed 2026-10-21 11:04:43 +08:00
1 parent 10eac70745
commit 84e2f0d9ba
30 files changed
+543 -294

No files matched your search

+8
View File
@@ -0,0 +1,8 @@
const test=require('node:test'),assert=require('node:assert/strict'),vm=require('node:vm'),fs=require('node:fs');
test('business list state preserves whitelisted filters and account separation',()=>{
const saved=new Map(),context={window:{},document:{querySelectorAll:()=>[]},URLSearchParams,location:{hash:''},history:{replaceState(){}},sessionStorage:{getItem:k=>saved.get(k),setItem:(k,v)=>saved.set(k,v),get length(){return saved.size},key:i=>[...saved.keys()][i],removeItem:k=>saved.delete(k)}};vm.runInNewContext(fs.readFileSync('web/modules/records/state.js','utf8'),context);const s=context.window.RecordState;
assert.equal(s.isRecord('#notification-orders?page=3'),true);s.configure({id:'alice'},()=>{});s.commit('notification-orders',{q:'order',page:3,pageSize:50,categoryId:'cat',secret:'no'});assert.match(s.href('notification-orders'),/page=3/);assert.equal(s.normalize('notification-orders',{secret:'no'}).secret,undefined);s.configure({id:'bob'},()=>{});assert.equal(s.href('notification-orders'),'#notification-orders');assert.equal(s.defaults('notification-batches').scope,'active');
});
test('retired supervisor entry delegates to health without a write form',async()=>{
let renders=0;const context={window:{HealthViews:{render:async()=>renders++}}};vm.runInNewContext(fs.readFileSync('web/modules/workspace/view.js','utf8'),context);await context.window.WorkspaceViews.supervisor({},()=>true);assert.equal(renders,1);
});
+31
View File
@@ -0,0 +1,31 @@
'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');
const {loadPlaywright,browserOptions}=require('../../src/platform/browser.cjs');
async function fixture(t){const dir=await fs.mkdtemp(path.join(os.tmpdir(),'business-query-ui-')),runtime=await startTestDashboard({stateDir:dir,mailHistory:true}),browser=await loadPlaywright().chromium.launch(browserOptions());t.after(async()=>{await browser.close();await runtime.close();await fs.rm(dir,{recursive:true,force:true});});
for(let i=0;i<83;i++)runtime.orderRules.put('orders',{id:'order-'+String(i).padStart(3,'0'),categoryId:'cat',status:'pending',sample:{connectionId:'c',fields:{private:'DO NOT EXPOSE'}},event:{connectionId:'c',orderNo:'ORDER '+i,receivedAt:'2026-10-20T10:00:00Z'},createdAt:'2026-10-20T10:00:00Z'});
runtime.orderRules.put('batches',{id:'old-prepared',status:'prepared',subject:'旧窗口待发批次',categoryId:'cat',orderIds:['order-000'],windowStart:'2020-01-01T00:00:00Z',text:'冻结正文',to:['test@example.invalid'],cc:[]});
const page=await browser.newPage({viewport:{width:1280,height:900}});page.setDefaultTimeout(6000);const base='http://127.0.0.1:'+runtime.server.address().port;return {page,runtime,base};}
test('business lists paginate, query on enter, retain detail during background updates, and keep mobile width',{timeout:90000},async t=>{
const {page,runtime,base}=await fixture(t);const errors=[];page.on('pageerror',e=>errors.push(e.message));await page.clock.install();await page.goto(base+'/#notification-orders?page=999');await login(page);await page.waitForFunction(()=>document.querySelector('[data-record-count]')?.textContent.includes('第 4 / 4'));
assert.equal(await page.locator('[data-business-detail]').count(),8);await page.getByLabel('每页条数',{exact:true}).selectOption('50');await page.waitForFunction(()=>document.querySelectorAll('[data-business-detail]').length===50);
await page.getByRole('button',{name:'查看详情',exact:true}).first().click();await page.getByRole('dialog',{name:'业务详情'}).getByRole('heading',{name:'处理进度'}).waitFor();
runtime.orderRules.put('orders',{id:'new',status:'blocked',event:{orderNo:'NEW',connectionId:'c',receivedAt:'2026-10-21T00:00:00Z'}});await page.clock.fastForward(11000);await page.getByText('记录有更新。',{exact:true}).waitFor();assert.equal(await page.locator('[data-business-detail]').count(),50);await page.getByRole('dialog').getByRole('heading',{name:'处理进度'}).waitFor();
await page.getByRole('button',{name:'关闭详情',exact:true}).click();await page.clock.fastForward(500);await page.locator('[name=q]').fill('ORDER 8');await page.locator('[name=q]').press('Enter');await page.waitForFunction(()=>document.querySelectorAll('[data-business-detail]').length===4);await page.setViewportSize({width:390,height:844});assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true);
await page.goto(base+'/#notification-history');await page.getByText('旧窗口待发批次',{exact:true}).waitFor();assert.equal(new URL(page.url()).hash,'#notification-batches?scope=all');assert.deepEqual(errors,[]);
});
test('failed pagination retains successful rows and slow request cannot replace destination',{timeout:90000},async t=>{
const {page,base}=await fixture(t);await page.goto(base+'/#notification-orders');await login(page);await page.locator('[data-business-detail]').first().waitFor();let held;await page.route('**/api/order-rules/orders?*',route=>{if(new URL(route.request().url()).searchParams.get('page')==='2')held=route;else route.continue();});await page.getByRole('button',{name:'下一页',exact:true}).click();await page.waitForFunction(()=>document.querySelector('[data-record-next]').disabled);while(!held)await new Promise(r=>setTimeout(r,20));await held.fulfill({status:503,json:{error:'隔离分页失败'}});await page.getByRole('button',{name:'重试加载',exact:true}).waitFor();assert.match(await page.locator('[data-record-count]').innerText(),/第 1 /);assert.equal(await page.locator('[data-business-detail]').count(),25);
held=null;await page.getByRole('button',{name:'重试加载',exact:true}).click();while(!held)await new Promise(r=>setTimeout(r,20));await page.goto(base+'/#notification-batches');await page.getByText('旧窗口待发批次',{exact:true}).waitFor();await held.fulfill({json:{items:[],total:0,page:1,pageSize:25}}).catch(()=>{});await page.getByText('旧窗口待发批次',{exact:true}).waitFor();
});
test('business list links retain independent applied pages through tab return, reload and account logout',{timeout:90000},async t=>{
const {page,base}=await fixture(t);await page.goto(base+'/#notification-orders');await login(page);await page.locator('[data-record-count]').waitFor();await page.getByRole('button',{name:'下一页',exact:true}).click();await page.waitForFunction(()=>document.querySelector('[data-record-count]').textContent.includes('第 2 /'));await page.locator('#sidebar-menu a[data-view=notification-batches]').click();await page.getByText('旧窗口待发批次',{exact:true}).waitFor();await page.locator('#sidebar-menu a[data-view=notification-orders]').click();await page.waitForFunction(()=>document.querySelector('[data-record-count]').textContent.includes('第 2 /'),null,{timeout:2500});await page.reload();await page.waitForFunction(()=>document.querySelector('[data-record-count]')?.textContent.includes('第 2 /'));await page.getByRole('button',{name:'退出',exact:true}).click();await page.locator('#login-form').waitFor();assert.equal(await page.evaluate(()=>Object.keys(sessionStorage).filter(k=>k.startsWith('ona-record-navigation:')).length),0);
});
test('dismissal cancels late details, guards Escape drafts, and sent batch links include history',{timeout:90000},async t=>{
const {page,runtime,base}=await fixture(t);runtime.orderRules.put('batches',{id:'sent-reference',status:'sent',subject:'已发送关联批次',orderIds:['order-000'],text:'历史正文',attachments:[]});
await page.goto(base+'/#notification-orders?q=order-000');await login(page);await page.locator('[data-business-detail]').waitFor();let release,started;const ready=new Promise(r=>started=r),gate=new Promise(r=>release=r);t.after(()=>release());
await page.route('**/api/order-rules/orders/order-000',async route=>{started();await gate;await route.continue().catch(()=>{});});await page.getByRole('button',{name:'查看详情',exact:true}).click();await ready;await page.getByRole('button',{name:'关闭详情',exact:true}).click();await page.getByRole('dialog',{name:'业务详情'}).waitFor({state:'hidden'});release();await page.unroute('**/api/order-rules/orders/order-000');await page.waitForTimeout(600);assert.equal(await page.locator('.record-detail.show,.record-detail.showing').count(),0);
await page.getByRole('button',{name:'查看详情',exact:true}).click();const link=page.getByRole('link',{name:'已发送关联批次',exact:true});await link.waitFor();assert.match(await link.getAttribute('href'),/scope=all/);await link.click();await page.getByText('已发送关联批次',{exact:true}).waitFor();
runtime.orderRules.put('batches',{id:'failed-draft',status:'failed',subject:'失败批次草稿',orderIds:['order-000'],text:'冻结正文',attachments:[],version:1});await page.goto(base+'/#notification-batches?q=failed-draft');await page.getByRole('button',{name:'查看详情',exact:true}).click();await page.locator('.record-detail.show:not(.showing)').waitFor();await page.locator('[data-business-action] textarea').fill('未提交的人工补发依据');assert.equal(await page.evaluate(()=>PageLifecycle.dirty()),true);await page.keyboard.press('Escape');await page.getByRole('dialog',{name:'未保存的修改'}).waitFor();await page.getByRole('button',{name:'留在此页',exact:true}).click();assert.equal(await page.locator('.record-detail.show').count(),1);await page.keyboard.press('Escape');await page.getByRole('button',{name:'放弃并继续',exact:true}).click();await page.getByRole('dialog',{name:'业务详情'}).waitFor({state:'hidden'});assert.equal(await page.evaluate(()=>PageLifecycle.dirty()),false);
});
+4 -4
View File
@@ -11,11 +11,11 @@ test('compact navigation groups settings, retains deep links and role boundaries
await page.goto(base+'/#system-settings');await page.getByLabel('账号',{exact:true}).fill(role);await page.getByLabel('密码',{exact:true}).fill(password);await page.getByRole('button',{name:'登录',exact:true}).click();
await page.getByRole('heading',{name:'BPM 连接',exact:true}).first().waitFor();assert.equal(await page.locator('#sidebar-menu [data-view]').count(),7);
assert.equal(await page.locator('#settings-tabs a[href="#users"]').count(),role==='admin'?1:0);
await page.getByRole('link',{name:'订单通知管理',exact:true}).click();await page.getByRole('link',{name:'通知配置',exact:true}).click();await page.locator('#schedule-form').waitFor();
assert.equal(await page.locator('#sidebar-menu [aria-current="page"]').getAttribute('href'),'#order-notifications');
await page.getByRole('link',{name:'邮件批次',exact:true}).click();await page.getByRole('link',{name:'通知配置',exact:true}).click();await page.locator('#schedule-form').waitFor();
assert.equal(await page.locator('#sidebar-menu [aria-current="page"]').getAttribute('href'),'#notification-batches');
await page.getByRole('link',{name:'业务设置',exact:true}).click();await page.getByRole('heading',{name:'分类通知规则',exact:true}).waitFor();
await page.goto(base+'/#users');await page.getByRole('heading',{name:role==='admin'?'团队账号':'工作总览',exact:true}).first().waitFor();
await page.goto(base+'/#calendar');await page.getByRole('heading',{name:'业务日历',exact:true}).waitFor();assert.equal(await page.locator('#sidebar-menu [aria-current="page"]').getAttribute('href'),'#order-notifications');
await page.goto(base+'/#users');await page.getByRole('heading',{name:role==='admin'?'团队账号':'业务首页',exact:true}).first().waitFor();
await page.goto(base+'/#calendar');await page.getByRole('heading',{name:'业务日历',exact:true}).waitFor();assert.equal(await page.locator('#sidebar-menu [aria-current="page"]').getAttribute('href'),'#notification-batches');
await page.goto(base+'/#system-settings');await page.setViewportSize({width:390,height:844});await page.getByRole('button',{name:'展开菜单',exact:true}).click();
await page.locator('#sidebar-menu').getByRole('link',{name:'业务设置',exact:true}).click();await page.getByRole('heading',{name:'分类通知规则',exact:true}).waitFor();
await page.waitForFunction(()=>!document.querySelector('#sidebar-menu').classList.contains('collapsing'));assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true);assert.equal(await page.locator('#sidebar-menu').evaluate(el=>el.classList.contains('show')),false);assert.equal(await page.getByRole('button',{name:'展开菜单',exact:true}).getAttribute('aria-expanded'),'false');
+17 -108
View File
@@ -1,117 +1,26 @@
'use strict';
const {test}=require('node:test');
const assert=require('node:assert/strict');
const fs=require('node:fs/promises'),os=require('node:os'),path=require('node:path');
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');
const {loadPlaywright,browserOptions}=require('../../src/platform/browser.cjs');
async function fixture(t){
const dir=await fs.mkdtemp(path.join(os.tmpdir(),'notification-navigation-'));
const runtime=await startTestDashboard({stateDir:dir,mailHistory:true});
const browser=await loadPlaywright().chromium.launch(browserOptions());
t.after(async()=>{await browser.close();await runtime.close();await fs.rm(dir,{recursive:true,force:true});});
return {runtime,browser,base:'http://127.0.0.1:'+runtime.server.address().port};
}
test('notification operations have addressable navigation while rules remain in business settings',{timeout:90000},async t=>{
const {runtime,browser,base}=await fixture(t),page=await browser.newPage({viewport:{width:1440,height:1000}});
page.setDefaultTimeout(7000);const errors=[],writes=[];
page.on('pageerror',error=>errors.push(error.message));page.on('request',req=>{if(req.method()==='POST'&&!req.url().endsWith('/login'))writes.push(req.url());});
await page.goto(base+'/#order-notifications');await login(page);
await page.getByRole('heading',{name:'通知总览',exact:true}).waitFor();
assert.equal(await page.locator('#sidebar-menu [data-view]').count(),7);
const routeCases=[['notification-execution','订单执行'],['notification-orders','通知订单'],['notification-batches','待发批次'],['notification-history','发送记录'],['schedule','发送计划'],['calendar','业务日历'],['templates','邮件模板'],['notification-settings','发送设置']];
for(const [route,title] of routeCases){
await page.goto(base+'/#'+route);await page.locator('#view-title').filter({hasText:title}).waitFor();
assert.equal(await page.locator('#sidebar-menu [aria-current="page"]').getAttribute('href'),'#order-notifications');
assert.equal(await page.locator('#settings-tabs .active').getAttribute('href'),['schedule','calendar','templates','notification-settings'].includes(route)?'#schedule':'#'+route);
if(['schedule','calendar','templates','notification-settings'].includes(route))assert.equal(await page.locator('#notification-config-tabs [aria-current="page"]').getAttribute('href'),'#'+route);
}
await page.goto(base+'/#business-settings');await page.getByRole('heading',{name:'分类通知规则',exact:true}).waitFor();
assert.deepEqual(await page.locator('#settings-tabs a').allTextContents(),['分类通知规则','字段映射']);
await page.locator('#settings-tabs a[href="#rule-fields"]').click();await page.getByRole('heading',{name:'字段映射',exact:true}).first().waitFor();
await page.reload();assert.equal(await page.locator('#sidebar-menu [aria-current="page"]').getAttribute('href'),'#business-settings');
await page.goBack();await page.getByRole('heading',{name:'分类通知规则',exact:true}).waitFor();
await page.goForward();await page.getByRole('heading',{name:'字段映射',exact:true}).first().waitFor();
assert.equal(runtime.orderRules.snapshot().settings.enabled,false);assert.deepEqual(writes,[]);assert.deepEqual(errors,[]);
async function fixture(t){const dir=await fs.mkdtemp(path.join(os.tmpdir(),'notification-navigation-')),runtime=await startTestDashboard({stateDir:dir,mailHistory:true}),browser=await loadPlaywright().chromium.launch(browserOptions());t.after(async()=>{await browser.close();await runtime.close();await fs.rm(dir,{recursive:true,force:true});});return {runtime,browser,base:'http://127.0.0.1:'+runtime.server.address().port};}
test('one business homepage and canonical order/batch routes preserve old deep links and configuration navigation',{timeout:90000},async t=>{
const {runtime,browser,base}=await fixture(t),page=await browser.newPage();page.setDefaultTimeout(6000);const errors=[],writes=[],full=[];page.on('pageerror',e=>errors.push(e.message));page.on('request',r=>{if(r.method()==='POST'&&!r.url().endsWith('/login'))writes.push(r.url());if(r.url()===base+'/api/order-rules')full.push(r.url());});await page.goto(base+'/#order-notifications');await login(page);await page.getByRole('heading',{name:'业务首页',exact:true}).waitFor();assert.equal(new URL(page.url()).hash,'#overview');assert.equal(await page.locator('#sidebar-menu [data-view]').count(),7);
for(const [route,title,canonical]of [['notification-execution','订单中心','notification-orders'],['notification-orders','订单中心','notification-orders'],['notification-history','邮件批次','notification-batches'],['notification-batches','邮件批次','notification-batches'],['schedule','发送计划','schedule'],['calendar','业务日历','calendar'],['templates','邮件模板','templates'],['notification-settings','发送设置','notification-settings']]){await page.goto(base+'/#'+route);await page.locator('#view-title').getByText(title,{exact:true}).waitFor();assert.equal(new URL(page.url()).hash,'#'+canonical+(route==='notification-history'?'?scope=all':''));if(['schedule','calendar','templates','notification-settings'].includes(route))await page.locator('#notification-config-tabs [aria-current=page]').waitFor();}
await page.goto(base+'/#templates');await page.getByRole('heading',{name:'有效使用情况(只读)',exact:true}).waitFor();assert.equal(await page.getByRole('button',{name:'保存关联',exact:true}).count(),0);
assert.equal(runtime.orderRules.settings().enabled,false);assert.deepEqual(writes,[]);assert.deepEqual(full,[]);assert.deepEqual(errors,[]);
});
test('status reflects persisted notification settings, read failures and late responses',{timeout:60000},async t=>{
const {browser,base}=await fixture(t),page=await browser.newPage();page.setDefaultTimeout(7000);
await page.goto(base+'/#overview');await login(page);await page.getByText('自动通知已暂停',{exact:true}).waitFor();
const original=await (await page.request.get(base+'/api/order-rules')).json();
const overview=await (await page.request.get(base+'/api/overview')).json();
await page.route('**/api/overview',route=>route.fulfill({json:{...overview,automation:{enabled:true,ready:true,reason:'隔离测试:实际检查通过'}}}));
await page.route('**/api/order-rules',route=>route.fulfill({json:{...original,settings:{...original.settings,enabled:true},capabilities:{liveTodo:true,pdfExport:true,automaticArchive:true}}}));
await page.getByRole('button',{name:'刷新数据',exact:true}).click();await page.getByText('自动通知已启用',{exact:true}).waitFor();
assert.match(await page.locator('#workspace-automation').innerText(),/已启用/);
await page.route('**/api/order-rules',route=>route.fulfill({status:503,json:{error:'隔离测试:状态查询失败'}}));
await page.getByRole('button',{name:'刷新数据',exact:true}).click();await page.getByText('通知状态待确认',{exact:true}).waitFor();
assert.match(await page.locator('#automation-status').getAttribute('title'),/状态查询失败/);
let release,received;
const held=new Promise(resolve=>{received=resolve;});
await page.route('**/api/order-rules',async route=>{release=()=>route.fulfill({json:{...original,settings:{...original.settings,enabled:true},capabilities:{liveTodo:true,pdfExport:true,automaticArchive:true}}});received();});
await page.getByRole('button',{name:'刷新数据',exact:true}).click();await held;
await page.route('**/api/order-rules',route=>route.fulfill({status:503,json:{error:'新页面状态仍待核实'}}));
await page.locator('#sidebar-menu a[href="#system-settings"]').click();await page.getByRole('heading',{name:'BPM 连接',exact:true}).first().waitFor();
await page.waitForFunction(()=>document.querySelector('#automation-status')?.title.includes('新页面状态仍待核实'));
const completed=page.waitForResponse(response=>response.url().endsWith('/api/order-rules')&&response.status()===200);
await release();await completed;await page.evaluate(()=>new Promise(requestAnimationFrame));
assert.equal(await page.locator('#automation-status').innerText(),'通知状态待确认');
});
test('notification and configuration navigation retain dirty guards and fit mobile for each role',{timeout:90000},async t=>{
const {runtime,browser,base}=await fixture(t);
for(const role of ['operator','viewer'])runtime.store.addUser({username:role,password:'Test-password-123',role},'admin');
for(const role of ['admin','operator','viewer']){
const context=await browser.newContext({viewport:{width:390,height:844}}),page=await context.newPage();page.setDefaultTimeout(7000);
await page.goto(base+'/#notification-settings');await page.getByLabel('账号',{exact:true}).fill(role);await page.getByLabel('密码',{exact:true}).fill('Test-password-123');await page.getByRole('button',{name:'登录',exact:true}).click();
await page.getByRole('heading',{name:'发送设置',exact:true}).first().waitFor();await page.locator('#order-rule-max-size').waitFor();
assert.equal(await page.locator('#order-rule-max-size').isDisabled(),role!=='admin');
assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true);
assert.equal(await page.locator('#settings-tabs .active').evaluate(el=>{const r=el.getBoundingClientRect(),p=el.parentElement.getBoundingClientRect();return r.left>=p.left-1&&r.right<=p.right+1;}),true);
if(role==='admin'){
await page.locator('#order-rule-max-size').fill('19');await page.locator('#notification-config-tabs a[href="#calendar"]').click();
await page.getByRole('button',{name:'留在此页',exact:true}).click();assert.equal(await page.locator('#order-rule-max-size').inputValue(),'19');
await page.locator('#notification-config-tabs a[href="#calendar"]').click();await page.getByRole('button',{name:'放弃并继续',exact:true}).click();await page.getByRole('heading',{name:'业务日历',exact:true}).waitFor();
await page.setViewportSize({width:1440,height:1000});await page.evaluate(()=>new Promise(requestAnimationFrame));
await page.setViewportSize({width:390,height:844});await page.evaluate(()=>new Promise(requestAnimationFrame));
assert.equal(await page.locator('#settings-tabs .active').evaluate(el=>{const r=el.getBoundingClientRect(),p=el.parentElement.getBoundingClientRect();return r.left>=p.left-1&&r.right<=p.right+1;}),true,'active notification configuration remains visible after resizing');
}
await page.goto(base+'/#system-settings');await page.getByRole('heading',{name:'BPM 连接',exact:true}).first().waitFor();
assert.equal(await page.locator('#settings-tabs a[href="#users"]').count(),role==='admin'?1:0);
assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true);
test('notification settings retain dirty guards and role controls on mobile',{timeout:90000},async t=>{
const {runtime,browser,base}=await fixture(t);for(const role of ['operator','viewer'])runtime.store.addUser({username:role,password:'Test-password-123',role},'admin');
for(const role of ['admin','operator','viewer']){const context=await browser.newContext({viewport:{width:390,height:844}}),page=await context.newPage();page.setDefaultTimeout(6000);await page.goto(base+'/#notification-settings');await page.getByLabel('账号',{exact:true}).fill(role);await page.getByLabel('密码',{exact:true}).fill('Test-password-123');await page.getByRole('button',{name:'登录',exact:true}).click();await page.locator('#order-rule-max-size').waitFor();assert.equal(await page.locator('#order-rule-max-size').isDisabled(),role!=='admin');assert.equal(await page.locator('[name=processingEnabled]').isDisabled(),role!=='admin');assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true);
if(role==='admin'){await page.locator('#order-rule-max-size').fill('19');await page.locator('#notification-config-tabs a[href="#calendar"]').click();await page.getByRole('button',{name:'留在此页',exact:true}).click();assert.equal(await page.locator('#order-rule-max-size').inputValue(),'19');await page.locator('#notification-config-tabs a[href="#calendar"]').click();await page.getByRole('button',{name:'放弃并继续',exact:true}).click();await page.getByRole('heading',{name:'业务日历',exact:true}).waitFor();}
await context.close();
}
assert.equal(runtime.orderRules.snapshot().settings.enabled,false);
});
test('older overview polls cannot replace a newer persisted notification state',{timeout:60000},async t=>{
const {browser,base}=await fixture(t),page=await browser.newPage();page.setDefaultTimeout(7000);
await page.clock.install();await page.goto(base+'/#overview');await login(page);await page.locator('#workspace-automation').waitFor();
const snapshot=await (await page.request.get(base+'/api/overview')).json(),pending=[];let firstSeen,secondSeen;
const first=new Promise(resolve=>{firstSeen=resolve;}),second=new Promise(resolve=>{secondSeen=resolve;});
await page.route('**/api/overview',route=>{pending.push(route);if(pending.length===1)firstSeen();if(pending.length===2)secondSeen();});
await page.clock.fastForward(15001);await first;
assert.equal(pending.length,1);
await page.clock.fastForward(15001);await second;
assert.equal(pending.length,2);
await pending[1].fulfill({json:{...snapshot,automation:{enabled:true,ready:true,reason:'较新服务端状态'}}});
await page.locator('#workspace-automation').getByText('较新服务端状态',{exact:true}).waitFor();
const completed=page.waitForResponse(response=>response.url().endsWith('/api/overview')&&response.status()===200);
await pending[0].fulfill({json:{...snapshot,automation:{enabled:false,ready:false,reason:'较旧服务端状态'}}});await completed;
await page.evaluate(()=>new Promise(requestAnimationFrame));
assert.match(await page.locator('#workspace-automation').innerText(),/较新服务端状态/);
test('summary status failures and old responses cannot overwrite a later page status',{timeout:60000},async t=>{
const {browser,base}=await fixture(t),page=await browser.newPage();page.setDefaultTimeout(6000);await page.goto(base+'/#notification-orders');await login(page);await page.getByText('自动通知已暂停',{exact:true}).waitFor();const original=await(await page.request.get(base+'/api/order-rules?view=summary')).json();
await page.route('**/api/order-rules?view=summary',route=>route.fulfill({json:{...original,settings:{...original.settings,enabled:true},capabilities:{liveTodo:true,pdfExport:true,automaticArchive:true}}}));await page.getByRole('button',{name:'刷新数据',exact:true}).click();await page.getByText('自动通知已启用',{exact:true}).waitFor();
let held,receive;const received=new Promise(r=>receive=r);await page.route('**/api/order-rules?view=summary',route=>{held=route;receive();});await page.getByRole('button',{name:'刷新数据',exact:true}).click();await received;await page.route('**/api/order-rules?view=summary',route=>route.fulfill({status:503,json:{error:'最新状态读取失败'}}));await page.goto(base+'/#bpm');await page.waitForFunction(()=>document.querySelector('#automation-status')?.title.includes('最新状态读取失败'));await held.fulfill({json:original}).catch(()=>{});await page.waitForTimeout(100);assert.equal(await page.locator('#automation-status').innerText(),'通知状态待确认');
});
test('a failed initial overview read cannot replace a later successful poll',{timeout:60000},async t=>{
const {browser,base}=await fixture(t),page=await browser.newPage();page.setDefaultTimeout(7000);await page.clock.install();
let initial,received,snapshot;const held=new Promise(resolve=>{received=resolve;});
await page.route('**/api/overview',route=>{if(!initial){initial=route;received();return;}return route.fulfill({json:{...snapshot,automation:{enabled:false,ready:false,reason:'最新读取成功'}}});});
await page.goto(base+'/#overview');await login(page);await held;
snapshot=await (await page.request.get(base+'/api/overview')).json();
await page.clock.fastForward(15001);await page.locator('#workspace-automation').getByText('最新读取成功',{exact:true}).waitFor();
const completed=page.waitForResponse(response=>response.url().endsWith('/api/overview')&&response.status()===503);
await initial.fulfill({status:503,json:{error:'已过期的读取错误'}});await completed;await page.evaluate(()=>new Promise(requestAnimationFrame));
assert.match(await page.locator('#content').innerText(),/最新读取成功/);
test('homepage background polling only announces updates and ignores responses after departure',{timeout:60000},async t=>{
const {browser,base}=await fixture(t),page=await browser.newPage();page.setDefaultTimeout(6000);await page.clock.install();await page.goto(base+'/#overview');await login(page);await page.getByRole('heading',{name:'连续业务窗口',exact:true}).waitFor();const original=await(await page.request.get(base+'/api/order-rules?view=summary')).json();let held;await page.route('**/api/order-rules?view=summary',route=>{held=route;return route.fulfill({json:{...original,counts:{...original.counts,orders:42}}});});await page.clock.fastForward(15001);await page.locator('[data-business-updates]').waitFor();assert.equal(await page.locator('.metric-number').first().innerText(),'0项');await page.goto(base+'/#notification-orders');await page.locator('[data-record-count]').waitFor();assert.equal(await page.locator('[data-business-updates]').count(),0);
});
+2 -2
View File
@@ -7,7 +7,7 @@ test('browser back to a bare record URL restores page one rather than the most r
test('logout clears saved record filters and the next account starts with its own defaults',async t=>{const f=await setup(t),page=await f.page('#records?page=3');await page.locator('[data-arrival-row]').first().waitFor();await page.getByRole('button',{name:'退出',exact:true}).click();await page.locator('#login-form').waitFor();assert.equal(await page.evaluate(()=>Object.keys(sessionStorage).filter(k=>k.startsWith('ona-record-navigation:')).length),0);await page.locator('#username').fill('viewer');await page.locator('#password').fill(f.password);await page.locator('#login-form button').click();await page.locator('[data-arrival-row]').first().waitFor();assert.match(await page.locator('[data-record-count]').innerText(),/第 1/);});
test('background updates preserve open details and drafts until explicit refresh, and page size uses applied filters',async t=>{const f=await setup(t),page=await f.page('#records','admin',true);await page.locator('[data-arrival-row]').first().waitFor();await page.getByLabel('搜索流程记录',{exact:true}).fill('未应用的关键字');await page.getByRole('button',{name:'查看详情',exact:true}).first().click();await page.getByRole('dialog',{name:'流程到达详情'}).waitFor();f.scan.complete(f.scan.begin(f.connection.id,'admin'),f.connection.id,[{taskId:'NEW',serialNum:'NEW',source:'portal-v4',processName:'海外运营订单评审',activityName:'通知节点',subject:'后台新增记录',arrivalDay:'2026-10-21',arrivedAt:'2026-10-21T01:00:00Z'}]);await page.clock.fastForward(11000);await page.getByText('记录有更新。',{exact:true}).waitFor();assert.match(await page.locator('[data-record-count]').innerText(),/105/);assert.equal(await page.locator('[data-arrival-row]').filter({hasText:'后台新增记录'}).count(),0);await page.getByRole('dialog').getByText('订单样例 000',{exact:true}).waitFor();await page.getByRole('button',{name:'关闭详情',exact:true}).click();await page.clock.fastForward(400);await page.locator('.card-header').getByRole('button',{name:'刷新记录',exact:true}).click();await page.locator('[data-arrival-row]').filter({hasText:'后台新增记录'}).waitFor();assert.match(await page.locator('[data-record-count]').innerText(),/106/);assert.equal(await page.getByLabel('搜索流程记录',{exact:true}).inputValue(),'未应用的关键字');await page.getByLabel('每页条数',{exact:true}).selectOption('50');await page.waitForFunction(()=>document.querySelectorAll('[data-arrival-row]').length===50);assert.equal(new URLSearchParams(page.url().split('?')[1]).has('q'),false);assert.equal(await page.evaluate(()=>JSON.stringify(sessionStorage).includes('后台新增记录')),false);});
test('record scroll positions survive page changes, tab return and reload without widening the mobile viewport',async t=>{const f=await setup(t),page=await f.page('#records?page=2');await page.locator('[data-arrival-row]').first().waitFor();await page.evaluate(()=>window.scrollTo(0,850));await page.waitForTimeout(250);await page.goto(f.base+'/#records-pdf');await page.locator('[data-pdf-row]').first().waitFor();await page.evaluate(()=>window.scrollTo(0,600));await page.waitForTimeout(250);await page.goto(f.base+'/#records?page=2');await page.locator('[data-arrival-row]').first().waitFor();await page.waitForFunction(()=>Math.abs(window.scrollY-850)<80);await page.reload();await page.locator('[data-arrival-row]').first().waitFor();await page.waitForFunction(()=>Math.abs(window.scrollY-850)<80);await page.setViewportSize({width:390,height:844});assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true);});
test('sync configuration failures retain input and use the shared save-and-leave guard',async t=>{const f=await setup(t),page=await f.page('#bpm');await page.locator('#scan-config').waitFor();let reject=true;await page.route('**/api/bpm-scan/config',route=>reject?route.fulfill({status:503,json:{error:'隔离保存失败'}}):route.continue());await page.getByLabel('完整对账间隔(分钟)',{exact:true}).fill('11');await page.getByRole('button',{name:'保存同步设置',exact:true}).click();await page.locator('#scan-config').getByText('隔离保存失败',{exact:true}).waitFor();assert.equal(await page.getByLabel('完整对账间隔(分钟)',{exact:true}).inputValue(),'11');assert.equal(f.scan.config().intervalMinutes,9);await page.getByRole('link',{name:'订单与导出记录',exact:true}).click();await page.getByRole('dialog',{name:'未保存的修改'}).waitFor();reject=false;await page.getByRole('button',{name:'保存并继续',exact:true}).click();await page.locator('[data-arrival-row]').first().waitFor();assert.equal(f.scan.config().intervalMinutes,11);});
test('sync configuration failures retain input and use the shared save-and-leave guard',async t=>{const f=await setup(t),page=await f.page('#bpm');await page.locator('#scan-config').waitFor();let reject=true;await page.route('**/api/bpm-scan/config',route=>reject?route.fulfill({status:503,json:{error:'隔离保存失败'}}):route.continue());await page.getByLabel('完整对账间隔(分钟)',{exact:true}).fill('11');await page.getByRole('button',{name:'保存同步设置',exact:true}).click();await page.locator('#scan-config').getByText('隔离保存失败',{exact:true}).waitFor();assert.equal(await page.getByLabel('完整对账间隔(分钟)',{exact:true}).inputValue(),'11');assert.equal(f.scan.config().intervalMinutes,9);await page.getByRole('link',{name:'工具',exact:true}).click();await page.getByRole('dialog',{name:'未保存的修改'}).waitFor();reject=false;await page.getByRole('button',{name:'保存并继续',exact:true}).click();await page.locator('[data-arrival-row]').first().waitFor();assert.equal(f.scan.config().intervalMinutes,11);});
test('missing sync configuration shows an error and retry without replacing the connection page or inventing defaults',async t=>{const f=await setup(t),page=await f.page('#records');await page.locator('[data-arrival-row]').first().waitFor();let fail=true;await page.route('**/api/bpm-scan',route=>fail?route.fulfill({status:503,json:{error:'配置暂不可用'}}):route.continue());await page.goto(f.base+'/#bpm');await page.getByRole('button',{name:'重试读取同步设置',exact:true}).waitFor();assert.equal(await page.locator('#scan-config').count(),0);await page.getByRole('heading',{name:'隔离测试来源',exact:true}).waitFor();fail=false;await page.getByRole('button',{name:'重试读取同步设置',exact:true}).click();await page.locator('#scan-config').waitFor();assert.equal(await page.getByLabel('完整对账间隔(分钟)',{exact:true}).inputValue(),'9');});
test('leaving a slow record page cancels its request and late data cannot replace the PDF tab',async t=>{const f=await setup(t),page=await f.page('#records');await page.locator('[data-arrival-row]').first().waitFor();let release;const received=new Promise(resolve=>release=resolve);await page.route('**/api/arrivals?*',route=>{if(new URL(route.request().url()).searchParams.get('page')==='2')release(route);else void route.continue();});await page.getByRole('button',{name:'下一页',exact:true}).click();const held=await received;await page.getByRole('link',{name:'PDF 导出记录',exact:true}).click();await page.locator('[data-pdf-row]').first().waitFor();await held.fulfill({json:{items:[],total:0,page:2,pageSize:25,sources:[]}}).catch(()=>{});assert.equal(await page.locator('[data-arrival-row]').count(),0);assert.equal(await page.locator('[data-pdf-row]').count(),25);assert.equal(new URL(page.url()).hash,'#records-pdf');});
test('the record same-tab shortcut does not suppress the existing refresh behavior of other pages',async t=>{const f=await setup(t),page=await f.page('#overview');await page.locator('#workspace-automation').waitFor();const read=page.waitForRequest(r=>new URL(r.url()).pathname==='/api/overview',{timeout:2000});await page.getByRole('link',{name:'工作总览',exact:true}).click();await read;});
test('the record same-tab shortcut does not suppress the existing refresh behavior of other pages',async t=>{const f=await setup(t),page=await f.page('#bpm');await page.locator('#scan-config').waitFor();const read=page.waitForRequest(r=>new URL(r.url()).pathname==='/api/workspace',{timeout:2000});await page.locator('#settings-tabs').getByRole('link',{name:'BPM 连接',exact:true}).click();await read;});
+12 -13
View File
@@ -1,9 +1,9 @@
'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};}
async function fixture(t,hash='schedule'){const dir=await fs.mkdtemp(path.join(os.tmpdir(),'closure-review-')),runtime=await startTestDashboard({stateDir:dir,mailHistory:true}),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 openRuleRoute(page,'notification-settings');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 openRuleRoute(page,'order-notifications');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);});
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 openRuleRoute(page,'notification-settings');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 openRuleRoute(page,'order-notifications');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 template immediately retires its old editable form while the next detail loads',{timeout:45000},async t=>{
@@ -15,34 +15,33 @@ test('switching a template immediately retires its old editable form while the n
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 openRuleRoute(page,'notification-execution');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('execution detail retains recovery notes during explicit list refresh and reopens with current version',{timeout:45000},async t=>{
const {page,runtime}=await fixture(t,'order-rules');runtime.orderRules.put('execution-tasks',{id:'t1',connectionId:'c1',status:'failed',version:1,error:'失败一',row:{orderNo:'ONE'}});const retried=[];
await page.route('**/api/order-execution/tasks/t1/retry',route=>{retried.push(route.request().postDataJSON());return route.fulfill({json:{ok:true}});});await openRuleRoute(page,'notification-execution');await page.getByRole('button',{name:'查看详情'}).click();await page.getByLabel('操作依据').fill('保留任务的处理依据');runtime.orderRules.put('execution-tasks',{id:'t1',connectionId:'c1',status:'failed',version:2,error:'再次失败',row:{orderNo:'ONE'}});await page.evaluate(()=>window.RecordTable.active.refresh());assert.equal(await page.getByLabel('操作依据').inputValue(),'保留任务的处理依据');await page.getByRole('button',{name:'重试失败任务',exact:true}).click();await page.getByText('操作已提交,请关闭详情并刷新列表核对实际结果。',{exact:true}).waitFor();assert.equal(retried[0].version,1);await page.getByRole('button',{name:'关闭详情'}).click();await page.waitForTimeout(400);await page.getByRole('button',{name:'查看详情'}).click();await page.getByLabel('操作依据').fill('读取最新版本再尝试');await page.getByRole('button',{name:'重试失败任务',exact:true}).click();await page.waitForFunction(()=>document.querySelector('[data-business-action] [role=alert]')?.textContent.includes('操作已提交'));assert.deepEqual(retried.map(r=>r.version),[1,2]);
});
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 openRuleRoute(page,'order-rules');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);});
test('rule durable save survives refresh failure, retains version and permits Save and Continue',{timeout:45000},async t=>{const {page}=await fixture(t,'order-rules');await openRuleRoute(page,'order-rules');let failRead=false;const versions=[];await page.route('**/api/order-rules',route=>failRead?route.fulfill({status:503,json:{error:'refresh unavailable'}}):route.continue());await page.route('**/api/order-rules/rules',async route=>{versions.push(route.request().postDataJSON().version);const response=await route.fetch();failRead=true;return route.fulfill({response});});await page.getByLabel('规则名称',{exact:true}).fill('首次持久保存');await page.getByRole('button',{name:'保存草稿',exact:true}).click();await page.getByText(/已保存.*刷新失败/).waitFor();assert.equal(await page.evaluate(()=>PageLifecycle.dirty()),false);await page.getByLabel('规则名称',{exact:true}).fill('再次持久保存');await page.locator('a[href="#system-settings"]').first().click();await page.getByRole('button',{name:'保存并继续',exact:true}).click();await page.getByRole('heading',{name:'BPM 连接',exact:true}).first().waitFor();assert.deepEqual(versions,[1,2]);});
test('rule durable save survives refresh failure, retains version and permits Save and Continue',{timeout:45000},async t=>{const {page}=await fixture(t,'order-rules');await openRuleRoute(page,'order-rules');let failRead=false;const versions=[];await page.route('**/api/order-rules?view=summary',route=>failRead?route.fulfill({status:503,json:{error:'refresh unavailable'}}):route.continue());await page.route('**/api/order-rules/rules',async route=>{versions.push(route.request().postDataJSON().version);const response=await route.fetch();failRead=true;return route.fulfill({response});});await page.getByLabel('规则名称',{exact:true}).fill('首次持久保存');await page.getByRole('button',{name:'保存草稿',exact:true}).click();await page.getByText(/已保存.*刷新失败/).waitFor();assert.equal(await page.evaluate(()=>PageLifecycle.dirty()),false);await page.getByLabel('规则名称',{exact:true}).fill('再次持久保存');await page.locator('a[href="#system-settings"]').first().click();await page.getByRole('button',{name:'保存并继续',exact:true}).click();await page.getByRole('heading',{name:'BPM 连接',exact:true}).first().waitFor();assert.deepEqual(versions,[1,2]);});
test('field mapping save retains returned version after followup GET fails',{timeout:45000},async t=>{
const {page}=await fixture(t,'order-rules');let saved=false;const versions=[];
await page.route('**/api/order-rules/fields*',route=>saved?route.fulfill({status:503,json:{error:'fields unavailable'}}):route.fulfill({json:{samples:[{id:'s1',processName:'测试流程',processVersion:'1',sample:{title:'订单号:A1'},fields:[{path:'order',label:'订单号',value:'A1'},{path:'brief',label:'摘要',value:'摘要'}]}],adapters:[]}}));
await page.route('**/api/order-rules/field-mappings/draft',route=>{const input=route.request().postDataJSON();versions.push(input.version);saved=true;return route.fulfill({json:{...input,id:'a1',version:versions.length,sources:{...input.sources,receivedAt:{type:'metadata',key:'receivedAt'}}}});});
await openRuleRoute(page,'rule-fields');await page.locator('#fm-manual').evaluate(e=>e.open=true);await page.locator('#fm-orderNo').selectOption('order');await page.getByRole('button',{name:'保存草稿',exact:true}).click();await page.getByText(/已保存.*刷新失败/).waitFor();assert.equal(await page.evaluate(()=>PageLifecycle.dirty()),false);
await page.getByText(/可选业务信息 ·/).evaluate(e=>e.parentElement.open=true);await page.locator('#fm-customer').selectOption('brief');await page.locator('a[href="#order-notifications"]').first().click();await page.getByRole('button',{name:'保存并继续',exact:true}).click();await page.getByRole('heading',{name:'本时段范围',exact:true}).waitFor();assert.deepEqual(versions,[0,1]);
await page.getByText(/可选业务信息 ·/).evaluate(e=>e.parentElement.open=true);await page.locator('#fm-customer').selectOption('brief');await page.locator('a[href="#overview"]').first().click();await page.getByRole('button',{name:'保存并继续',exact:true}).click();await page.getByRole('heading',{name:'连续业务窗口',exact:true}).waitFor();assert.deepEqual(versions,[0,1]);
});
test('category binding save retains response version without repeating committed mutation',{timeout:45000},async t=>{const {page}=await fixture(t);await mailFixture(page);let saved=false;const versions=[];await page.route('**/api/mail/templates/categories',route=>{if(route.request().method()==='GET')return saved?route.fulfill({status:503,json:{error:'bindings unavailable'}}):route.fulfill({json:{categories:[{id:'r1',name:'测试类别'}],bindings:[]}});const input=route.request().postDataJSON();versions.push(input.version);saved=true;return route.fulfill({json:{...input,version:versions.length}});});await page.getByRole('link',{name:'邮件模板',exact:true}).click();await page.locator('[data-category=r1] button').click();await page.getByText(/已保存.*刷新失败/).waitFor();await page.locator('[data-category=r1] button').click();await page.waitForFunction(()=>document.querySelector('[data-category=r1]')?.getAttribute('aria-busy')===null);assert.deepEqual(versions,[0,1]);});
test('template usage read failure never enables an alternate binding writer',{timeout:45000},async t=>{const {page}=await fixture(t);await mailFixture(page);await page.route('**/api/order-rules?view=summary',route=>route.fulfill({status:503,json:{error:'使用情况读取失败'}}));await page.getByRole('link',{name:'邮件模板',exact:true}).click();await page.locator('#content').getByText('使用情况读取失败',{exact:true}).waitFor();assert.equal(await page.getByRole('button',{name:'保存关联'}).count(),0);});
test('owner retry and persisted scan progress refresh together without replacing recovery notes',{timeout:45000},async t=>{const {page}=await fixture(t,'order-rules');await page.evaluate(async()=>{currentUser={username:'owner',role:'operator'};OrderRuleViews.configure({api,esc,formatDate,notify,user:currentUser});await renderView();});await page.route('**/api/workspace',route=>route.fulfill({json:{connections:[{id:'c1',owner:'owner',name:'owned'}]}}));let query={status:'scanning',startedAt:'2026-10-19T03:00:00Z',rowCount:2,targetCount:2,processedCount:0},blockers=['扫描尚未完成'];let tasks=[{id:'t1',status:'failed',canRetry:true,version:1,connectionId:'c1'},{id:'unknown',status:'unknown',canRetry:false},{id:'conflict',status:'blocked',conflict:true,canRetry:false}];await page.route('**/api/order-execution',route=>route.fulfill({json:{tasks,query,blockers,capabilities:{liveTodo:true}}}));await openRuleRoute(page,'notification-execution');await page.locator('[data-execution-retry=t1]').waitFor();await page.locator('[data-execution-retry=t1] textarea').fill('保留负责人的恢复依据');assert.equal(await page.locator('[data-execution-retry]').count(),1);await page.locator('#execution-query').getByText(/扫描中/).waitFor();tasks=[];query={status:'failed',error:'zero-row provider failure',targetCount:0,rowCount:0,finishedAt:'2026-10-19T03:00:10Z'};blockers=['扫描失败,冻结受阻'];await page.locator('#order-rule-refresh').click();await page.locator('#execution-query').getByText(/zero-row provider failure/).waitFor();assert.equal(await page.locator('[data-execution-retry=t1] textarea').inputValue(),'保留负责人的恢复依据');assert.match(await page.locator('#execution-capabilities').innerText(),/冻结受阻/);});
test('unknown and conflicted task details cannot offer ordinary retry',{timeout:45000},async t=>{const {page,runtime}=await fixture(t,'order-rules');runtime.orderRules.put('execution-tasks',{id:'unknown',connectionId:'c1',status:'unknown',version:1,row:{orderNo:'UNKNOWN'}});await openRuleRoute(page,'notification-execution');await page.getByRole('button',{name:'查看详情'}).click();await page.getByRole('heading',{name:'处理进度'}).waitFor();assert.equal(await page.getByRole('button',{name:'重试失败任务',exact:true}).count(),0);});
test('confirmed template and created user stay committed when list refresh fails',{timeout:45000},async t=>{const {page}=await fixture(t);await mailFixture(page);await page.route('**/api/mail/templates/t1/confirm',route=>route.fulfill({json:{id:'t1',status:'active',version:2}}));await page.getByRole('link',{name:'邮件模板',exact:true}).click();await page.locator('[data-template=t1]').click();await page.route('**/api/mail',route=>route.fulfill({status:503,json:{error:'mail list unavailable'}}));await page.getByRole('button',{name:'确认生效',exact:true}).click();await page.getByText(/模板已确认生效.*刷新失败/).waitFor();assert.equal(await page.getByRole('button',{name:'确认生效',exact:true}).count(),0);await page.getByRole('link',{name:'系统设置',exact:true}).click();await page.getByRole('link',{name:'团队账号',exact:true}).click();await page.locator('#new-username').fill('isolated-new');await page.locator('#new-password').fill('Fixture-password-123');await page.route('**/api/users',route=>route.request().method()==='POST'?route.fulfill({json:{id:'new-user'}}):route.fulfill({status:503,json:{error:'users unavailable'}}));await page.getByRole('button',{name:'创建账号',exact:true}).click();await page.getByText(/账号已创建.*刷新失败/).waitFor();assert.equal(await page.locator('#new-password').inputValue(),'');});
test('assistant settings retain persisted version after refresh failure',{timeout:45000},async t=>{const {page}=await fixture(t);await page.route('**/api/assistant',route=>route.fulfill({json:{settings:{version:1,runtimePath:'',apiBase:'',model:'',timeoutSeconds:30,dailyLimit:10}}}));await page.getByRole('link',{name:'系统设置',exact:true}).click();await page.getByRole('link',{name:'助手设置',exact:true}).click();await page.locator('#assistant-model').waitFor();const versions=[];await page.route('**/api/assistant/settings',async route=>{versions.push(route.request().postDataJSON().version);return route.fulfill({json:{version:versions.at(-1)+1}});});await page.route('**/api/assistant',route=>route.fulfill({status:503,json:{error:'assistant refresh unavailable'}}));await page.locator('#assistant-model').fill('fixture-model-one');await page.getByRole('button',{name:'保存助手设置',exact:true}).click();await page.getByText(/助手设置已保存.*刷新失败/).waitFor();await page.locator('#assistant-model').fill('fixture-model-two');await page.getByRole('button',{name:'保存助手设置',exact:true}).click();await page.waitForFunction(()=>!document.querySelector('#assistant-settings-form')?.hasAttribute('aria-busy'));assert.equal(versions[1],versions[0]+1);});
async function openRuleRoute(page,hash){
if(!await page.locator('a[href="#'+hash+'"]').count()){
const business=['order-rules','rule-fields'].includes(hash);
await page.locator('a[href="#'+(business?'business-settings':'order-notifications')+'"]').first().click();
if(hash==='notification-settings')await page.locator('a[href="#schedule"]').first().click();
}
await page.locator('a[href="#'+hash+'"]').first().click();
await page.evaluate(hash=>{const link=document.createElement('a');link.href='#'+hash;document.body.append(link);link.click();link.remove();},hash);
}
+17 -16
View File
@@ -2,37 +2,38 @@
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');
const {loadPlaywright,browserOptions}=require('../../src/platform/browser.cjs');
async function fixture(t,hash='schedule') {const dir=await fs.mkdtemp(path.join(os.tmpdir(),'web-closure-'));const runtime=await startTestDashboard({stateDir:dir});const 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(5000);await page.goto('http://127.0.0.1:'+runtime.server.address().port+'/#'+hash);await login(page);return {page,runtime};}
test('settings open directly with horizontal tabs, retired hashes redirect, and mobile stays inside viewport',{timeout:45000},async t=>{const {page}=await fixture(t,'business-settings');await page.locator('#order-rules-panel').waitFor();assert.equal(await page.locator('#settings-tabs a').count(),2);await page.getByRole('link',{name:'订单通知管理',exact:true}).click();await page.getByRole('link',{name:'发送计划',exact:true}).first().click();await page.locator('#schedule-form').waitFor();assert.equal(await page.locator('#send-mode').count(),0);await page.goBack();await page.goBack();await page.locator('#order-rules-panel').waitFor();for(const [hash,title] of [['supervisor','系统健康'],['connections','系统健康'],['notifications','分类通知规则']]){await page.evaluate(h=>location.hash=h,hash);await page.getByRole('heading',{name:title,exact:true}).first().waitFor();}await page.evaluate(()=>location.hash='system-settings');await page.getByRole('heading',{name:'BPM 连接',exact:true}).first().waitFor();assert.equal(await page.locator('#settings-tabs a').count(),7);await page.setViewportSize({width:390,height:844});assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true);assert.equal(await page.locator('#settings-tabs').evaluate(e=>getComputedStyle(e).overflowX),'auto');});
async function fixture(t,hash='schedule') {const dir=await fs.mkdtemp(path.join(os.tmpdir(),'web-closure-'));const runtime=await startTestDashboard({stateDir:dir,mailHistory:true});const 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(5000);await page.goto('http://127.0.0.1:'+runtime.server.address().port+'/#'+hash);await login(page);return {page,runtime};}
test('settings open directly with horizontal tabs, retired hashes redirect, and mobile stays inside viewport',{timeout:45000},async t=>{const {page}=await fixture(t,'business-settings');await page.locator('#order-rules-panel').waitFor();assert.equal(await page.locator('#settings-tabs a').count(),2);await page.getByRole('link',{name:'邮件批次',exact:true}).click();await page.getByRole('link',{name:'通知配置',exact:true}).first().click();await page.locator('#schedule-form').waitFor();assert.equal(await page.locator('#send-mode').count(),0);await page.goBack();await page.goBack();await page.locator('#order-rules-panel').waitFor();for(const [hash,title] of [['supervisor','系统健康'],['connections','系统健康'],['notifications','分类通知规则']]){await page.evaluate(h=>location.hash=h,hash);await page.getByRole('heading',{name:title,exact:true}).first().waitFor();}await page.evaluate(()=>location.hash='system-settings');await page.getByRole('heading',{name:'BPM 连接',exact:true}).first().waitFor();assert.equal(await page.locator('#settings-tabs a').count(),6);await page.setViewportSize({width:390,height:844});assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true);assert.equal(await page.locator('#settings-tabs').evaluate(e=>getComputedStyle(e).overflowX),'auto');});
test('dirty navigation offers stay discard save, suppresses duplicate saves and preserves failed inputs',{timeout:45000},async t=>{const {page}=await fixture(t);await page.locator('#schedule-form').waitFor();await page.locator('#time-first').fill('09:11');await page.getByRole('link',{name:'业务日历',exact:true}).first().click();await page.getByRole('dialog',{name:'未保存的修改'}).waitFor();await page.getByRole('button',{name:'留在此页',exact:true}).click();assert.equal(await page.locator('#time-first').inputValue(),'09:11');await page.getByRole('link',{name:'业务日历',exact:true}).first().click();await page.getByRole('button',{name:'放弃并继续',exact:true}).click();await page.locator('#day-form').waitFor();await page.getByRole('link',{name:'发送计划',exact:true}).first().click();await page.locator('#time-first').fill('09:12');let requests=0;await page.route('**/api/settings',async route=>{if(route.request().method()==='GET')return route.continue();requests++;await new Promise(r=>setTimeout(r,100));await route.fulfill({status:409,json:{error:'版本已更新,请核对'}});});await page.getByRole('button',{name:'保存发送计划',exact:true}).dblclick();await page.getByRole('alert').getByText('版本已更新,请核对',{exact:true}).waitFor();assert.equal(requests,1);assert.equal(await page.locator('#time-first').inputValue(),'09:12');await page.unroute('**/api/settings');await page.getByRole('link',{name:'业务日历',exact:true}).first().click();await page.getByRole('button',{name:'保存并继续',exact:true}).click();await page.locator('#day-form').waitFor();await page.getByRole('link',{name:'发送计划',exact:true}).first().click();assert.equal(await page.locator('#time-first').inputValue(),'09:12');});
test('password creation is discard-only and assistant settings have a distinct route',{timeout:45000},async t=>{const {page}=await fixture(t,'account');await page.route('**/api/assistant',route=>route.fulfill({json:{settings:{version:1,runtimePath:'',apiBase:'',model:'',timeoutSeconds:60,dailyLimit:30,enabled:false,allowActions:false},conversations:[],usage:{calls:0,limit:30}}}));await page.locator('#account-current').fill('unsaved-test-secret');await page.getByRole('link',{name:'系统设置',exact:true}).click();await page.getByRole('dialog',{name:'未保存的修改'}).waitFor();assert.equal(await page.getByRole('button',{name:'保存并继续',exact:true}).count(),0);await page.getByRole('button',{name:'放弃并继续',exact:true}).click();await page.getByRole('link',{name:'助手设置',exact:true}).click();await page.locator('#assistant-settings-form').waitFor();await page.getByRole('link',{name:'ZCode 助手',exact:true}).click();await page.locator('#assistant-compose').waitFor();assert.equal(await page.locator('#assistant-settings-form').count(),0);});
test('password creation is discard-only and assistant settings have a distinct route',{timeout:45000},async t=>{const {page}=await fixture(t,'account');await page.route('**/api/assistant',route=>route.fulfill({json:{settings:{version:1,runtimePath:'',apiBase:'',model:'',timeoutSeconds:60,dailyLimit:30,enabled:false,allowActions:false},conversations:[],usage:{calls:0,limit:30}}}));await page.locator('#account-current').fill('unsaved-test-secret');await page.getByRole('link',{name:'系统设置',exact:true}).click();await page.getByRole('dialog',{name:'未保存的修改'}).waitFor();assert.equal(await page.getByRole('button',{name:'保存并继续',exact:true}).count(),0);await page.getByRole('button',{name:'放弃并继续',exact:true}).click();await page.getByRole('link',{name:'助手设置',exact:true}).click();await page.locator('#assistant-settings-form').waitFor();await page.getByRole('link',{name:'工具',exact:true}).click();await page.getByRole('link',{name:'ZCode 助手',exact:true}).click();await page.locator('#assistant-compose').waitFor();assert.equal(await page.locator('#assistant-settings-form').count(),0);});
test('execution scan, evidence-only field draft and check emit versioned contracts',{timeout:45000},async t=>{
const {page}=await fixture(t,'order-rules'),writes=[];
const {page,runtime}=await fixture(t,'order-rules'),writes=[];runtime.orderRules.put('execution-tasks',{id:'task1',version:4,status:'failed',error:'归档失败',connectionId:'connection1',row:{orderNo:'TASK1'}});await page.route('**/api/workspace',route=>route.fulfill({json:{connections:[{id:'connection1',name:'隔离连接',owner:'admin'}]}}));
await page.route('**/api/order-execution**',async route=>{if(route.request().method()==='POST'){writes.push({url:route.request().url(),body:route.request().postDataJSON()});return route.fulfill({json:{ok:true}});}return route.fulfill({json:{tasks:[{id:'task1',version:4,status:'failed',error:'归档失败',connectionId:'connection1'}],capabilities:{liveTodo:false,pdfExport:false,automaticArchive:false}}});});
const sample={id:'sample1',processName:'订单流程',processVersion:'v7',sample:{title:'订单号:TITLE-1',serialNum:'SER1'},fields:[{path:'Order.Number',label:'订单编号',value:'A123'},{path:'Order.Text',label:'正文',value:'通知'}]};
await page.route('**/api/order-rules/fields*',route=>route.fulfill({json:{samples:[sample],adapters:[]}}));
await page.route('**/api/order-rules/field-mappings/draft',route=>{const body=route.request().postDataJSON();writes.push({url:route.request().url(),body});return route.fulfill({json:{...body,id:'mapping1',version:1,sources:{...body.sources,processName:{type:'metadata',key:'processName'}}}});});
await page.route('**/api/order-rules/field-mappings/check',route=>{const body=route.request().postDataJSON();writes.push({url:route.request().url(),body});return route.fulfill({json:{id:'check1',version:1,sampleId:'sample1',valid:true,result:{event:{orderNo:'A123',brief:'订单号:TITLE-1',titleOrders:[{orderNo:'TITLE-1'}]},filenames:[],affectedCategories:[],issues:[]}}});});
await openRuleRoute(page,'notification-execution');await page.getByText('归档失败',{exact:true}).waitFor();await page.getByLabel('扫描连接',{exact:true}).selectOption('connection1');await page.evaluate(()=>{crypto.randomUUID=undefined;});await page.getByRole('button',{name:'扫描待办',exact:true}).click();await page.getByText('扫描请求已提交,请核对任务状态。',{exact:true}).waitFor();assert.equal(writes[0].body.connectionId,'connection1');assert.match(writes[0].body.idempotencyKey,/^[a-z0-9-]+$/i);
await page.getByLabel('任务重试依据',{exact:true}).fill('已恢复隔离归档目录');await page.getByRole('button',{name:'重试失败任务',exact:true}).click();await page.getByText('重试请求已提交,请核对任务状态。',{exact:true}).waitFor();assert.equal(writes[1].body.version,4);
await openRuleRoute(page,'notification-execution');await page.getByText('归档失败',{exact:true}).waitFor();await page.getByLabel('扫描连接',{exact:true}).selectOption('connection1');await page.evaluate(()=>{crypto.randomUUID=undefined;});await page.getByRole('button',{name:'扫描并处理订单',exact:true}).click();await page.getByText('扫描已完成,请核对订单中心。',{exact:true}).waitFor();assert.equal(writes[0].body.connectionId,'connection1');assert.match(writes[0].body.idempotencyKey,/^[a-z0-9-]+$/i);
await page.getByRole('button',{name:'查看详情',exact:true}).first().click();await page.getByLabel('操作依据',{exact:true}).fill('已恢复隔离归档目录');await page.getByRole('button',{name:'重试失败任务',exact:true}).click();await page.getByText('操作已提交,请关闭详情并刷新列表核对实际结果。',{exact:true}).waitFor();assert.equal(writes[1].body.version,4);await page.getByRole('button',{name:'关闭详情',exact:true}).click();await page.waitForTimeout(400);
await openRuleRoute(page,'rule-fields');await page.locator('#fm-manual').evaluate(e=>e.open=true);await page.locator('#fm-orderNo').selectOption('Order.Number');assert.equal(await page.locator('[data-fm-binding] input[type=text]').count(),0);await page.getByRole('button',{name:'保存草稿',exact:true}).click();await page.getByText('字段对应草稿已保存。',{exact:true}).waitFor();const draft=writes[2].body;assert.deepEqual({...draft,idempotencyKey:undefined},{sampleId:'sample1',processName:'订单流程',processVersion:'v7',sources:{orderNo:{type:'form',path:'Order.Number'},brief:{type:'title'}},version:0,idempotencyKey:undefined});assert.equal(typeof draft.idempotencyKey,'string');assert.equal(await page.evaluate(()=>PageLifecycle.dirty()),false);
await page.getByRole('button',{name:'检查识别结果',exact:true}).click();await page.locator('#fm-result .fm-title-order').getByText('订单号:TITLE-1',{exact:true}).waitFor();assert.deepEqual({...writes[3].body,idempotencyKey:undefined},{id:'mapping1',version:1,sampleId:'sample1',idempotencyKey:undefined});assert.equal(await page.locator('#fm-activate').isDisabled(),true);
});
test('calendar staged changes save through navigation and rule tab changes use the same guard',{timeout:45000},async t=>{const {page,runtime}=await fixture(t,'calendar');await page.route('**/api/order-rules/fields*',route=>route.fulfill({json:{samples:[],adapters:[]}}));await page.getByLabel('安排说明',{exact:true}).fill('隔离测试调休日');await page.getByRole('button',{name:'应用到此日期',exact:true}).click();await page.getByRole('link',{name:'发送计划',exact:true}).first().click();await page.getByRole('button',{name:'保存并继续',exact:true}).click();await page.locator('#schedule-form').waitFor();assert.equal(runtime.workspace.snapshot().calendar.overrides[0].note,'隔离测试调休日');await openRuleRoute(page,'order-rules');await page.getByLabel('规则名称',{exact:true}).fill('尚未保存规则');await openRuleRoute(page,'rule-fields');await page.getByRole('button',{name:'留在此页',exact:true}).click();assert.equal(await page.getByLabel('规则名称',{exact:true}).inputValue(),'尚未保存规则');assert.equal(await page.evaluate(()=>{const e=new Event('beforeunload',{cancelable:true});window.dispatchEvent(e);return e.defaultPrevented;}),true);await openRuleRoute(page,'rule-fields');await page.getByRole('button',{name:'放弃并继续',exact:true}).click();await page.waitForFunction(()=>location.hash==='#rule-fields');await page.locator('#fm-editor').waitFor();});
test('manual resend is only offered for failed batches and sends frozen identity with version and reason',{timeout:45000},async t=>{const {page}=await fixture(t,'order-rules');const original=await page.request.get(new URL('/api/order-rules',page.url()).href);const snapshot=await original.json();snapshot.batches=[{id:'failed1',version:8,status:'failed',categoryId:'test',subject:'隔离失败批次',to:['frozen@example.test'],orderNos:['A1']},{id:'unknown1',version:1,status:'unknown',categoryId:'test',subject:'待核验批次',to:[],orderNos:[]}];let body;await page.route('**/api/order-rules',route=>route.fulfill({json:snapshot}));await page.route('**/api/order-rules/batches/failed1/resend',route=>{body=route.request().postDataJSON();return route.fulfill({json:{ok:true}});});await openRuleRoute(page,'notification-history');await page.locator('[data-rule-resend]').waitFor();assert.equal(await page.locator('[data-rule-resend]').count(),1);await page.getByLabel('人工补发依据',{exact:true}).fill('已确认原发送明确失败');await page.getByRole('button',{name:'人工补发此失败批次',exact:true}).click();await page.getByText('人工补发请求已提交,请核对发送记录。',{exact:true}).waitFor();assert.equal(body.version,8);assert.equal(body.note,'已确认原发送明确失败');assert.equal(typeof body.idempotencyKey,'string');assert.equal(Object.hasOwn(body,'to'),false);});
test('manual resend uses frozen batch identity and unknown offers verification only',{timeout:45000},async t=>{
const {page,runtime}=await fixture(t,'order-rules');for(const [id,status]of [['failed1','failed'],['unknown1','unknown']])runtime.orderRules.put('batches',{id,version:8,status,subject:id,orderIds:[],to:['frozen@example.test'],cc:[]});let body;
await page.route('**/api/order-rules/batches/failed1/resend',route=>{body=route.request().postDataJSON();return route.fulfill({json:{ok:true}});});await openRuleRoute(page,'notification-history');await page.getByRole('button',{name:'查看详情'}).first().click();await page.locator('[data-business-action=resend]').waitFor();await page.getByLabel('操作依据').fill('已确认原发送明确失败');await page.getByRole('button',{name:'人工补发原冻结批次',exact:true}).click();await page.getByText('操作已提交,请关闭详情并刷新列表核对实际结果。',{exact:true}).waitFor();assert.equal(body.version,8);assert.equal(body.note,'已确认原发送明确失败');assert.equal(typeof body.idempotencyKey,'string');assert.equal(Object.hasOwn(body,'to'),false);await page.getByRole('button',{name:'关闭详情'}).click();await page.waitForTimeout(400);await page.getByRole('button',{name:'查看详情'}).nth(1).click();await page.locator('[data-business-action=resolve]').waitFor();assert.equal(await page.locator('[data-business-action=resend]').count(),0);
});
test('late page responses cannot overwrite new form and dirty browser history keeps current inputs',{timeout:45000},async t=>{const {page}=await fixture(t,'calendar');await page.locator('#day-form').waitFor();let release;const gate=new Promise(r=>release=r);await page.route('**/api/settings',async route=>{if(route.request().method()!=='GET')return route.continue();await gate;return route.continue();});await page.getByRole('link',{name:'发送计划',exact:true}).first().click();await page.getByRole('link',{name:'业务日历',exact:true}).first().click();release();await page.locator('#day-form').waitFor();assert.equal(await page.locator('#schedule-form').count(),0);await page.unroute('**/api/settings');await page.getByRole('link',{name:'发送计划',exact:true}).first().click();await page.locator('#time-first').fill('10:13');await page.goBack();await page.getByRole('button',{name:'留在此页',exact:true}).click();assert.match(page.url(),/#schedule$/);assert.equal(await page.locator('#time-first').inputValue(),'10:13');});
test('write timeout queries state without resubmission and retains uncertain inputs',{timeout:45000},async t=>{const {page}=await fixture(t,'schedule');await page.locator('#schedule-form').waitFor();await page.clock.install();let posts=0,gets=0;await page.route('**/api/settings',async route=>{if(route.request().method()==='GET'){gets++;return route.continue();}posts++;await route.abort('timedout');});await page.locator('#time-first').fill('10:14');await page.getByRole('button',{name:'保存发送计划',exact:true}).click();await page.locator('#operation-uncertain').waitFor();assert.equal(posts,1);await page.waitForFunction(()=>document.querySelector('#flash')?.textContent.includes('已查询最新状态'));assert.equal(gets,1);assert.equal(await page.locator('#time-first').inputValue(),'10:14');});
test('record history opens legacy notifications read-only after retired address redirects',{timeout:45000},async t=>{const {page}=await fixture(t,'notifications');await page.getByRole('heading',{name:'分类通知规则',exact:true}).waitFor();assert.equal(await page.locator('#notification-settings').count(),0);await page.route('**/api/notifications',route=>route.fulfill({json:{items:[{sourceId:'OLD1',industry:'原分类',subject:'历史通知',brief:'原正文',status:'sent'}],batches:[{id:'old-batch',industry:'原分类',subject:'历史批次',status:'sent',to:['old@example.test']}]}}));await page.getByRole('link',{name:'订单与导出记录',exact:true}).click();await page.getByRole('button',{name:'查看旧通知历史(只读)',exact:true}).click();await page.getByText('历史通知',{exact:true}).waitFor();assert.equal(await page.locator('#legacy-notification-history form').count(),0);});
test('record history opens legacy notifications read-only after retired address redirects',{timeout:45000},async t=>{const {page}=await fixture(t,'notifications');await page.getByRole('heading',{name:'分类通知规则',exact:true}).waitFor();assert.equal(await page.locator('#notification-settings').count(),0);await page.route('**/api/notifications',route=>route.fulfill({json:{items:[{sourceId:'OLD1',industry:'原分类',subject:'历史通知',brief:'原正文',status:'sent'}],batches:[{id:'old-batch',industry:'原分类',subject:'历史批次',status:'sent',to:['old@example.test']}]}}));await page.getByRole('link',{name:'工具',exact:true}).click();await page.getByRole('button',{name:'查看旧通知历史(只读)',exact:true}).click();await page.getByText('历史通知',{exact:true}).waitFor();assert.equal(await page.locator('#legacy-notification-history form').count(),0);});
test('a delayed execution response cannot replace the selected field directory',{timeout:45000},async t=>{const {page}=await fixture(t,'order-rules');let release;const gate=new Promise(r=>release=r);await page.route('**/api/order-execution',async route=>{await gate;return route.fulfill({json:{tasks:[],capabilities:{},fields:{samples:[],adapters:[]}}});});await page.route('**/api/order-rules/fields*',route=>route.fulfill({json:{samples:[],adapters:[]}}));await openRuleRoute(page,'notification-execution');await openRuleRoute(page,'rule-fields');await page.locator('#fm-editor').waitFor();release();await page.waitForTimeout(300);assert.equal(await page.locator('#fm-editor').count(),1);assert.equal(await page.locator('#execution-scan').count(),0);});
test('operator scans but cannot configure fields or resend, viewer has no scan action',{timeout:45000},async t=>{const {page,runtime}=await fixture(t,'order-rules');const base=new URL(page.url()).origin;for(const role of ['operator','viewer'])runtime.store.addUser({username:role,password:'Test-password-123',role},'admin');for(const role of ['operator','viewer']){const context=await page.context().browser().newContext(),member=await context.newPage();member.setDefaultTimeout(5000);await member.route('**/api/order-execution',route=>route.fulfill({json:{tasks:[{id:'x',version:1,status:'failed'}],capabilities:{},fields:{samples:[],adapters:[]}}}));await member.route('**/api/order-rules/fields*',route=>route.fulfill({json:{samples:[],adapters:[]}}));await member.goto(base+'/#order-rules');await member.getByLabel('账号',{exact:true}).fill(role);await member.getByLabel('密码',{exact:true}).fill('Test-password-123');await member.getByRole('button',{name:'登录',exact:true}).click();await openRuleRoute(member,'notification-execution');await member.getByRole('heading',{name:'持久执行任务',exact:true}).waitFor();assert.equal(await member.getByRole('button',{name:'扫描待办',exact:true}).count(),role==='operator'?1:0);assert.equal(await member.getByRole('button',{name:'重试失败任务',exact:true}).count(),0);await openRuleRoute(member,'rule-fields');await member.locator('#fm-editor').waitFor();assert.equal(await member.getByRole('button',{name:'保存草稿',exact:true}).count(),0);await context.close();}});
test('operator scans but cannot configure fields or resend, viewer has no scan action',{timeout:45000},async t=>{const {page,runtime}=await fixture(t,'order-rules');const base=new URL(page.url()).origin;for(const role of ['operator','viewer'])runtime.store.addUser({username:role,password:'Test-password-123',role},'admin');for(const role of ['operator','viewer']){const context=await page.context().browser().newContext(),member=await context.newPage();member.setDefaultTimeout(5000);await member.route('**/api/order-execution',route=>route.fulfill({json:{tasks:[{id:'x',version:1,status:'failed'}],capabilities:{},fields:{samples:[],adapters:[]}}}));await member.route('**/api/order-rules/fields*',route=>route.fulfill({json:{samples:[],adapters:[]}}));await member.goto(base+'/#order-rules');await member.getByLabel('账号',{exact:true}).fill(role);await member.getByLabel('密码',{exact:true}).fill('Test-password-123');await member.getByRole('button',{name:'登录',exact:true}).click();await openRuleRoute(member,'notification-execution');await member.getByRole('heading',{name:'订单中心',exact:true}).first().waitFor();assert.equal(await member.getByRole('button',{name:'扫描并处理订单',exact:true}).count(),role==='operator'?1:0);assert.equal(await member.getByRole('button',{name:'重试失败任务',exact:true}).count(),0);await openRuleRoute(member,'rule-fields');await member.locator('#fm-editor').waitFor();assert.equal(await member.getByRole('button',{name:'保存草稿',exact:true}).count(),0);await context.close();}});
test('staying after browser Back preserves history so a second Back can discard to its original page',{timeout:45000},async t=>{const {page}=await fixture(t,'calendar');await page.locator('#day-form').waitFor();await page.getByRole('link',{name:'发送计划',exact:true}).first().click();await page.locator('#time-first').fill('11:17');await page.goBack();await page.getByRole('button',{name:'留在此页',exact:true}).click();await page.goBack();await page.getByRole('button',{name:'放弃并继续',exact:true}).click();await page.locator('#day-form').waitFor();await page.goForward();await page.locator('#schedule-form').waitFor();});
test('template categories use explicit versioned bindings and keep recipient editing in rules',{timeout:45000},async t=>{const {page}=await fixture(t,'schedule');const bindings=[];let saved;await page.route('**/api/mail',route=>route.fulfill({json:{channels:[],templates:[{id:'t1',status:'active',subject:'已确认模板',scope:'原产品线',attachmentCount:0}],receipts:[],sends:[]}}));await page.route('**/api/mail/templates/categories',route=>{if(route.request().method()==='POST'){saved=route.request().postDataJSON();bindings.push({...saved,version:1});return route.fulfill({json:{ok:true}});}return route.fulfill({json:{categories:[{id:'cat1',name:'Excel 分类一'}],bindings}});});await page.getByRole('link',{name:'邮件模板',exact:true}).click();await page.getByLabel('Excel 分类一',{exact:true}).selectOption('t1');assert.equal(await page.locator('#group-editor,#save-groups').count(),0);await page.getByRole('button',{name:'保存关联',exact:true}).click();await page.getByText('类别模板关联已保存。',{exact:true}).waitFor();assert.deepEqual(saved,{categoryId:'cat1',templateId:'t1',version:0});await page.getByLabel('Excel 分类一',{exact:true}).selectOption('');await page.getByRole('button',{name:'保存关联',exact:true}).click();await page.getByText('类别模板关联已保存。',{exact:true}).waitFor();assert.equal(saved.templateId,'');assert.equal(saved.version,1);});
test('template categories show effective published usage without a second binding writer',{timeout:45000},async t=>{
const {page}=await fixture(t,'schedule');let writes=0;await page.route('**/api/mail',route=>route.fulfill({json:{channels:[],templates:[],receipts:[],sends:[]}}));await page.route('**/api/mail/templates/categories',route=>{writes++;return route.fulfill({json:{}});});await page.getByRole('link',{name:'邮件模板',exact:true}).click();await page.getByRole('heading',{name:'有效使用情况(只读)'}).waitFor();assert.equal(await page.locator('[data-category] form').count(),0);assert.equal(await page.getByRole('button',{name:'保存关联'}).count(),0);assert.equal(writes,0);
});
async function openRuleRoute(page,hash){
if(!await page.locator('a[href="#'+hash+'"]').count()){
const business=['order-rules','rule-fields'].includes(hash);
await page.locator('a[href="#'+(business?'business-settings':'order-notifications')+'"]').first().click();
if(hash==='notification-settings')await page.locator('a[href="#schedule"]').first().click();
}
await page.locator('a[href="#'+hash+'"]').first().click();
await page.evaluate(hash=>{const link=document.createElement('a');link.href='#'+hash;document.body.append(link);link.click();link.remove();},hash);
}
+7 -1
View File
@@ -259,7 +259,7 @@ test('narrow screens keep the frame inside the page and native typing forwards t
test('refresh and logout release BPM control before rendering or dropping authentication',async()=>{
const vm=require('node:vm'),events=[],elements=new Map();
const element=id=>{if(!elements.has(id))elements.set(id,{innerHTML:'',textContent:'',classList:{remove(){}},querySelector(){return {disabled:false};}});return elements.get(id);};
const context=vm.createContext({Intl,setTimeout,clearInterval,location:{hash:'#overview'},history:{replaceState(){}},document:{querySelector:element,querySelectorAll:()=>[],addEventListener(){}},window:{addEventListener(){},PageLifecycle:{guard:fn=>fn(),dispose:async()=>{},attach(){},bind(){}},AppNavigation:{primary:[],resolve:id=>id,sectionFor:()=>null,renderTabs(){},isConfiguration:()=>false},BpmLogin:{dispose:async()=>events.push('release')},WorkspaceViews:{overview:async()=>events.push('render')}}});
const context=vm.createContext({Intl,setTimeout,clearInterval,location:{hash:'#overview'},history:{replaceState(){}},document:{querySelector:element,querySelectorAll:()=>[],addEventListener(){}},window:{addEventListener(){},PageLifecycle:{guard:fn=>fn(),dispose:async()=>{},attach(){},bind(){}},AppNavigation:{primary:[],resolve:id=>id,sectionFor:()=>null,renderTabs(){},isConfiguration:()=>false},BpmLogin:{dispose:async()=>events.push('release')},OrderNotificationViews:{render:async()=>events.push('render')}}});
const source=fs.readFileSync(path.join(__dirname,'../../web/app.js'),'utf8').replace(/boot\(\)\.catch[\s\S]*$/,'');
vm.runInContext(fs.readFileSync(path.join(__dirname,'../../web/modules/records/state.js'),'utf8'),context);
vm.runInContext(source,context);
@@ -312,3 +312,9 @@ test('a delayed background snapshot cannot resurrect a connection after deletion
const connection={id:'off',name:'旧连接',owner:'alice',status:'disabled',version:1},f=await fixture(t,{user:{username:'admin',role:'admin'},connections:[connection]});let arrive,release;const arrived=new Promise(r=>arrive=r),gate=new Promise(r=>release=r);
await f.page.route('**/api/workspace',async route=>{arrive();await gate;await route.fulfill({json:{connections:[connection],capabilities:{remoteLogin:true}}});});await arrived;f.page.once('dialog',dialog=>dialog.accept());await f.page.getByRole('button',{name:'删除',exact:true}).click();await f.page.getByText('连接已删除。',{exact:true}).waitFor();const response=f.page.waitForResponse(r=>r.url().endsWith('/api/workspace'));release();await response;await f.page.waitForTimeout(100);assert.equal(await f.page.getByRole('heading',{name:'旧连接',exact:true}).count(),0);
});
test('source read state and local delivery are separate and handover uses connection version',async t=>{
const connection={id:'one',name:'隔离监听连接',owner:'boss',version:7,status:'connected',monitoring:{status:'listening',nextReconcileAt:'2026-10-21T10:00:00Z',sources:{todo:{status:'healthy',lastSuccessAt:'2026-10-21T09:00:00Z'},inform:{status:'failed',lastFailureAt:'2026-10-21T09:01:00Z',retryAt:'2026-10-21T09:02:00Z'}},delivery:{status:'retrying',pending:2,message:'隔离本地投递失败'}}};
const f=await fixture(t,{user:{username:'boss',role:'admin'},connections:[connection]});await f.page.getByText(/待办源读取 · healthy/).waitFor();await f.page.getByText(/通知源读取 · failed/).waitFor();await f.page.getByText(/本地执行器投递 · retrying · 待交付 2/).waitFor();let submitted;
await f.page.route('**/api/connections/one/owner',route=>{submitted=route.request().postDataJSON();return route.fulfill({json:{connection:{...connection,owner:'alice',status:'disabled',version:8},cleanupPending:false}});});
await f.page.locator('[data-owner-transfer] select').selectOption('alice');await f.page.getByRole('button',{name:'确认转交',exact:true}).click();await f.page.getByRole('button',{name:'启用连接',exact:true}).waitFor();assert.deepEqual(submitted,{version:7,owner:'alice'});assert.match(await f.page.locator('[data-bpm-feedback]').innerText(),/连接已暂停/);
});
+2 -2
View File
@@ -37,11 +37,11 @@ for(const role of ['operator','viewer'])test(role+' sees readonly bindings and n
const page=await setup(t,role);assert.equal(await page.locator('#fm-orderNo').isDisabled(),true);assert.equal(await page.locator('#fm-orderNo').inputValue(),'form.order');assert.match(await page.locator('#fm-version-state').innerText(),/生效 v4/);assert.equal(await page.getByRole('button',{name:'保存草稿',exact:true}).count(),0);assert.equal(await page.evaluate(()=>calls.some(c=>c.url==='/workspace'||c.body&&!c.url.endsWith('/propose'))),false);
});
test('sample capture uses listed row identity, guards dirty input, and can fetch a new list after successful reads',async t=>{
const page=await setup(t);await page.locator('#fm-orderNo').selectOption('form.order');await page.getByText('从 BPM 待办采集样本',{exact:true}).click();await page.locator('#fm-connection').selectOption('c1');await page.getByRole('button',{name:'读取待办列表',exact:true}).click();await page.locator('[data-fm-capture]').waitFor();await page.getByRole('button',{name:'读取待办列表',exact:true}).click();await page.waitForFunction(()=>calls.filter(c=>c.url.endsWith('/field-samples/list')).length===2);const keys=await page.evaluate(()=>calls.filter(c=>c.url.endsWith('/field-samples/list')).map(c=>c.body.idempotencyKey));assert.notEqual(keys[0],keys[1]);await page.evaluate(()=>window.failCapture=true);await page.locator('[data-fm-capture]').click();await page.getByRole('button',{name:'放弃并继续',exact:true}).click();await page.getByText('采集断线',{exact:true}).waitFor();assert.equal(await page.locator('#fm-orderNo').inputValue(),'form.order');await page.evaluate(()=>window.failCapture=false);await page.locator('[data-fm-capture]').click();await page.getByRole('button',{name:'放弃并继续',exact:true}).click();await page.getByText('真实样本已采集,可选择样本核对字段。',{exact:true}).waitFor();assert.equal(await page.locator('#fm-sample').inputValue(),'s2');const body=await page.evaluate(()=>calls.find(c=>c.url.endsWith('/field-samples/capture')).body);assert.equal(body.connectionId,'c1');assert.equal(body.listId,'list-1');assert.equal(body.rowId,'row-1');const captureKeys=await page.evaluate(()=>calls.filter(c=>c.url.endsWith('/field-samples/capture')).map(c=>c.body.idempotencyKey));assert.notEqual(captureKeys[0],captureKeys[1]);assert.equal(await page.evaluate(()=>calls.some(c=>/order-execution|adapters|pdf|mail/.test(c.url))),false);
const page=await setup(t);await page.locator('#fm-orderNo').selectOption('form.order');await page.getByText('从 BPM 选择',{exact:true}).click();await page.locator('[data-picker=connection]').selectOption('c1');await page.getByRole('button',{name:'读取待办列表',exact:true}).click();await page.locator('[data-picker-capture]').waitFor();await page.getByRole('button',{name:'读取待办列表',exact:true}).click();await page.waitForFunction(()=>calls.filter(c=>c.url.endsWith('/field-samples/list')).length===2);const keys=await page.evaluate(()=>calls.filter(c=>c.url.endsWith('/field-samples/list')).map(c=>c.body.idempotencyKey));assert.notEqual(keys[0],keys[1]);await page.evaluate(()=>window.failCapture=true);await page.locator('[data-picker-capture]').click();await page.getByRole('button',{name:'放弃并继续',exact:true}).click();await page.getByText('采集断线',{exact:true}).waitFor();assert.equal(await page.locator('#fm-orderNo').inputValue(),'form.order');await page.evaluate(()=>window.failCapture=false);await page.locator('[data-picker-capture]').click();await page.getByRole('button',{name:'放弃并继续',exact:true}).click();await page.waitForFunction(()=>document.querySelector('#fm-sample')?.value==='s2');assert.equal(await page.locator('#fm-sample').inputValue(),'s2');const body=await page.evaluate(()=>calls.find(c=>c.url.endsWith('/field-samples/capture')).body);assert.equal(body.connectionId,'c1');assert.equal(body.listId,'list-1');assert.equal(body.rowId,'row-1');const captureKeys=await page.evaluate(()=>calls.filter(c=>c.url.endsWith('/field-samples/capture')).map(c=>c.body.idempotencyKey));assert.notEqual(captureKeys[0],captureKeys[1]);assert.equal(await page.evaluate(()=>calls.some(c=>/order-execution|adapters|pdf|mail/.test(c.url))),false);
});
test('a definite sample-list failure can be retried with a new key while an uncertain attempt retains its key',async t=>{
const page=await setup(t);await page.getByText('从 BPM 待办采集样本',{exact:true}).click();await page.locator('#fm-connection').selectOption('c1');await page.evaluate(()=>window.failList=true);await page.getByRole('button',{name:'读取待办列表',exact:true}).click();await page.getByText('列表读取失败',{exact:true}).waitFor();await page.evaluate(()=>{window.failList=false;window.uncertainList=true;});await page.getByRole('button',{name:'读取待办列表',exact:true}).click();await page.getByText('结果待核实',{exact:true}).waitFor();await page.evaluate(()=>window.uncertainList=false);await page.getByRole('button',{name:'读取待办列表',exact:true}).click();await page.locator('[data-fm-capture]').waitFor();const keys=await page.evaluate(()=>calls.filter(c=>c.url.endsWith('/field-samples/list')).map(c=>c.body.idempotencyKey));assert.notEqual(keys[0],keys[1]);assert.equal(keys[1],keys[2]);
const page=await setup(t);await page.getByText('从 BPM 选择',{exact:true}).click();await page.locator('[data-picker=connection]').selectOption('c1');await page.evaluate(()=>window.failList=true);await page.getByRole('button',{name:'读取待办列表',exact:true}).click();await page.getByText('列表读取失败',{exact:true}).waitFor();await page.evaluate(()=>{window.failList=false;window.uncertainList=true;});await page.getByRole('button',{name:'读取待办列表',exact:true}).click();await page.getByText('结果待核实',{exact:true}).waitFor();await page.evaluate(()=>window.uncertainList=false);await page.getByRole('button',{name:'读取待办列表',exact:true}).click();await page.locator('[data-picker-capture]').waitFor();const keys=await page.evaluate(()=>calls.filter(c=>c.url.endsWith('/field-samples/list')).map(c=>c.body.idempotencyKey));assert.notEqual(keys[0],keys[1]);assert.equal(keys[1],keys[2]);
});
test('legacy active-only mappings load field paths and start an independent draft revision that survives refresh failures',async t=>{
const page=await setup(t,'admin',true);assert.equal(await page.locator('#fm-orderNo').inputValue(),'form.order');assert.equal(await page.locator('#fm-quantity').inputValue(),'form.qty');assert.match(await page.locator('#fm-version-state').innerText(),/生效 v9/);assert.equal(await page.locator('#fm-check').isDisabled(),true);await page.evaluate(()=>window.failRefresh=true);await page.getByRole('button',{name:'保存草稿',exact:true}).click();await page.getByText(/刷新失败/).waitFor();assert.equal(await page.evaluate(()=>PageLifecycle.dirty()),false);await page.locator('[data-fm-version="1"]').click();await page.locator('[data-fm-version="0"]').click();await page.locator('#fm-manual').evaluate(e=>e.open=true);await page.locator('#fm-quantity').selectOption('');await page.getByRole('button',{name:'保存草稿',exact:true}).click();await page.waitForFunction(()=>calls.filter(c=>c.url.endsWith('/draft')).length===2&&!document.querySelector('#fm-save').disabled);const writes=await page.evaluate(()=>calls.filter(c=>c.url.endsWith('/draft')).map(c=>c.body));assert.deepEqual(writes.map(body=>body.version),[0,1]);assert.deepEqual(writes[0].sources,{brief:{type:'title'},orderNo:{type:'form',path:'form.order'},quantity:{type:'form',path:'form.qty'}});assert.equal(await page.evaluate(()=>PageLifecycle.dirty()),false);assert.match(await page.locator('#fm-version-state').innerText(),/草稿 v2/);
+54
View File
@@ -0,0 +1,54 @@
'use strict';
const test=require('node:test'),assert=require('node:assert/strict');
const {queryOrders,queryBatches,orderDetail,batchDetail,readOrderFile}=require('../../src/modules/order-rules/query.cjs');
function fixture(){
const rows=Array.from({length:83},(_,i)=>({id:'o'+i,status:'pending',categoryId:'cat',event:{connectionId:'a',orderNo:'NO'+i,receivedAt:'2026-10-20T10:00:00Z',fields:{secret:'raw'}},sample:{connectionId:'a',fields:{secret:'raw'}}}));
rows.push({id:'foreign',sample:{connectionId:'b'},event:{orderNo:'PRIVATE'},status:'blocked'});
const records={orders:rows,batches:[{id:'old',orderIds:['o0'],status:'prepared',windowStart:'2020-01-01',text:'frozen'},{id:'mixed',orderIds:['o0','foreign'],status:'unknown',text:'SECRET'}],'execution-tasks':[], 'business-issues':[]};
const store={all:k=>records[k]||[],get:(k,id)=>(records[k]||[]).find(r=>r.id===id),queryRevision:()=>1};
return {orderRules:store,workspace:{recordSources:()=>[{id:'a',owner:'alice'},{id:'b',owner:'bob'}]},execution:{archive:{read:async()=>Buffer.from('%PDF-x')}}};
}
const user={username:'alice',role:'operator'};
test('authorized queries paginate to actual last page, filter and reject invalid enums',()=>{
const c=fixture(),result=queryOrders(c,{page:999,pageSize:25},user);assert.equal(result.page,4);assert.equal(result.total,83);assert.equal(result.items.length,8);assert.equal(result.from,76);assert.equal(result.to,83);
assert.equal(JSON.stringify(result).includes('raw'),false);
assert.equal(queryOrders(c,{q:'PRIVATE'},user).total,0);assert.equal(queryOrders(c,{q:'none',page:99},user).page,1);
assert.throws(()=>queryOrders(c,{status:'made-up'},user));assert.throws(()=>queryBatches(c,{scope:'made-up'},user));
});
test('old prepared remains active, mixed source evidence is denied and permissions are rechecked',()=>{
const c=fixture();assert.deepEqual(queryBatches(c,{scope:'active'},user).items.map(b=>b.id),['old']);assert.throws(()=>orderDetail(c,'foreign',user));assert.throws(()=>batchDetail(c,'mixed',user));
c.workspace.recordSources=()=>[{id:'a',owner:'bob'}];assert.equal(queryOrders(c,{},user).total,0);
});
test('task-only blocked work remains visible and private raw fields never leave detail',()=>{
const c=fixture();c.orderRules.all('execution-tasks').push({id:'task',connectionId:'a',status:'blocked',row:{orderNo:'MISSED',fields:{secret:'raw'}},missedWindow:{start:'2020'}});
assert.equal(queryOrders(c,{},user).total,84);assert.equal(orderDetail(c,'task:task',user).executionTask.id,'task');assert.equal(JSON.stringify(orderDetail(c,'o0',user)).includes('raw'),false);
});
test('file endpoint reauthorizes and validates bytes against durable evidence',async()=>{
const c=fixture(),bytes=Buffer.from('%PDF-x');c.orderRules.get('orders','o0').archive={files:[{name:'a.pdf',path:'server-only',size:bytes.length,sha256:require('node:crypto').createHash('sha256').update(bytes).digest('hex')}]};
assert.deepEqual((await readOrderFile(c,'o0',0,user)).bytes,bytes);c.execution.archive.read=async()=>Buffer.from('tampered');await assert.rejects(()=>readOrderFile(c,'o0',0,user));await assert.rejects(()=>readOrderFile(c,'foreign',0,user));
});
test('batch pagination covers more than three pages and scope all retains completed history',()=>{
const c=fixture();for(let i=0;i<85;i++)c.orderRules.all('batches').push({id:'b'+i,orderIds:['o0'],status:i===0?'sent':'prepared',subject:'Batch '+i});
const active=queryBatches(c,{page:999,pageSize:25},user);assert.equal(active.page,4);assert.equal(active.total,85);assert.equal(active.items.length,10);assert.equal(queryBatches(c,{scope:'all'},user).total,86);
});
test('HTTP query routing rejects missing services, invalid parameters and malformed encoding',async()=>{
const {orderRuleQueryApi}=require('../../src/modules/order-rules/query-api.cjs');const c=fixture(),invoke=(route,extra={})=>orderRuleQueryApi({...c,user,route,method:'GET',url:new URL(route,'http://localhost'),reply(){},...extra});
await assert.rejects(()=>invoke('/api/order-rules/orders?unused=1',{route:'/api/order-rules/orders'}),e=>e.status===400||e.statusCode===400);
await assert.rejects(()=>invoke('/api/order-rules/orders/%ZZ'),e=>e.status===400||e.statusCode===400);
await assert.rejects(()=>invoke('/api/order-rules/orders',{orderRules:null}),e=>e.status===503||e.statusCode===503);
assert.equal(await invoke('/api/unrelated'),false);
});
test('date filters use the displayed Beijing business day rather than UTC midnight',()=>{
const c=fixture();c.orderRules.all('orders').push({id:'night',status:'pending',sample:{connectionId:'a'},event:{connectionId:'a',orderNo:'NIGHT',receivedAt:'2026-10-20T16:30:00Z'}});
assert.equal(queryOrders(c,{from:'2026-10-21',to:'2026-10-21'},user).total,1);
assert.equal(queryOrders(c,{from:'2026-10-20',to:'2026-10-20'},user).total,83);
});
test('batch date range follows the frozen business window, including old prepared work',()=>{
const c=fixture(),batch=c.orderRules.get('batches','old');batch.createdAt='2026-10-21T00:00:00Z';batch.window={start:'2020-01-01T00:00:00Z',end:'2020-01-01T03:00:00Z'};
assert.equal(queryBatches(c,{from:'2020-01-01',to:'2020-01-01'},user).total,1);
});
test('order list and detail select the same latest live revision with genuine previous evidence',()=>{
const c=fixture(),tasks=c.orderRules.all('execution-tasks');tasks.push({id:'original',connectionId:'a',orderId:'o0',row:{revision:'1',orderNo:'OLD'},status:'archived',createdAt:'2026-10-20T00:00:00Z'},{id:'incoming',connectionId:'a',orderId:'o0',previousTaskId:'original',conflict:true,conflictRow:{revision:'2',orderNo:'NEW'},row:{revision:'2',orderNo:'NEW'},status:'blocked',createdAt:'2026-10-21T00:00:00Z'});
const row=queryOrders(c,{q:'o0'},user).items.find(i=>i.id==='o0'),detail=orderDetail(c,'o0',user);assert.equal(row.executionTaskId,'incoming');assert.equal(detail.executionTask.id,row.executionTaskId);assert.equal(detail.executionTask.conflict,true);assert.equal(detail.executionTask.revisionEvidence.previous.revision,'1');assert.equal(detail.executionTask.revisionEvidence.incoming.revision,'2');
});
+7 -12
View File
@@ -2,17 +2,12 @@
const test=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs/promises'),path=require('node:path');
const {loadPlaywright,browserOptions}=require('../../src/platform/browser.cjs');
async function setup(t,section,owner='OrderNotificationViews',mailFailure=false){
const browser=await loadPlaywright().chromium.launch(browserOptions());t.after(()=>browser.close());const page=await browser.newPage();await page.setContent('<main id="root"></main>');
const browser=await loadPlaywright().chromium.launch(browserOptions());t.after(()=>browser.close());const page=await browser.newPage();page.setDefaultTimeout(5000);await page.setContent('<main id="root"></main>');
for(const file of ['order-notifications/shared.js','order-rules/view.js','order-notifications/view.js'])await page.addScriptTag({content:await fs.readFile(path.resolve('web/modules',file),'utf8')});
await page.evaluate(async({section,owner,mailFailure})=>{window.calls=[];window.active=true;window.PageLifecycle={requestKey:()=> 'key',dirty:()=>false,onDispose:()=>{},afterSave:async reload=>reload(),guard:fn=>fn()};window.OrderExecutionViews={fields:async panel=>{panel.textContent='字段映射';},execution:async panel=>{panel.textContent='订单执行';return {refresh:async()=>{}};}};const snapshot={rules:[],orders:[{id:'o1',orderNo:'ORDER-1',status:'blocked',batchId:'BATCH-1',ruleSnapshot:{version:4},archive:{path:'archive/ORDER-1.pdf'},reason:'缺少归档证据'}],batches:[],audit:[],adapters:[],settings:{enabled:false},capabilities:{},window:{available:true,start:'2026-10-19T00:00:00Z',end:'2026-10-19T11:00:00Z'}};window[owner].configure(window.viewHelpers={api:async url=>{window.calls.push(url);if(url==='/mail'&&mailFailure)throw Error('SMTP目录暂不可读');return url==='/overview'?{nextSlots:['2026-10-20T03:00:00Z']}:url==='/mail'?{channels:[]}:url.endsWith('/fields')?{samples:[]}:snapshot;},esc:value=>String(value??'').replaceAll('&','&amp;').replaceAll('<','&lt;'),formatDate:v=>v||'—',user:{role:'admin'}});await window[owner].render(document.querySelector('#root'),()=>window.active,section);},{section,owner,mailFailure});return page;
await page.evaluate(async({section,owner,mailFailure})=>{window.calls=[];window.active=true;window.PageLifecycle={requestKey:()=> 'key',dirty:()=>false,onDispose:()=>{},afterSave:async reload=>reload(),guard:fn=>fn()};window.BusinessRecordViews={render:async(host,options,kind)=>{host.textContent='授权分页 '+kind;}};window.OrderExecutionViews={fields:async panel=>{panel.textContent='字段映射';}};const snapshot={rules:[],adapters:[],settings:{enabled:false,processingEnabled:false,version:1},counts:{orders:3,blocked:1,unknown:1,activeBatches:2},capabilities:{},window:{available:true,start:'2026-10-19T00:00:00Z',end:'2026-10-19T11:00:00Z'}};window[owner].configure(window.viewHelpers={api:async(url,body)=>{window.calls.push(url);if(body)return new Promise(r=>window.releaseAction=()=>r({version:2}));if(url==='/mail'&&mailFailure)throw Error('SMTP目录暂不可读');return url==='/mail'?{channels:[]}:snapshot;},esc:value=>String(value??'').replaceAll('&','&amp;').replaceAll('<','&lt;'),formatDate:v=>v||'—',user:{role:'admin'}});await window[owner].render(document.querySelector('#root'),()=>window.active,section);},{section,owner,mailFailure});return page;
}
test('notification orders expose batch and archive evidence without reading mailbox or field catalogs',async t=>{const page=await setup(t,'orders');await page.locator('summary').click();assert.match(await page.locator('main').innerText(),/BATCH-1/);assert.match(await page.locator('main').innerText(),/archive\/ORDER-1.pdf/);assert.equal(await page.locator('a[href="#notification-batches"]').count(),1);assert.equal(await page.locator('a[href="#records"]').count(),1);assert.equal(await page.locator('[data-rule-tab]').count(),0);assert.deepEqual(await page.evaluate(()=>calls),['/order-rules']);});
test('fields route delegates fields lifecycle and never reads notification mailbox or runtime snapshot',async t=>{const page=await setup(t,'fields','OrderRuleViews');await page.getByText('字段映射',{exact:true}).waitFor();assert.deepEqual(await page.evaluate(()=>calls),[]);assert.equal(await page.locator('[data-rule-tab]').count(),0);});
test('workbench shows server next slot and concrete capability remediation links',async t=>{const page=await setup(t,'workbench');assert.match(await page.locator('main').innerText(),/2026-10-20T03:00:00Z/);for(const hash of ['#rule-fields','#bpm','#storage','#notification-orders'])assert.ok(await page.locator('a[href="'+hash+'"]').count());assert.deepEqual(await page.evaluate(()=>calls),['/order-rules','/overview']);});
test('settings mailbox read failure is visible and does not present an empty catalog as confirmed',async t=>{const page=await setup(t,'settings','OrderNotificationViews',true);assert.match(await page.locator('main').innerText(),/SMTP目录暂不可读/);assert.match(await page.locator('main').innerText(),/邮箱.*读取失败/);});
test('a late notification action after departure starts no readback and emits no saved feedback',async t=>{
const page=await setup(t,'pending');await page.evaluate(()=>{const prior=window.viewHelpers.api;window.OrderNotificationViews.configure({...window.viewHelpers,api:async(url,body)=>{if(url==='/order-rules/prepare')return new Promise(resolve=>window.releaseAction=()=>resolve({version:2}));return prior(url,body);}});});
await page.locator('#order-rule-prepare button[type=submit]').click();await page.waitForFunction(()=>typeof window.releaseAction==='function');await page.evaluate(()=>{window.active=false;window.releaseAction();});await page.waitForFunction(()=>!document.querySelector('#order-rule-prepare button[type=submit]').disabled);assert.deepEqual(await page.evaluate(()=>calls),['/order-rules']);assert.equal(await page.locator('#order-rules-feedback').textContent(),'');
});
test('order and batch sections delegate to bounded query views without loading full snapshots',async t=>{const page=await setup(t,'orders');assert.equal(await page.locator('main').innerText(),'授权分页 orders');assert.deepEqual(await page.evaluate(()=>calls),[]);await page.evaluate(()=>OrderNotificationViews.render(document.querySelector('#root'),()=>active,'pending'));assert.equal(await page.locator('main').innerText(),'授权分页 batches');assert.deepEqual(await page.evaluate(()=>calls),[]);});
test('fields delegate their lifecycle without notification runtime reads',async t=>{const page=await setup(t,'fields','OrderRuleViews');await page.getByText('字段映射',{exact:true}).waitFor();assert.deepEqual(await page.evaluate(()=>calls),[]);});
test('business homepage uses bounded summary and concrete remediation links',async t=>{const page=await setup(t,'workbench');assert.match(await page.locator('main').innerText(),/2026-10-19T11:00:00Z/);for(const hash of ['#rule-fields','#bpm','#storage','#notification-orders'])assert.ok(await page.locator('a[href="'+hash+'"]').count());assert.deepEqual(await page.evaluate(()=>calls),['/order-rules?view=summary']);});
test('mailbox failure is explicit and cannot save an empty catalog',async t=>{const page=await setup(t,'settings','OrderNotificationViews',true);assert.match(await page.locator('main').innerText(),/邮箱目录读取失败/);await page.getByRole('button',{name:'保存设置'}).click();assert.deepEqual(await page.evaluate(()=>calls),['/order-rules?view=summary','/mail']);});
test('late settings action after departure starts no readback or saved feedback',async t=>{const page=await setup(t,'settings');await page.getByRole('button',{name:'保存设置'}).click();await page.waitForFunction(()=>typeof releaseAction==='function');await page.evaluate(()=>{active=false;releaseAction();});await page.waitForFunction(()=>!document.querySelector('#order-rule-settings button').disabled);assert.deepEqual(await page.evaluate(()=>calls),['/order-rules?view=summary','/mail','/order-rules/settings']);assert.equal(await page.locator('form [role=alert]').innerText(),'');});