#!/usr/bin/env node // 浏览器端到端检查:确定时钟下启动应用子进程,用真实页面以三个角色操作。 // 断言:无未捕获页面错误、无控制台错误、无非预期失败请求;关键文字与金额出现在页面上。 // 每个页面保存截图到 e2e/out/screens/,并保存规范化的页面文字快照: // node e2e/browser.mjs 录制快照基线到 e2e/baseline/ui/ // node e2e/browser.mjs --check 与基线比较(忽略无意义空白),有差异退出码 1 // --headed 可视化运行;--slow 每步放慢 import {createRequire} from 'node:module'; import fs from 'node:fs';import os from 'node:os';import path from 'node:path';import {fileURLToPath} from 'node:url'; const require=createRequire(import.meta.url); const {chromium}=require('playwright'); const {startServer}=require('./lib/server.js'); const {Session}=require('./lib/client.js'); const {Normalizer}=require('./lib/normalize.js'); const HERE=path.dirname(fileURLToPath(import.meta.url)); const args=process.argv.slice(2),check=args.includes('--check'),headed=args.includes('--headed'); const BASE_UI=path.join(HERE,'baseline','ui'),OUT_UI=path.join(HERE,'out','ui'),SCREENS=path.join(HERE,'out','screens'); const D0='2026-11-19',D='2026-11-20'; const PW={owner:'browser-owner-pass-1',assistant:'browser-assistant-pass',assistant2:'browser-assistant2-pass'}; const SHANGHAI=8*3600*1000; const dayStart=date=>Date.parse(date+'T00:00:00Z')-SHANGHAI+10*3600*1000; const failures=[];const notes=[]; function fail(message){failures.push(message);console.error(' ✗ '+message);} function ok(message){console.log(' ✓ '+message);} async function seed(server,base){ // 前置数据只经 HTTP 写入:账号、起始库存、购料和前一天的订单(用于跨天修改申请与前后单切换)。 const s=new Session({base,server});await s.day(D0); await s.post('owner','/api/setup',{ownerPassword:PW.owner,assistantPassword:PW.assistant,assistant2Password:PW.assistant2}); await s.post('assistant','/api/login',{name:'娜娜',password:PW.assistant}); await s.post('assistant2','/api/login',{name:'小昊',password:PW.assistant2}); for(const [pocket,grams] of [['现货','100'],['金料','50']])await s.post('owner','/api/stock',{date:D0,kind:'opening',pocket,grams,note:'浏览器检查起始库存'}); await s.post('owner','/api/material-purchases',{date:D0,grams:'10',total:'9000',payer:'owner',note:'浏览器检查购料'}); const order=(member,customer,quantity,sale)=>({date:D0,customer,internal_note:'浏览器检查备注',salesperson:{owner:'麦麦',assistant:'娜娜',assistant2:'小昊'}[member],payment_account:{owner:'麦麦微信',assistant:'助理微信',assistant2:'助理2微信'}[member],rounding_mode:'cent',lines:[{name:'足金999',unit:'g',quantity,pocket:'现货',payer:member,sale,cost:String(Math.round(Number(sale)*0.85))}],fee_items:[]}); await s.post('owner','/api/orders/issue',order('owner','昨日老板客户甲','1.5','1500')); await s.post('assistant','/api/orders/issue',order('assistant','昨日娜娜客户','2','2000')); await s.post('owner','/api/orders/issue',order('owner','昨日老板客户乙','3','3100')); await s.post('assistant2','/api/orders/issue',order('assistant2','昨日小昊客户','1','1050')); if(s.problems.length)throw new Error('前置数据写入失败:\n'+s.problems.join('\n')); } class Browser{ constructor(browser,base,server){this.browser=browser;this.base=base;this.server=server;this.step=0;this.normalizer=new Normalizer();this.normalizer.literal(base,'http://');this.normalizer.literal(base.slice(7),'');this.snapIndex=0;this.allowed=[];this.inflight=0;this.snapshots=[];} async open(role){ this.role=role;this.context=await this.browser.newContext({viewport:{width:1400,height:1000},locale:'zh-CN',timezoneId:'Asia/Shanghai'}); await this.context.addInitScript(()=>{window.print=()=>{};});this.context.on('page',page=>this.watch(page));this.page=await this.context.newPage();this.page.setDefaultTimeout(8000);await this.page.clock.setFixedTime(new Date(dayStart(D))); this.watch(this.page); } watch(page){ this.watched??=new WeakSet();if(this.watched.has(page))return;this.watched.add(page); page.clock?.setFixedTime(new Date(dayStart(D))).catch(()=>{}); page.on('pageerror',e=>fail(`[${this.role}] 页面未捕获错误:${e.message}`)); page.on('console',m=>{if(m.type()==='error')fail(`[${this.role}] 控制台错误:${m.text()}`);}); page.on('dialog',d=>{notes.push(`${this.role} 对话框:${d.message()}`);d.accept();}); page.on('request',()=>{this.inflight++;}); page.on('requestfinished',async r=>{this.inflight--;const res=await r.response();if(res&&res.status()>=400&&!this.isAllowed(r.url(),res.status()))fail(`[${this.role}] 请求失败 ${res.status()} ${r.method()} ${r.url().replace(this.base,'')}`);}); page.on('requestfailed',r=>{this.inflight--;fail(`[${this.role}] 请求未完成 ${r.method()} ${r.url().replace(this.base,'')} ${r.failure()?.errorText}`);}); } isAllowed(url,status){return this.allowed.some(([pattern,code])=>(code===status)&&pattern.test(url.replace(this.base,'')));} async close(){await this.context?.close();this.context=null;} // 每个界面动作前把服务器时钟前进 1 秒,使写入时间戳只取决于动作顺序。 async act(fn){this.step++;await this.server.setTime(dayStart(D)+this.step*1000);const result=await fn(this.page);await this.idle();return result;} async idle(){ const page=this.page;let quiet=0;const deadline=Date.now()+15000; while(Date.now()=300)break;} await page.evaluate(()=>new Promise(r=>requestAnimationFrame(()=>r()))); } async snap(name){ const label=String(++this.snapIndex).padStart(2,'0')+'-'+name; await this.idle(); // 页面可见文字(含打开的对话框),规范化标识与空白。 const raw=await this.page.evaluate(()=>{ const parts=[...document.body.children].filter(el=>el.id!=='toast'&&el.tagName!=='DIALOG'&&el.tagName!=='SCRIPT').map(el=>el.innerText);// 提示条按真实计时消失,不计入快照 for(const d of document.querySelectorAll('dialog[open]'))parts.push('[对话框]\n'+d.innerText); // 表单控件当前值(innerText 不含输入框内容) const values=[...document.querySelectorAll('input,select,textarea')].filter(el=>el.offsetParent!==null&&el.type!=='hidden'&&el.type!=='password').map(el=>{const key=el.name||el.id||el.getAttribute('aria-label')||el.type;const value=el.type==='checkbox'||el.type==='radio'?(el.checked?'☑':'☐'):el.tagName==='SELECT'?(el.selectedOptions[0]?.textContent||''):el.value;return key+'='+value;}); return parts.join('\n')+'\n[控件]\n'+values.join('\n'); }); const text=raw.split('\n').map(line=>this.normalizer.string(line).replace(/[\t   ]+/g,' ').trim()).filter(Boolean).join('\n')+'\n'; fs.mkdirSync(OUT_UI,{recursive:true});fs.mkdirSync(SCREENS,{recursive:true}); fs.writeFileSync(path.join(OUT_UI,label+'.txt'),text); await this.page.screenshot({path:path.join(SCREENS,label+'.png'),fullPage:true}); this.snapshots.push({label,text});return text; } // 提交前列出浏览器校验未通过的字段,便于定位表单变化。 async invalid(selector){const names=await this.page.$$eval(selector+' :invalid',els=>els.filter(e=>e.name).map(e=>e.name+'('+(e.validationMessage||'')+')'));if(names.length)fail(`[${this.role}] 表单 ${selector} 有未通过校验的字段:${names.join('、')}`);return names;} async expectText(text,what){const body=await this.page.evaluate(()=>document.body.innerText+[...document.querySelectorAll('dialog[open]')].map(d=>d.innerText).join('\n'));if(body.includes(text))ok(what||('页面显示 '+text));else fail(`[${this.role}] 页面未显示「${text}」${what?'('+what+')':''}`);} async login(role,member,label){ await this.open(role); await this.act(p=>p.goto(this.base+'/')); if(label)await this.snap(label); await this.act(async p=>{await p.selectOption('#login-form select[name=member]',member);await p.fill('#login-form input[name=password]',PW[role]);await p.click('#login-form button.primary');}); await this.page.waitForSelector('#shell:not([hidden])',{timeout:10000});await this.idle(); ok(`${role} 登录成功`); } async closeDialogs(){for(const close of await this.page.locator('dialog[open] .dialog-close').all())if(await close.isVisible())await this.act(()=>close.click());} async logout(){await this.closeDialogs();await this.act(p=>p.click('[data-action="logout"]'));await this.close();} async tab(name){await this.act(p=>p.click(`nav [data-tab="${name}"]`));} async visitTabs(prefix){ const tabs=await this.page.$$eval('nav [data-tab]',buttons=>buttons.filter(b=>!b.hidden&&!b.disabled&&b.offsetParent!==null).map(b=>b.dataset.tab)); for(const tab of tabs){await this.tab(tab);await this.snap(prefix+'-tab-'+tab);} ok(`${this.role} 访问全部 ${tabs.length} 个导航页:${tabs.join('、')}`); return tabs; } } async function flowOwner(b){ await b.login('owner','owner','login-page'); await b.snap('owner-home'); await b.visitTabs('owner'); // —— 开单:按克计价 + 附加项目 + 成本行 —— await b.tab('create'); await b.act(async p=>{ const f=p.locator('#order-form'); await f.locator('input[name=customer]').fill('浏览器客户甲'); await f.locator('input[name=customer_type][value=new]').check(); await f.locator('select[name=member]').selectOption('owner'); const line=f.locator('.line-item').first(); await line.locator('input[name=quantity]').fill('2.5'); await line.locator('input[name=goldPrice]').fill('950'); await line.locator('input[name=laborRate]').fill('30'); await line.locator('[data-action="add-charge"]').click(); const charge=line.locator('.charge-list > *').first(); const amount=charge.locator('input[type=number]').first();await amount.fill('20'); await line.locator('input[name="cost-materialRate"]').fill('880'); await line.locator('input[name="cost-labor"]').fill('25'); await f.locator('[name=internal_note]').fill('#浏览器 内部备注'); // 附加项目对应的内部成本行(必填) for(const fee of await f.locator('input[name=feeAmount]').all())if(await fee.isVisible()&&!(await fee.inputValue()))await fee.fill('5'); }); await b.invalid('#order-form'); const sale=await b.page.locator('#order-form .line-item input[name=sale]').first().inputValue(); if(sale==='2470.00'||sale==='2470')ok('本行销售额自动计算为 2470.00(2.5g×(950+30)+附加 20)');else fail('本行销售额计算不符:'+sale); await b.snap('owner-create-filled'); await b.act(p=>p.click('#order-form button[type=submit]')); await b.snap('owner-create-submitted'); // 生成后自动打开订单明细 await b.expectText('¥2,470','订单明细显示成交合计 ¥2,470'); await b.expectText('未打印','新单显示未打印'); // —— 客户预览/打印:新窗口点击“打印”后记录已打印 —— const [popup]=await Promise.all([b.context.waitForEvent('page'),b.act(p=>p.locator('#order-dialog [data-action="print"]').first().click())]); const main=b.page;b.page=popup;popup.setDefaultTimeout(8000); await popup.waitForLoadState('load');await b.idle(); await b.snap('owner-print-preview'); await b.act(p=>p.click('#print')); await popup.waitForFunction(()=>document.getElementById('document-print-state')?.textContent.includes('已打印')); await b.expectText('✓ 已打印','打印预览中点击打印后记录为已打印'); await b.snap('owner-print-marked'); await popup.close();b.page=main; await b.act(p=>p.locator('#order-dialog [data-action="close-dialog"]').click()); await b.tab('orders'); await b.expectText('浏览器客户甲','新订单出现在订单列表'); await b.snap('owner-orders-after-create'); // —— 订单明细与前后单切换(本月列表含昨天的多张单)—— await b.act(p=>p.click('[data-action="order-period"][data-period="month"]')); await b.snap('owner-orders-month'); await b.act(p=>p.locator('[data-action="open-order"]',{hasText:'浏览器客户甲'}).first().click()); await b.expectText('已打印','重新打开明细显示已打印'); await b.snap('owner-order-detail'); const next=b.page.locator('#order-dialog [data-action="order-detail-next"]'); const prev=b.page.locator('#order-dialog [data-action="order-detail-prev"]'); if(await next.count()&&await next.isEnabled()){await b.act(()=>next.click());await b.snap('owner-order-detail-next');await b.act(()=>prev.click());await b.snap('owner-order-detail-prev');await b.expectText('浏览器客户甲','上一条回到原订单');} else if(await prev.count()&&await prev.isEnabled()){await b.act(()=>prev.click());await b.snap('owner-order-detail-prev');await b.act(()=>next.click());await b.snap('owner-order-detail-next');await b.expectText('浏览器客户甲','下一条回到原订单');} else fail('订单明细前后单按钮均不可用'); await b.act(p=>p.locator('#order-dialog [data-action="close-dialog"]').click()); // —— 每日购料 —— await b.tab('material-pools'); await b.act(async p=>{const f=p.locator('#material-purchase-form');await f.locator('input[name=grams]').fill('5');await f.locator('input[name=total]').fill('4600');await f.locator('select[name=payer]').selectOption('owner');await f.locator('input[name=note]').fill('浏览器购料');await f.locator('button[type=submit],button.primary').first().click();}); await b.expectText('浏览器购料','购料登记成功'); await b.snap('owner-material-purchase'); // —— 锁价 —— await b.tab('create'); await b.act(p=>p.click('[data-action="create-mode"][data-mode="lock"]')); await b.snap('owner-price-lock-form'); await priceLockForm(b); // —— 直接回收 —— await b.tab('recoveries'); await recoveryForm(b); // —— 店铺设置 —— await b.tab('settings'); await b.act(async p=>{const f=p.locator('#shop-settings-form');await f.locator('input[name=storeName]').fill('浏览器对照珠宝');await f.locator('button[type=submit],button.primary').first().click();}); await b.expectText('浏览器对照珠宝','店铺名称已更新'); await b.snap('owner-settings-saved'); await b.logout(); } async function priceLockForm(b){ const form=b.page.locator('form').filter({has:b.page.locator('[name=customer]')}).first(); await b.act(async p=>{ await form.locator('[name=customer]').fill('浏览器锁价客户'); const radio=form.locator('input[name=customer_type][value=returning]');if(await radio.count())await radio.check(); await form.locator('[name=quantity]').first().fill('2'); await form.locator('[name=goldPrice]').first().fill('900'); await form.locator('[name=laborRate]').first().fill('10'); await form.locator('[name=material_rate]').fill('850'); await form.locator('[name=received_amount]').fill('1000'); for(const box of await form.locator('input[type=checkbox][name*=verified]').all())await box.check(); }); await b.invalid('form:has([name=received_amount])'); await b.snap('owner-price-lock-filled'); await b.act(()=>form.locator('button[type=submit]').first().click()); await b.snap('owner-price-lock-submitted'); await b.closeDialogs(); await b.tab('price-locks'); await b.expectText('浏览器锁价客户','锁价单出现在待交付列表'); await b.snap('owner-price-locks-after-create'); } async function recoveryForm(b){ await b.act(async p=>{ const f=p.locator('#recovery-form'); await f.locator('[name=customer]').fill('浏览器回收客户'); await f.locator('[name=incoming_weight]').first().fill('5'); await f.locator('[name=melted_weight]').first().fill('5'); await f.locator('[name=purity]').first().fill('99'); await f.locator('[name=buy_rate]').fill('880'); await f.locator('[name=verified]').check(); }); await b.snap('owner-recovery-filled'); await b.act(p=>p.locator('#recovery-form button[type=submit]').first().click()); await b.expectText('浏览器回收客户','回收单出现在记录中'); await b.snap('owner-recovery-saved'); await b.closeDialogs(); } async function flowAssistantChange(b){ await b.login('assistant','assistant'); await b.snap('assistant-home'); await b.visitTabs('assistant'); await b.tab('orders'); await b.act(p=>p.click('[data-action="order-period"][data-period="yesterday"]')); await b.act(p=>p.locator('[data-action="open-order"]',{hasText:'昨日娜娜客户'}).first().click()); await b.snap('assistant-order-detail'); const edit=b.page.locator('#order-dialog button',{hasText:/^申请修改$/}).first(); await b.act(()=>edit.click()); await b.snap('assistant-change-form'); await b.act(async p=>{const f=p.locator('#order-form');await f.locator('input[name=customer]').fill('昨日娜娜客户(改)');await f.locator('input[name=customer_type][value=returning]').check();await f.locator('[name=edit_reason]').fill('客户名写错');await f.locator('[name=edit_verified]').check();}); await b.invalid('#order-form'); await b.act(p=>p.locator('#order-form button[type=submit]').click()); await b.snap('assistant-change-submitted'); await b.expectText('待','提交后显示待复核'); await b.logout(); // 麦麦审批 await b.login('owner','owner'); await b.tab('orders'); await b.act(p=>p.click('details.order-review-menu > summary')); await b.act(p=>p.click('[data-action="open-order-changes"]')); await b.snap('owner-order-changes'); await b.act(p=>p.locator('dialog[open] button',{hasText:'查看并复核'}).first().click()); await b.snap('owner-order-change-detail'); await b.act(p=>p.locator('dialog[open] button',{hasText:'查看变更并复核'}).first().click()); await b.snap('owner-order-change-review'); await b.act(async p=>{const dialog=p.locator('dialog[open]').last();await dialog.locator('[name=note]').fill('已核对');await dialog.locator('[name=verified]').check();}); await b.act(p=>p.locator('dialog[open] button',{hasText:'同意变更并更新原单'}).click()); await b.expectText('昨日娜娜客户(改)','批准后订单明细显示新客户名'); await b.snap('owner-order-change-approved'); await b.closeDialogs(); await b.tab('orders'); await b.act(p=>p.click('[data-action="order-period"][data-period="yesterday"]')); await b.expectText('昨日娜娜客户(改)','批准后订单显示新客户名'); await b.snap('owner-orders-after-approve'); await b.logout(); } async function flowAssistant2(b){ await b.login('assistant2','assistant2'); await b.snap('assistant2-home'); await b.visitTabs('assistant2'); await b.logout(); } function compareSnapshots(snapshots){ const expected=fs.existsSync(BASE_UI)?fs.readdirSync(BASE_UI).filter(f=>f.endsWith('.txt')).sort():[]; const actual=snapshots.map(s=>s.label+'.txt');const problems=[]; for(const name of expected)if(!actual.includes(name))problems.push('缺少页面快照 '+name); for(const name of actual)if(!expected.includes(name))problems.push('多出页面快照 '+name); for(const {label,text} of snapshots){ const file=path.join(BASE_UI,label+'.txt');if(!fs.existsSync(file))continue; const a=fs.readFileSync(file,'utf8').split('\n'),c=text.split('\n'); if(a.join('\n')===c.join('\n'))continue; let i=0;while(i0; console.log(`browser ${failed?'FAIL':'PASS'}:${b.snapshots.length} 个页面快照,${failures.length} 个运行错误,${problems.length} 处快照差异,用时 ${seconds}s(截图在 e2e/out/screens/)`); process.exitCode=failed?1:0; }else{ if(failures.length){console.error(`运行中有 ${failures.length} 个错误,拒绝写入基线`);process.exitCode=1;} else{fs.rmSync(BASE_UI,{recursive:true,force:true});fs.mkdirSync(BASE_UI,{recursive:true});for(const {label,text} of b.snapshots)fs.writeFileSync(path.join(BASE_UI,label+'.txt'),text);console.log(`基线已写入 e2e/baseline/ui/(${b.snapshots.length} 个页面快照,用时 ${seconds}s)`);} } if(notes.length&&args.includes('--verbose'))console.log(notes.join('\n')); }finally{await browser?.close();await server.stop();fs.rmSync(dataDir,{recursive:true,force:true});}