const assert = require('node:assert/strict') const { chromium, frontend: base, backend, username, password } = require('./vue3-test-runtime.cjs') const delay = ms => new Promise(resolve => setTimeout(resolve, ms)) ;(async () => { const login = await (await fetch(backend + '/login', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ username, password, code: '', uuid: '' }) })).json() assert.equal(login.code, 200) const browser = await chromium.launch() const writes = [], errors = [], failedPages = new Set(), pageQueries = [], attempts = new Map() try { const context = await browser.newContext({ viewport: { width: 1440, height: 900 } }) await context.addCookies([{ name: 'Admin-Token', value: login.token, url: base }]) const page = await context.newPage() page.setDefaultTimeout(15000) page.on('pageerror', error => errors.push(error.message)) await context.route('**/dev-api/**', async route => { const req=route.request(),url=new URL(req.url()),path=url.pathname const reply=data=>route.fulfill({json:{code:200,...data}}) const failure=()=>route.fulfill({json:{code:500,msg:'模拟网络失败,请重试'}}) if(!['GET','HEAD'].includes(req.method())){ if(path==='/dev-api/warehouse/stock/out'||/^\/dev-api\/warehouse\/in\/receive\/99[12]$/.test(path)){ const payload=req.postDataJSON(),id=path.endsWith('/out')?payload.id:Number(path.split('/').pop()),key=path+':'+id writes.push({path,id,payload});attempts.set(key,(attempts.get(key)||0)+1) return id===992&&attempts.get(key)===1?failure():reply({data:{}}) } writes.push({blocked:true,path});return route.abort('blockedbyclient') } if(url.searchParams.has('auditPaging')){ const key=url.searchParams.get('auditPaging'),pageNo=Number(url.searchParams.get('pageNum')) pageQueries.push({key,pageNo}) if(!failedPages.has(key)){failedPages.add(key);return failure()} return reply({rows:[{id:1,inStatus:0},{id:2,inStatus:0}],total:4}) } if(path==='/dev-api/warehouse/purchase/batch/list'&&url.searchParams.get('keyword')?.startsWith('AUDIT-')){ const keyword=url.searchParams.get('keyword');await delay(keyword==='AUDIT-A'?280:15) return reply({rows:[{id:991,batchName:keyword}],total:1}) } if(path==='/dev-api/warehouse/purchase/sheet/options'&&[url.searchParams.get('keyword'),url.searchParams.get('name')].includes('回归目录物品'))return reply({data:{items:[{id:996001,productName:'回归目录物品',brand:'甲牌',spec:'10型',unit:'件',category:'材料'},{id:996002,productName:'回归目录物品',brand:'乙牌',spec:'20型',unit:'件',category:'材料'}]}}) if(path==='/dev-api/warehouse/purchase/filtered'){ await delay(220);return reply({data:[{id:991,projectId:Number(url.searchParams.get('projectId')),supplierId:1,priceLocked:true,remainingQuantity:1}]}) } if(/^\/dev-api\/warehouse\/in\/99[12]$/.test(path))return reply({data:{id:Number(path.split('/').pop()),receiptRoot:true,inNum:2,inStatus:0}}) if(path==='/dev-api/warehouse/area/optionselect')return reply({data:[{id:1,areaName:'A 库区'},{id:2,areaName:'B 库区'}]}) return route.continue() }) await page.goto(base+'/procurement/details') await page.getByRole('button',{name:'新增采购批次',exact:true}).waitFor() const sheet=code=>page.locator('.purchase-sheet').evaluate((el,code)=>Function('v','return ('+code+')(v)')(el.__vueParentComponent.proxy),code) await page.waitForFunction(()=>!document.querySelector('.purchase-sheet').__vueParentComponent.proxy.loading) const batches=await sheet(`async v=>{v.query.keyword='AUDIT-A';const first=v.loadBatches();v.query.keyword='AUDIT-B';const last=v.loadBatches();await Promise.all([first,last]);return {query:v.query.keyword,batch:v.batches[0].batchName,loading:v.loading}}`) assert.deepEqual(batches,{query:'AUDIT-B',batch:'AUDIT-B',loading:false}) await page.getByRole('button',{name:'新增采购批次',exact:true}).click();await page.locator('.sheet-grid').waitFor() const validation=await sheet(`async v=>{const good={projectId:v.projects[0].id,expenseCategoryId:v.categories[0].id,materialName:'回归新物品',unit:v.units[0],category:v.dict.type.wms_item_category[0].label,quantity:1};v.sheet.rows=[{...v.emptyRow(),...good,projectId:null},{...v.emptyRow(),...good,materialName:'正常行'},{...v.emptyRow(),...good,materialName:'错误行',finalUnitPrice:-1,category:''}];await v.save();v.onlyInvalid=true;await v.$nextTick();const originalLines=v.visibleRows.map(row=>v.originalIndex(row)+1);await v.focusError(v.rowErrors.find(e=>e.field==='finalUnitPrice'));return {errors:v.rowErrors.length,rows:v.errorKeys.size,originalLines,focused:document.activeElement.closest('.sheet-cell')?.dataset.row}}`) assert.deepEqual(validation,{errors:3,rows:2,originalLines:[1,3],focused:'2'}) assert.equal(await page.locator('.cell-invalid').count(),2) const timings=await sheet(`async v=>{const times=[];v.onlyInvalid=false;v.validationEnabled=false;for(const count of [50,100,200]){const begin=performance.now();v.sheet.rows=Array.from({length:count},(_,i)=>({...v.emptyRow(),projectId:v.projects[0].id,expenseCategoryId:v.categories[0].id,materialName:'性能样例'+i,unit:v.units[0],category:v.dict.type.wms_item_category[0].label,quantity:1}));await v.$nextTick();times.push({rows:count,renderMs:Math.round(performance.now()-begin)});}v.sheet.rows[0].quantity=2;await v.$nextTick();v.baseline=v.serialize(v.sheet);return times}`) console.log('PASS batch latest request; sheet collects all errors, preserves original row numbers and focuses field. Render baseline:',JSON.stringify(timings)) const cell=field=>page.locator('.sheet-cell[data-row="0"][data-field="'+field+'"]') await cell('quantity').dblclick();await cell('quantity').locator('input:not(.sheet-keyboard-input)').fill('3');await cell('quantity').locator('input:not(.sheet-keyboard-input)').press('Enter') await page.waitForFunction(()=>document.activeElement.closest('.sheet-cell')?.dataset.row==='1') assert.equal(await sheet('v=>document.activeElement.closest(".sheet-cell")?.dataset.field'),'quantity') await cell('finalUnitPrice').dblclick();await cell('finalUnitPrice').locator('input:not(.sheet-keyboard-input)').fill('9');await cell('finalUnitPrice').locator('input:not(.sheet-keyboard-input)').press('Shift+Tab') await page.waitForFunction(()=>document.activeElement.closest('.sheet-cell')?.dataset.field==='actualUnitPrice') await page.keyboard.press('Tab');await page.waitForFunction(()=>document.activeElement.closest('.sheet-cell')?.dataset.field==='finalUnitPrice') await cell('quantity').click() const pastedUnit=await sheet('v=>v.sheet.rows[0].unit') await cell('quantity').evaluate((el,unit)=>{const data=new DataTransfer();data.setData('text/plain',`数量\t单位\t报价单价\n2\t${unit}\t3.50\n4\t${unit}\t5.00`);el.dispatchEvent(new ClipboardEvent('paste',{bubbles:true,clipboardData:data}))},pastedUnit) await page.getByRole('dialog',{name:'Excel 粘贴预览',exact:true}).getByRole('button',{name:'应用到表格',exact:true}).click();await page.getByRole('dialog',{name:'Excel 粘贴预览',exact:true}).waitFor({state:'hidden'}) assert.deepEqual(await sheet('v=>v.sheet.rows.slice(0,2).map(r=>[r.quantity,r.finalUnitPrice])'),[[2,3.5],[4,5]]) await page.getByRole('button',{name:'撤销',exact:true}).click() assert.deepEqual(await sheet('v=>[v.sheet.rows[0].quantity,v.sheet.rows[0].finalUnitPrice]'),[3,'9']) await cell('materialName').dblclick();await cell('materialName').locator('input').fill('回归目录物品') await page.locator('.el-select-dropdown:visible .el-select-dropdown__item').filter({hasText:/回归目录物品.*甲牌/}).click() await page.waitForFunction(()=>document.querySelector('.purchase-sheet').__vueParentComponent.proxy.items.some(i=>i.id===996002)) await cell('materialBrand').dblclick() await page.locator('.el-select-dropdown:visible .el-select-dropdown__item').filter({hasText:/^乙牌$/}).click() assert.deepEqual(await sheet('v=>{const r=v.sheet.rows[0];return [r.productId,r.materialBrand,r.materialParams,r.unit]}'),[null,'乙牌','10型','件'],'changing brand alone must preserve an explicit specification') await cell('materialParams').dblclick();await page.locator('.el-select-dropdown:visible .el-select-dropdown__item').filter({hasText:'20型'}).click() assert.deepEqual(await sheet('v=>{const r=v.sheet.rows[0];return [r.productId,r.materialBrand,r.materialParams,r.unit]}'),[996002,'乙牌','20型','件']) await sheet('v=>{v.baseline=v.serialize(v.sheet)}') console.log('PASS lazy editor keeps Enter/Tab/Shift-Tab, rectangular paste, undo and item/brand/spec auto-fill') await page.goto(base+'/procurement/arrival') await page.locator('.arrival-workbench-page').waitFor() const selection=await page.locator('.arrival-workbench-page').evaluate(async el=>{ const v=el.__vueParentComponent.proxy v.queryParams.projectId=991;const first=v.chooseFiltered();v.queryParams.projectId=992;v.getList();await first const changed=v.ids.slice();const second=v.chooseFiltered();v.clearArrivalSelection();await second return {changed,cleared:v.ids,loading:v.choosingFiltered} }) assert.deepEqual(selection,{changed:[],cleared:[],loading:false}) console.log('PASS delayed full-selection cannot survive filter change or manual clear') const paging=await page.evaluate(async()=>{ const {default:Mobile}=await import('/src/views/mobile/index.vue'),{default:Purchase}=await import('/src/views/mobile/components/MobilePurchase.vue') const result=[] for(const [key,list,total,method] of [['stock','stockList','stockListTotal','loadStock'],['in','inList','inTotal','loadInRecords'],['out','outList','outTotal','loadOutRecords'],['check','checkList','checkTotal','loadCheckRecords'],['product','productList','productTotal','loadProducts'],['area','areaList','areaTotal','loadAreas']]){ const v={listErrors:{},[key+'Query']:{pageNum:1,auditPaging:key},[key+'ListRequestId']:0,[list]:[{id:1}],[total]:4,selectedStockIds:[],selectedInIds:[],canUseStock:()=>true} await Mobile.methods[method].call(v,false);const failedPage=v[key+'Query'].pageNum await Mobile.methods[method].call(v,false) result.push({key,failedPage,successPage:v[key+'Query'].pageNum,ids:v[list].map(r=>r.id),error:v.listErrors[key]}) } const v={query:{pageNum:1,auditPaging:'purchase'},listRequestId:0,list:[{id:1}],total:4,selectedIds:[],canSelectArrival:()=>true} await Purchase.methods.load.call(v,false);const failedPage=v.query.pageNum await Purchase.methods.load.call(v,false) result.push({key:'purchase',failedPage,successPage:v.query.pageNum,ids:v.list.map(r=>r.id),error:v.listError}) return result }) for(const result of paging)assert.deepEqual(result,{key:result.key,failedPage:1,successPage:2,ids:[1,2],error:false}) for(const {key} of paging)assert.deepEqual(pageQueries.filter(q=>q.key===key).map(q=>q.pageNo),[2,2]) console.log('PASS all seven mobile lists retry the failed page without omission or duplicates') await page.evaluate(async()=>{ const {createApp,h,ElementPlus}=await import('/tests/browser-runtime.js') const {default:Receipt}=await import('/src/components/ReceiptDialog/Batch.vue'),{default:Stock}=await import('/src/components/Production/StockOperations.vue') window.auditApps=[];window.auditBatch={} for(const [name,component] of [['receipt',Receipt],['stock',Stock]]){ const host=document.createElement('div');document.body.append(host) const app=createApp({render:()=>h(component)}).use(ElementPlus) app.config.globalProperties.parseTime=()=> '2026-10-13' app.config.globalProperties.$modal={msgWarning(){},msgSuccess(){},msgError(){}} app.config.globalProperties.$store={getters:{permissions:['*:*:*']}} app.mount(host);window.auditApps.push({app,host});window.auditBatch[name]=app._instance.subTree.component.proxy } }) for(const [name,selector] of [['receipt','.receipt-batch-dialog'],['stock','.stock-batch-dialog']]){ await page.evaluate(async name=>{ const v=window.auditBatch[name],rows=[991,992].map(id=>({id,projectId:1,projectName:'回归项目',productName:'回归物品 '+id,purchaseBatchNo:'CG261001',unit:'件',areaId:1,areaName:'A 库区',inStatus:0,inNum:2,stockNum:3})) await v.open(rows);if(name==='receipt'){v.commonArea=1;v.setArea(1)} },name) for(const width of [360,390,430]){ await page.setViewportSize({width,height:850});await page.locator(selector+'.is-fullscreen').waitFor() const layout=await page.locator(selector).evaluate(el=>({overflow:el.scrollWidth>el.clientWidth+1,table:!!el.querySelector('.el-table'),footer:el.querySelector('.el-dialog__footer').getBoundingClientRect().bottom,viewport:innerHeight})) assert.equal(layout.overflow,false,name+' '+width);assert.equal(layout.table,false);assert.ok(layout.footer<=layout.viewport+1) } await page.setViewportSize({width:1440,height:900});await page.locator(selector+' .el-table').waitFor() const result=await page.evaluate(async name=>{const v=window.auditBatch[name];await v.submit();v.onlyFailed=true;await v.$nextTick();return {done:v.rows.filter(r=>r.done).length,failed:v.rows.filter(r=>r.failed).length,total:v.runRows.length,completed:v.completedCount,visible:(v.filteredRows||v.displayRows).length}},name) assert.deepEqual(result,{done:1,failed:1,total:2,completed:2,visible:1}) await delay(1050) const retried=await page.evaluate(async name=>{const v=window.auditBatch[name];await v.submit(true);return {done:v.rows.filter(r=>r.done).length,failed:v.rows.filter(r=>r.failed).length}},name) assert.deepEqual(retried,{done:2,failed:0}) await page.evaluate(name=>{window.auditBatch[name].visible=false},name) } for(const prefix of ['/dev-api/warehouse/in/receive/','/dev-api/warehouse/stock/out']){ const rows=writes.filter(w=>w.path.startsWith(prefix));assert.equal(rows.length,3);assert.equal(rows.filter(r=>r.id===991).length,1) const retry=rows.filter(r=>r.id===992);assert.deepEqual(retry[0].payload,retry[1].payload) } assert.equal(writes.some(w=>w.blocked),false) assert.deepEqual(errors,[]) await page.evaluate(()=>window.auditApps.forEach(({app,host})=>{app.unmount();host.remove()})) console.log('PASS receipt/stock mobile cards at 360/390/430px; desktop partial failures retry original keys without resubmitting successful rows; all writes mocked') } finally {await browser.close()} })().catch(error=>{console.error(error);process.exitCode=1})