cmvr-wms/scripts/projectdev/real-data-page-replay.cjs
lixiaolong 5bdeceafd7 feat(auth): 添加认证cookie名称配置并优化表单布局
- 在 .env.production 中新增 VITE_AUTH_COOKIE_NAME 配置项用于设置认证cookie名称
- 将 AcceptanceException.vue 中的表单标签宽度从固定90px改为自动适配
- 在 ActionDialog.vue 中将多个表单项标记为必填项并调整标签宽度为自动适配
- 重构 ActionHistory.vue 中的按钮布局结构并添加表格列样式类名
- 更新 api-contract-audit.cjs 添加生产任务和BOM相关接口的契约测试
- 修改 auth.js 使用动态认证cookie键名替换硬编码的Admin-Token
- 调整系统角色授权用户页面的表单布局和表格样式类名
- 优化 ReceiptDialog Batch 组件的对话框尺寸、表单验证和分页功能
2026-10-15 11:30:55 +08:00

283 lines
47 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

const fs=require('node:fs'),path=require('node:path'),assert=require('node:assert/strict'),crypto=require('node:crypto')
const {chromium,frontend,username,password}=require('./vue3-test-runtime.cjs')
const directory=path.resolve(__dirname,'../../.codex-tmp/real-data-replay'),source=JSON.parse(fs.readFileSync(path.join(directory,'wms-dev-inventory.json'),'utf8')).tables
const checkpoint=path.join(directory,'page-checkpoint.json'),state=fs.existsSync(checkpoint)?JSON.parse(fs.readFileSync(checkpoint,'utf8')):{reset:false,maps:{sys_user:{1:1},sys_role:{1:1}},completed:[],operations:[],issues:[]}
const mode=process.argv[2]||'plan',limit=Number(process.argv[3]||Infinity)
const persist=()=>fs.writeFileSync(checkpoint,JSON.stringify(state,null,2))
const rows=table=>source[table]?.rows||[],mapped=(table,id)=>id==null?null:state.maps[table]?.[id]
const remember=(table,id,target)=>{state.maps[table]||={};state.maps[table][id]=target;persist()}
let browser,context,page,token
async function get(route,params={}){const url=new URL(frontend+'/dev-api'+route);for(const[k,v]of Object.entries(params))if(v!==undefined&&v!==null)url.searchParams.set(k,String(v));const response=await context.request.get(url.toString(),{headers:{Authorization:'Bearer '+token}});const body=await response.json();assert.equal(body.code,200,route+': '+body.msg);return body}
async function ready(route){await page.goto(frontend+route,{waitUntil:'domcontentloaded'});await page.locator('.desktop-viewport > .app-container').waitFor({timeout:60000});await page.waitForFunction(()=>![...document.querySelectorAll('.desktop-viewport .el-loading-mask')].some(e=>e.getClientRects().length),{timeout:60000})}
const dialog=()=>page.locator('.el-dialog:visible').last()
function field(root,label){return root.locator('.el-form-item').filter({has:root.page().locator('.el-form-item__label').filter({hasText:new RegExp('^\\s*'+escape(label)+'\\s*$')})}).first()}
async function fill(root,label,value){if(value===undefined||value===null)return;await field(root,label).locator('input:not([type=radio]):not([type=checkbox]),textarea').first().fill(String(value))}
async function select(root,label,value){
if(value===undefined||value===null||value==='')return
const item=field(root,label),control=item.locator('.el-select,.el-tree-select,.el-cascader').first();await control.click()
const input=control.locator('input').first()
if((await control.getAttribute('class')||'').includes('el-cascader')){
await input.fill(String(value));const suggestion=page.locator('.el-cascader__suggestion-item:visible').filter({hasText:String(value)}).first();await suggestion.waitFor({state:'visible'});await suggestion.click();await root.locator('.el-dialog__header').click({position:{x:10,y:10}});return
}
const popupId=await input.getAttribute('aria-controls')
const popup=popupId?page.locator(`[id="${popupId}"]`):page.locator('.el-select__popper:visible').last()
const tree=popup.locator('.el-tree').last()
if(!await tree.count()&&await input.count()&&await input.isEditable())await input.fill(String(value))
await popup.waitFor({state:'visible'})
if(await tree.count()){
const treeItem=tree.locator('.el-tree-node__label,.el-select-dropdown__item').filter({hasText:new RegExp('^\\s*'+escape(value)+'\\s*$')}).first()
for(let i=0;i<20&&(!await treeItem.count()||!await treeItem.isVisible());i++){const caret=tree.locator('.el-tree-node__expand-icon:not(.is-leaf):not(.expanded):visible').first();if(!await caret.count())break;await caret.click()}
await treeItem.waitFor({state:'visible'});await treeItem.click();await root.locator('.el-dialog__header').click({position:{x:10,y:10}});return
}
let option=popup.locator('.el-select-dropdown__item').filter({hasText:new RegExp('^'+escape(value)+'$')}).first()
await option.waitFor({state:'visible'})
if(await option.count())await option.click()
else{
option=page.locator('.el-cascader__suggestion-list:visible .el-cascader__suggestion-item').filter({hasText:String(value)}).first()
if(await option.count())await option.click()
else{
option=page.locator('.el-select-dropdown:visible .el-tree-node__label').filter({hasText:new RegExp('^'+escape(value)+'$')}).first()
for(let i=0;i<20&&(!await option.count()||!await option.isVisible());i++){const caret=page.locator('.el-select-dropdown:visible .el-tree-node__expand-icon:not(.is-leaf):not(.expanded):visible').first();if(!await caret.count())break;await caret.click()}
if(await option.count()&&await option.isVisible())await option.click();else await input.press('Enter')
}
}
await root.locator('.el-dialog__header').click({position:{x:10,y:10}})
}
const escape=value=>String(value).replace(/[.*+?^${}()|[\]\\]/g,'\\$&')
async function radio(root,label,text){const group=field(root,label);if(await group.getByText(text,{exact:true}).count())await group.getByText(text,{exact:true}).click()}
async function submit(api,method='POST',button=/^确\s*定$/){const d=dialog(),handle=await d.elementHandle();const response=page.waitForResponse(r=>new URL(r.url()).pathname==='/dev-api'+api&&r.request().method()===method,{timeout:60000});response.catch(()=>{});await d.locator('.el-dialog__footer').getByRole('button',{name:button}).click();const body=await(await response).json();assert.equal(body.code,200,api+': '+body.msg);await handle.waitForElementState('hidden');state.operations.push({api,method,at:new Date().toISOString()});persist();return body}
async function add(button='新增'){await page.getByRole('button',{name:button,exact:true}).first().click();await dialog().waitFor({state:'visible'})}
async function mappings(){await ready('/system/data-replay');await page.getByRole('button',{name:'记录页面关联',exact:true}).click();const list=[];for(const[table,ids]of Object.entries(state.maps))for(const[sourceId,targetId]of Object.entries(ids))if(Number(sourceId)>0)list.push({table,sourceId:Number(sourceId),targetId:Number(targetId)});await dialog().locator('textarea').fill(JSON.stringify(list));await submit('/system/data-replay/mappings','POST','保存关联')}
async function restore(stage,label){await ready('/system/data-replay');const response=page.waitForResponse(r=>new URL(r.url()).pathname==='/dev-api/system/data-replay/restore/'+stage&&r.request().method()==='POST',{timeout:300000});await page.getByRole('button',{name:label,exact:true}).click();await page.locator('.el-message-box:visible').getByRole('button',{name:/确定|确认/}).click();const body=await(await response).json();assert.equal(body.code,200,stage+': '+body.msg);state.completed.push('restore:'+stage);persist()}
async function progress(stage,n,total){console.log(stage+' '+n+'/'+total);if(n%20===0||n===total)await page.screenshot({path:path.join(directory,stage+'-'+n+'.png')})}
async function dictionaries(){
const types=[...rows('sys_dict_type'),...['wms_item_category_group','wms_item_category','wms_item_unit'].map((dict_type,i)=>({dict_id:-i-1,dict_name:['物品大类','物品小类','物品单位'][i],dict_type,status:'0',remark:'真实数据演练:从源档案维护缺失的业务选项'}))]
await ready('/system/dict-types')
for(const row of types){if(mapped('sys_dict_type',row.dict_id))continue;const existing=(await get('/system/dict/type/list',{pageSize:1000,dictType:row.dict_type})).rows.find(r=>r.dictType===row.dict_type);if(existing){remember('sys_dict_type',row.dict_id,existing.dictId);continue}await add();const d=dialog();await fill(d,'字典名称',row.dict_name);await fill(d,'字典类型',row.dict_type);await fill(d,'备注',row.remark);await submit('/system/dict/type');const record=(await get('/system/dict/type/list',{pageSize:1000,dictType:row.dict_type})).rows.find(r=>r.dictType===row.dict_type);remember('sys_dict_type',row.dict_id,record.dictId)}
const units=[...new Set([...rows('product_info'),...rows('purchase_request')].map(r=>r.unit).filter(Boolean)), '未记录']
const categories=[...new Set(rows('product_info').map(r=>r.category).filter(Boolean))]
const values=[...rows('sys_dict_data'),...categories.map((dict_label,i)=>({dict_code:-100-i,dict_type:'wms_item_category',dict_label,dict_value:String(i+1),dict_sort:i+1,status:'0',list_class:'',remark:'沿用源物品分类,尚未分大类'})),...units.map((dict_label,i)=>({dict_code:-200-i,dict_type:'wms_item_unit',dict_label,dict_value:String(i+1),dict_sort:i+1,status:'0',list_class:''})),{dict_code:-301,dict_type:'wms_in_type',dict_label:'其他入库',dict_value:'5',dict_sort:5,status:'0',list_class:''},{dict_code:-302,dict_type:'wms_out_type',dict_label:'项目领用',dict_value:'4',dict_sort:4,status:'0',list_class:''}]
let n=0,current
for(const row of values){n++;if(mapped('sys_dict_data',row.dict_code))continue;const type=types.find(r=>r.dict_type===row.dict_type),id=mapped('sys_dict_type',type.dict_id);if(current!==id){await ready('/system/dict-data/index/'+id);current=id}await add();const d=dialog();await fill(d,'数据标签',row.dict_label);await fill(d,'数据键值',row.dict_value);await fill(d,'显示排序',row.dict_sort);await fill(d,'样式属性',row.css_class);await fill(d,'备注',row.remark);await submit('/system/dict/data');const list=(await get('/system/dict/data/list',{pageSize:1000,dictType:row.dict_type})).rows;const record=list.find(r=>r.dictValue===row.dict_value&&r.dictLabel===row.dict_label);assert.ok(record,'dictionary saved');remember('sys_dict_data',row.dict_code,record.dictCode);await progress('dictionaries',n,values.length)}
}
async function areas(){await ready('/businessBasics/area');let n=0;for(const row of rows('warehouse_area')){n++;if(mapped('warehouse_area',row.id))continue;await add();await fill(dialog(),'库区名称',row.area_name);await fill(dialog(),'备注',row.remark);await submit('/warehouse/area');const record=(await get('/warehouse/area/list',{pageSize:1000,areaName:row.area_name})).rows.find(r=>r.areaName===row.area_name);assert.ok(record);remember('warehouse_area',row.id,record.id);await progress('areas',n,rows('warehouse_area').length);if(n>=limit)break}}
async function departments(){await ready('/system/dept');let n=0;const pending=[...rows('sys_dept')];while(pending.length){const index=pending.findIndex(r=>r.parent_id===0||mapped('sys_dept',r.parent_id));assert.ok(index>=0,'department parent mapping');const row=pending.splice(index,1)[0];n++;if(mapped('sys_dept',row.dept_id))continue;if(row.parent_id===0)await add();else{const parent=rows('sys_dept').find(p=>p.dept_id===row.parent_id);const tr=page.locator('.el-table__body tr').filter({has:page.getByText(parent.dept_name,{exact:true})}).first();await tr.getByRole('button',{name:'新增',exact:true}).click();await dialog().waitFor({state:'visible'})}const d=dialog();await fill(d,'部门名称',row.dept_name);await fill(d,'显示排序',row.order_num);await fill(d,'负责人',row.leader);await fill(d,'联系电话',row.phone);await fill(d,'邮箱',row.email);await submit('/system/dept');const record=(await get('/system/dept/list')).data.find(r=>r.deptName===row.dept_name&&r.parentId===(row.parent_id===0?0:mapped('sys_dept',row.parent_id)));assert.ok(record);remember('sys_dept',row.dept_id,record.deptId);await progress('departments',n,rows('sys_dept').length)}}
async function posts(){await ready('/system/post');let n=0;for(const row of rows('sys_post')){n++;if(mapped('sys_post',row.post_id))continue;await add();const d=dialog();await fill(d,'岗位名称',row.post_name);await fill(d,'岗位编码',row.post_code);await fill(d,'岗位顺序',row.post_sort);await fill(d,'备注',row.remark);await submit('/system/post');const r=(await get('/system/post/list',{pageSize:1000})).rows.find(r=>r.postCode===row.post_code);remember('sys_post',row.post_id,r.postId);await progress('posts',n,rows('sys_post').length)}}
async function categories(){await ready('/project/info');await page.getByRole('button',{name:'经费科目',exact:true}).click();for(const row of rows('expense_category')){if(mapped('expense_category',row.id))continue;await dialog().getByRole('button',{name:'新增科目',exact:true}).click();const d=dialog();await fill(d,'科目编码',row.category_code);await fill(d,'科目名称',row.category_name);await fill(d,'排序',row.sort_order);await fill(d,'备注',row.remark);await submit('/project/info/category','POST','保存');const record=(await get('/project/info/category/list')).data.find(r=>r.categoryCode===row.category_code);assert.ok(record,row.category_code+' available');remember('expense_category',row.id,record.id)}await dialog().locator('.el-dialog__headerbtn').click()}
async function projects(){await ready('/project/info');let n=0;for(const row of rows('project_info')){n++;if(mapped('project_info',row.id))continue;await add('新增项目');const d=dialog();await fill(d,'项目名称',row.project_name);await select(d,'项目状态',({0:'立项',1:'进行中',2:'结题',3:'终止'})[row.project_status]);const total=rows('project_budget').filter(r=>r.project_id===row.id).reduce((s,r)=>s+Number(r.budget_amount),0);await fill(d,'总金额',total);await fill(d,'备注',row.remark);await submit('/project/info', 'POST','确定');const r=(await get('/project/info/list',{pageSize:1000,projectName:row.project_name})).rows.find(r=>r.projectName===row.project_name);remember('project_info',row.id,r.id);await progress('projects',n,rows('project_info').length)}}
async function budgets(){let current;for(const row of rows('project_budget')){if(mapped('project_budget',row.id))continue;const id=mapped('project_info',row.project_id);if(current!==id){await ready('/project/detail/'+id);await page.getByRole('tab',{name:'分类预算',exact:true}).click();current=id}await add();const d=dialog();await select(d,'费用分类',rows('expense_category').find(c=>c.id===row.expense_category_id).category_name);await fill(d,'预算金额',row.budget_amount);await fill(d,'备注',row.remark);await submit('/project/info/budget','POST','保存');const record=(await get('/project/info/'+id+'/budgets')).data.find(r=>r.expenseCategoryId===mapped('expense_category',row.expense_category_id));remember('project_budget',row.id,record.id)}console.log('project budgets recreated: '+rows('project_budget').length)}
async function roles(){
await ready('/system/role');const menus=(await get('/system/menu/list')).data
for(const row of rows('sys_role').filter(r=>r.role_id!==1)){
if(mapped('sys_role',row.role_id))continue;await add();const d=dialog();await fill(d,'角色名称',row.role_name);await fill(d,'权限字符',row.role_key);await fill(d,'角色顺序',row.role_sort);await fill(d,'备注',row.remark)
await d.getByText('父子联动',{exact:true}).click();await d.getByText('展开/折叠',{exact:true}).click()
await page.waitForFunction(count=>document.querySelectorAll('.el-dialog .el-tree-node').length>=count,menus.length)
await d.locator('.el-tree-node').evaluateAll(elements=>{for(const element of elements){let component=element.__vueParentComponent;while(component){if(component.props?.node?.data?.id!=null){element.dataset.replayNode=component.props.node.data.id;break}component=component.parent}}})
const wanted=new Set();for(const grant of rows('sys_role_menu').filter(g=>g.role_id===row.role_id)){const old=rows('sys_menu').find(m=>m.menu_id===grant.menu_id);if(!old)continue;const target=menus.find(m=>old.perms&&m.perms===old.perms)||menus.find(m=>m.menuId===old.menu_id&&m.path===old.path)||menus.find(m=>old.menu_type!=='F'&&m.path===old.path&&m.menuType===old.menu_type);if(!target){state.issues.push({kind:'source-menu-without-current-equivalent',roleId:row.role_id,sourceMenuId:old.menu_id,permission:old.perms});continue}wanted.add(target.menuId);let parent=target.parentId;while(parent){wanted.add(parent);parent=menus.find(m=>m.menuId===parent)?.parentId}}
for(const id of wanted){const node=d.locator(`.el-tree-node[data-replay-node="${id}"] > .el-tree-node__content .el-checkbox`);assert.equal(await node.count(),1,'menu checkbox '+id);if(!await node.locator('input').isChecked())await node.click()}
await submit('/system/role');const record=(await get('/system/role/list',{pageSize:1000})).rows.find(r=>r.roleKey===row.role_key);remember('sys_role',row.role_id,record.roleId);state.roleMenuMap||={};state.roleMenuMap[row.role_id]=[...wanted];persist();console.log('role recreated with explicit menus '+row.role_id)
}
}
async function users(){
await ready('/system/user');let n=0
async function removeHistoricalUser(row){
state.deletedUsers||=[];if(state.deletedUsers.includes(row.user_id))return
const records=(await get('/system/user/list',{pageSize:1000,userName:row.user_name})).rows
if(!records.some(r=>r.userId===mapped('sys_user',row.user_id))){state.deletedUsers.push(row.user_id);persist();return}
await page.locator('.el-form--inline').getByPlaceholder('请输入用户名称',{exact:true}).fill(row.user_name)
await page.getByRole('button',{name:'搜索',exact:true}).click()
const tr=page.locator('.el-table__body tr').filter({has:page.getByText(row.user_name,{exact:true})}).first();const button=tr.getByRole('button',{name:'删除',exact:true});await button.waitFor({state:'visible'})
const response=page.waitForResponse(r=>new URL(r.url()).pathname==='/dev-api/system/user/'+mapped('sys_user',row.user_id)&&r.request().method()==='DELETE',{timeout:30000});response.catch(()=>{})
await button.click();await page.locator('.el-message-box:visible').getByRole('button',{name:/确定|确认/}).click();assert.equal((await(await response).json()).code,200)
state.operations.push({api:'/system/user/'+mapped('sys_user',row.user_id),method:'DELETE',at:new Date().toISOString()});state.deletedUsers.push(row.user_id);persist();await page.getByRole('button',{name:'重置',exact:true}).click()
}
for(const row of rows('sys_user').filter(r=>r.user_id!==1)){
if(!mapped('sys_user',row.user_id)){
const existing=(await get('/system/user/list',{pageSize:1000,userName:row.user_name})).rows.find(r=>r.userName===row.user_name)
if(existing){assert.equal(existing.nickName,row.nick_name||row.user_name,'recover only the intended saved account');const info=await get('/system/user/'+existing.userId);assert.equal(info.data.deptId,mapped('sys_dept',row.dept_id));assert.deepEqual([...(info.roleIds||[])].sort(),rows('sys_user_role').filter(r=>r.user_id===row.user_id).map(r=>mapped('sys_role',r.role_id)).sort());remember('sys_user',row.user_id,existing.userId);state.issues.push({kind:'saved-response-lost-recovered',table:'sys_user',sourceId:row.user_id});persist()}
}
n++;if(mapped('sys_user',row.user_id)){if(row.del_flag==='2')await removeHistoricalUser(row);continue}await add();const d=dialog();await fill(d,'用户昵称',row.nick_name||row.user_name);await fill(d,'用户名称',row.user_name);await fill(d,'用户密码','Ui'+crypto.randomBytes(5).toString('hex')+'9!');await fill(d,'手机号码',row.phonenumber);await fill(d,'邮箱',row.email);await fill(d,'备注',row.remark)
if(row.dept_id)await select(d,'归属部门',rows('sys_dept').find(r=>r.dept_id===row.dept_id).dept_name)
for(const grant of rows('sys_user_role').filter(r=>r.user_id===row.user_id)){const role=rows('sys_role').find(r=>r.role_id===grant.role_id);await select(d,'角色',role.role_name)}
await select(d,'用户性别',({0:'男',1:'女',2:'未知'})[row.sex]);await submit('/system/user')
const record=(await get('/system/user/list',{pageSize:1000,userName:row.user_name})).rows.find(r=>r.userName===row.user_name);assert.ok(record);remember('sys_user',row.user_id,record.userId)
const current=(await get('/system/user/'+record.userId)).roleIds||[],expected=rows('sys_user_role').filter(r=>r.user_id===row.user_id).map(r=>mapped('sys_role',r.role_id));assert.deepEqual([...current].sort(),[...expected].sort(),'assigned roles match page selections')
if(row.del_flag==='2')await removeHistoricalUser(row)
await progress('users',n,rows('sys_user').length-1);if(n>=limit)break
}
}
async function configurations(){await ready('/system/config');for(const row of rows('sys_config')){if(mapped('sys_config',row.config_id))continue;await add();const d=dialog();await fill(d,'参数名称',row.config_name);await fill(d,'参数键名',row.config_key);await fill(d,'参数键值',row.config_value);await fill(d,'备注',row.remark);await radio(d,'系统内置',row.config_type==='Y'?'是':'否');await submit('/system/config');const record=(await get('/system/config/list',{pageSize:1000})).rows.find(r=>r.configKey===row.config_key);remember('sys_config',row.config_id,record.configId)}console.log('system configurations recreated: '+rows('sys_config').length)}
async function notices(){await ready('/system/notice');for(const row of rows('sys_notice')){if(mapped('sys_notice',row.notice_id))continue;await add();const d=dialog();await fill(d,'公告标题',row.notice_title);await select(d,'公告类型',row.notice_type==='1'?'通知':'公告');await d.locator('.ql-editor').fill(Buffer.from(row.notice_content||'','base64').toString('utf8'));await submit('/system/notice');const record=(await get('/system/notice/list',{pageSize:1000})).rows.find(r=>r.noticeTitle===row.notice_title);remember('sys_notice',row.notice_id,record.noticeId)}console.log('notices recreated: '+rows('sys_notice').length)}
async function jobs(){await ready('/monitor/job');for(const row of rows('sys_job')){if(mapped('sys_job',row.job_id))continue;await add();const d=dialog();await fill(d,'任务名称',row.job_name);await select(d,'任务分组',row.job_group==='DEFAULT'?'默认':'系统');await fill(d,'调用方法',row.invoke_target);await fill(d,'cron表达式',row.cron_expression);await radio(d,'执行策略',({1:'立即执行',2:'执行一次',3:'放弃执行'})[row.misfire_policy]);await radio(d,'是否并发',row.concurrent==='0'?'允许':'禁止');await submit('/monitor/job');const record=(await get('/monitor/job/list',{pageSize:1000})).rows.find(r=>r.jobName===row.job_name);remember('sys_job',row.job_id,record.jobId)}console.log('scheduled job definitions recreated with global scheduler stopped')}
async function items(){
await ready('/businessBasics/product');const recovered=new Map();for(const row of rows('purchase_request'))if(row.unit)recovered.set(row.product_id,row.unit)
const trim=v=>String(v??'').trim();let data=(await get('/warehouse/product/optionselect')).data,n=0
for(const row of rows('product_info')){
n++;if(mapped('product_info',row.id))continue
const match=r=>trim(r.productName)===trim(row.product_name)&&trim(r.brand)===trim(row.brand)&&trim(r.spec)===trim(row.spec)&&trim(r.category)===trim(row.category)
let record=data.find(match);const unit=row.unit||recovered.get(row.id)||'未记录'
if(!record){await add();const d=dialog();await fill(d,'物品名称',trim(row.product_name));await select(d,'品牌',trim(row.brand));await select(d,'类别',trim(row.category));await fill(d,'规格型号',trim(row.spec));await select(d,'单位',unit);await fill(d,'备注',row.remark);await submit('/warehouse/product');data=(await get('/warehouse/product/optionselect')).data;record=data.find(match)}
assert.ok(record,'saved catalog record '+row.id);assert.equal(record.unit,unit,'saved catalog unit');remember('product_info',row.id,record.id)
if(!row.unit)state.issues.push({kind:'source-unit-missing',sourceId:row.id,used:unit,recovered:recovered.has(row.id)})
await progress('items',n,rows('product_info').length);if(n>=limit)break
}
}
async function manualInbound(){
const originals=rows('in_record').filter(r=>r.purchase_request_id==null&&r.in_status===1)
const products=(await get('/warehouse/product/optionselect')).data,projects=(await get('/project/info/options')).data
await ready('/warehouse/inRecord');let n=0
for(const row of originals){
n++;const marker='WMS-REPLAY:IN:'+row.id,remark=[marker,row.in_no,row.remark].filter(Boolean).join(';').slice(0,300),date=String(row.confirm_time||row.create_time).slice(0,10)
let record=mapped('in_record',row.id)?(await get('/warehouse/in/'+mapped('in_record',row.id))).data:null
if(!record){record=(await get('/warehouse/in/list',{pageSize:1000})).rows.find(r=>r.remark===remark);if(record)remember('in_record',row.id,record.id)}
if(!record){
await add('其他入库');const d=dialog(),product=products.find(p=>p.id===mapped('product_info',row.product_id)),project=projects.find(p=>p.id===mapped('project_info',row.source_project_id))
assert.ok(product&&project,'inbound references mapped')
await select(d,'库区',rows('warehouse_area').find(a=>a.id===row.area_id).area_name)
await select(d,'物品',product.productName+'('+[product.brand,product.category,product.spec,product.unit].filter(Boolean).join(' / ')+')')
await select(d,'库存接收项目',project.projectName+'('+project.projectCode+')')
await fill(d,'入库数量',row.in_num);await fill(d,'业务日期',date);await fill(d,'备注',remark)
await submit('/warehouse/in');record=(await get('/warehouse/in/list',{pageSize:1000})).rows.find(r=>r.remark===remark);assert.ok(record,'inbound saved');remember('in_record',row.id,record.id)
}
if(record.inStatus!==1){
await ready('/warehouse/inRecord?inNo='+encodeURIComponent(record.inNo));await page.locator('.el-table__body tr').filter({has:page.getByText(record.inNo,{exact:true})}).getByRole('button',{name:'入库',exact:true}).click()
await dialog().waitFor({state:'visible'});await fill(dialog(),'入库日期',date);await fill(dialog(),'备注',remark)
await submit('/warehouse/in/confirm/'+record.id,'PUT','确认入库')
const confirmed=(await get('/warehouse/in/'+record.id)).data;assert.equal(confirmed.inStatus,1);assert.equal(Number(confirmed.inNum),Number(row.in_num))
}
await progress('manual-in',n,originals.length);if(n>=limit)break
}
}
async function supplier(){
await ready('/businessBasics/suppliers');const name='历史供应商(源库未记录)';let existing=(await get('/warehouse/suppliers')).data.find(r=>r.name===name)
if(!existing){await add('新增供应商');await fill(dialog(),'名称',name);await fill(dialog(),'备注','源库没有供应商档案;此记录只用于历史采购回放,原供应商信息未记录。');await submit('/warehouse/suppliers','POST','保存');existing=(await get('/warehouse/suppliers')).data.find(r=>r.name===name)}
assert.ok(existing);state.extra||={};state.extra.supplierId=existing.id;persist()
}
const tsvCell=value=>{const s=String(value??'');return /[\t\r\n"]/.test(s)?'"'+s.replaceAll('"','""')+'"':s}
async function confirmGroup(group,batchId){
const sheet=(await get('/warehouse/purchase/sheet/'+batchId)).data,wanted=new Set(group.rows.filter(r=>rows('purchase_arrival').some(a=>a.purchase_request_id===r.id)).map(r=>mapped('purchase_request',r.id)))
if(!sheet.rows.some(r=>wanted.has(r.id)&&!r.priceLocked))return
await ready('/procurement/details?purchaseBatchId='+batchId);await page.locator('.sheet-grid').waitFor()
if(sheet.rows.some(r=>!wanted.has(r.id))){
await page.locator('.sheet-grid .el-table__header .el-checkbox').first().click()
for(const row of sheet.rows.filter(r=>!wanted.has(r.id))){await page.getByPlaceholder('清单内搜索',{exact:true}).fill(row.requestNo);const tr=page.locator('.sheet-grid .el-table__body tr');await tr.locator('.el-checkbox').first().click()}
await page.getByPlaceholder('清单内搜索',{exact:true}).fill('')
}
const response=page.waitForResponse(r=>new URL(r.url()).pathname==='/dev-api/warehouse/purchase/sheet/'+batchId+'/confirm'&&r.request().method()==='POST',{timeout:60000});response.catch(()=>{});await page.getByRole('button',{name:'确认采购',exact:true}).click();await page.locator('.el-message-box:visible').getByRole('button',{name:/确定|确认/}).click();const body=await(await response).json();assert.equal(body.code,200,body.msg)
for(const row of body.data.rows)assert.equal(!!row.priceLocked,wanted.has(row.id),'only originally arrived lines locked')
state.operations.push({api:'/warehouse/purchase/sheet/'+batchId+'/confirm',method:'POST',rows:wanted.size,at:new Date().toISOString()});persist()
}
async function outHistory(){
let n=0;const products=(await get('/warehouse/product/optionselect')).data
for(const row of rows('out_record')){
n++;if(mapped('out_record',row.id))continue
const marker='WMS-REPLAY:OUT:'+row.id,existing=(await get('/warehouse/out/list',{pageSize:1000})).rows.find(r=>r.remark===marker)
if(existing){remember('out_record',row.id,existing.id);continue}
const owner=rows('stock_info').find(s=>s.area_id===row.area_id&&s.product_id===row.product_id)?.source_project_id||1
const projectId=mapped('project_info',owner),product=products.find(p=>p.id===mapped('product_info',row.product_id)),area=rows('warehouse_area').find(a=>a.id===row.area_id)
const stock=(await get('/warehouse/stock/list',{pageSize:1000,projectId,areaId:mapped('warehouse_area',row.area_id)})).rows.find(s=>s.productId===product.id)
assert.ok(stock&&Number(stock.stockNum)>=Number(row.out_num),'stock sufficient for original issue '+row.id)
await ready('/warehouse/stock?projectId='+projectId)
const form=page.locator('.el-form--inline').first(),control=field(form,'库区').locator('.el-select');await control.click();await page.locator('.el-select-dropdown__item:visible').filter({hasText:new RegExp('^'+escape(area.area_name)+'$')}).click()
await fill(form,'关键词',product.productName);const search=page.waitForResponse(r=>r.url().includes('/warehouse/stock/list'));await form.getByRole('button',{name:'搜索',exact:true}).click();await search
const candidates=page.locator('.el-table__body tr').filter({has:page.getByText(product.productName,{exact:true})});let tr=candidates
if(await candidates.count()>1)tr=candidates.filter({hasText:product.spec||product.brand})
assert.equal(await tr.count(),1,'unique stock row for original issue '+row.id);await tr.getByRole('button',{name:'操作',exact:true}).click();await page.getByRole('menuitem',{name:'项目领用',exact:true}).click();await dialog().waitFor()
const d=dialog();await fill(d,'日期',String(row.out_time).slice(0,10));await fill(d,'备注',marker);await d.locator('.el-table__body .el-input-number input').fill(String(row.out_num))
const response=page.waitForResponse(r=>new URL(r.url()).pathname==='/dev-api/warehouse/stock/out'&&r.request().method()==='POST',{timeout:60000});response.catch(()=>{});await d.locator('.el-dialog__footer').getByRole('button',{name:'确认',exact:true}).click();assert.equal((await(await response).json()).code,200)
const saved=(await get('/warehouse/out/list',{pageSize:1000})).rows.find(r=>r.remark===marker);assert.ok(saved);remember('out_record',row.id,saved.id);state.operations.push({api:'/warehouse/stock/out',method:'POST',at:new Date().toISOString()});persist();await progress('out-history',n,rows('out_record').length);if(n>=limit)break
}
}
async function arrivals(){
let n=0
for(const row of rows('purchase_arrival')){
n++;const requestId=mapped('purchase_request',row.purchase_request_id),request=(await get('/warehouse/purchase/'+requestId)).data,marker='WMS-REPLAY:ARRIVAL:'+row.id
let record=(await get('/warehouse/purchase/arrival/'+requestId)).data.find(a=>a.id===mapped('purchase_arrival',row.id)||a.remark===marker)
if(!record||Number(record.acceptanceStatus)===0){
await ready('/procurement/arrival?requestNo='+encodeURIComponent(request.requestNo));await page.locator('.el-table__body tr').filter({hasText:request.materialName}).getByRole('button',{name:/登记到货|验收到货|继续登记/}).click();await dialog().waitFor();const d=dialog()
if(!record){
await fill(d,'本次到货',row.arrival_quantity);await fill(d,'到货日期',row.arrival_date);await fill(d,'备注',marker)
const response=page.waitForResponse(r=>new URL(r.url()).pathname==='/dev-api/warehouse/purchase/arrival'&&r.request().method()==='POST',{timeout:60000});response.catch(()=>{});await d.getByRole('button',{name:'登记到货',exact:true}).click();assert.equal((await(await response).json()).code,200)
record=(await get('/warehouse/purchase/arrival/'+requestId)).data.find(a=>a.remark===marker);assert.ok(record);remember('purchase_arrival',row.id,record.id);state.operations.push({api:'/warehouse/purchase/arrival',method:'POST',at:new Date().toISOString()});persist()
}
if(Number(record.acceptanceStatus)===0){
const tr=d.locator('.el-table__body tr').filter({hasText:record.arrivalNo}),response=page.waitForResponse(r=>new URL(r.url()).pathname==='/dev-api/warehouse/purchase/arrival/'+record.id+'/accept'&&r.request().method()==='PUT',{timeout:60000});response.catch(()=>{});await tr.getByRole('button',{name:row.acceptance_status===1?'通过':'拒收',exact:true}).click();const box=page.locator('.el-message-box:visible');if(row.acceptance_status!==1)await box.locator('input').fill(row.acceptance_remark||'历史拒收');await box.getByRole('button',{name:/确定|确认/}).click();assert.equal((await(await response).json()).code,200);state.operations.push({api:'/warehouse/purchase/arrival/'+record.id+'/accept',method:'PUT',at:new Date().toISOString()});persist()
}
}
if(!mapped('purchase_arrival',row.id))remember('purchase_arrival',row.id,record.id)
record=(await get('/warehouse/purchase/arrival/'+requestId)).data.find(a=>a.id===record.id);assert.equal(record.acceptanceStatus,row.acceptance_status,'source acceptance status')
if(row.acceptance_status===1){
const original=rows('in_record').find(i=>i.arrival_id===row.id),inRows=(await get('/warehouse/in/list',{pageSize:1000})).rows,root=inRows.find(i=>i.arrivalId===record.id&&i.receiptRoot);assert.ok(original&&root,'accepted arrival generated receipt root')
if(original.in_status===0)remember('in_record',original.id,root.id)
else if(!mapped('in_record',original.id)){
const receiptMarker='WMS-REPLAY:RECEIPT:'+original.id;let child=inRows.find(i=>i.parentInId===root.id&&i.remark===receiptMarker)
if(!child){await ready('/warehouse/inRecord?inNo='+encodeURIComponent(root.inNo));await page.locator('.el-table__body tr').filter({hasText:root.inNo}).getByRole('button',{name:'入库',exact:true}).click();await dialog().waitFor();await select(dialog(),'库区',rows('warehouse_area').find(a=>a.id===original.area_id).area_name);await fill(dialog(),'入库日期',String(original.confirm_time).slice(0,10));await fill(dialog(),'备注',receiptMarker);await submit('/warehouse/in/receive/'+root.id,'POST','确认入库');child=(await get('/warehouse/in/list',{pageSize:1000})).rows.find(i=>i.parentInId===root.id&&i.remark===receiptMarker)}
assert.ok(child);assert.equal(child.inStatus,1);assert.equal(Number(child.inNum),Number(original.in_num));remember('in_record',original.id,child.id)
}
}
await progress('arrivals',n,rows('purchase_arrival').length);if(n>=limit)break
}
}
async function cancelRejected(){
for(const sourceArrival of rows('purchase_arrival').filter(a=>a.acceptance_status===2)){
const request=(await get('/warehouse/purchase/'+mapped('purchase_request',sourceArrival.purchase_request_id))).data;if(Number(request.lockedAmount)===0&&request.purchaseStatus===5)continue
assert.equal(Number(request.acceptedQuantity),0);assert.equal(Number(request.pendingArrivalQuantity),0)
await ready('/procurement/details');const form=page.locator('.el-form--inline').first();await fill(form,'批次',request.purchaseBatchNo);await form.getByRole('button',{name:'搜索',exact:true}).click();await page.locator('.el-table__body tr').filter({hasText:request.purchaseBatchNo}).getByRole('button',{name:'打开',exact:true}).click();await page.locator('.sheet-grid').waitFor();await page.getByPlaceholder('清单内搜索',{exact:true}).fill(request.materialName)
const response=page.waitForResponse(r=>new URL(r.url()).pathname==='/dev-api/warehouse/purchase/'+request.id+'/cancel-remaining'&&r.request().method()==='POST',{timeout:60000});response.catch(()=>{});await page.locator('.sheet-grid .el-table__body tr').filter({hasText:request.materialName}).getByRole('button',{name:'取消剩余',exact:true}).click();const box=page.locator('.el-message-box:visible');await box.locator('input').fill('历史拒收,冲回未采购金额;源库原稿状态随后按历史恢复');await box.getByRole('button',{name:/确定|确认/}).click();assert.equal((await(await response).json()).code,200);assert.equal(Number((await get('/warehouse/purchase/'+request.id)).data.lockedAmount),0);state.operations.push({api:'/warehouse/purchase/'+request.id+'/cancel-remaining',method:'POST',at:new Date().toISOString()});persist()
}
}
async function cleanupDemo(){
const id=1338;if(Object.values(state.maps.project_info).includes(id))return
const listed=(await get('/project/info/list',{pageSize:1000,projectName:'演示项目'})).rows.find(r=>r.id===id);if(!listed)return
assert.equal(listed.projectCode,'PM-7f7f7da5-824');assert.equal(Number(listed.spentAmount),0)
assert.equal((await get('/warehouse/stock/list',{pageSize:1000,projectId:id,includeZero:true})).rows.length,0);assert.equal((await get('/warehouse/purchase/list',{pageSize:1000,projectId:id})).rows.length,0)
await ready('/project/info');const form=page.locator('.el-form--inline').first();await fill(form,'项目编码',listed.projectCode);const result=page.waitForResponse(r=>r.url().includes('/project/info/list'));await form.getByRole('button',{name:'搜索',exact:true}).click();await result
const tr=page.locator('.el-table__body tr').filter({hasText:listed.projectCode});await tr.getByRole('button',{name:'更多',exact:true}).click();const response=page.waitForResponse(r=>new URL(r.url()).pathname==='/dev-api/project/info/'+id&&r.request().method()==='DELETE',{timeout:60000});response.catch(()=>{});await page.getByRole('menuitem',{name:'删除',exact:true}).click();await page.locator('.el-message-box:visible').getByRole('button',{name:/确定|确认/}).click();assert.equal((await(await response).json()).code,200);state.operations.push({api:'/project/info/'+id,method:'DELETE',at:new Date().toISOString()});state.issues.push({kind:'old-isolated-test-demo-removed',id});persist()
}
async function draftQuotes(){
for(const [key,group]of Object.entries(state.purchaseGroups)){
const originals=group.sourceIds.map(id=>rows('purchase_request').find(r=>r.id===id)).filter(r=>r.purchase_status===0&&Number(r.estimated_unit_price)>0&&!rows('purchase_arrival').some(a=>a.purchase_request_id===r.id));if(!originals.length)continue
const current=await Promise.all(originals.map(r=>get('/warehouse/purchase/'+mapped('purchase_request',r.id)).then(v=>v.data)));if(current.every((r,i)=>Number(r.finalUnitPrice)===Number(originals[i].estimated_unit_price)))continue
if(group.batchId){await ready('/procurement/details?purchaseBatchId='+group.batchId);await page.getByRole('button',{name:'编辑',exact:true}).click()}
else{await ready('/procurement/details?view=unbatched');await page.locator('.purchase-lookup .el-table__header .el-checkbox').first().click();await page.locator('.purchase-lookup .list-actions').getByRole('button',{name:'编辑',exact:true}).click()}
await page.locator('.sheet-grid').waitFor()
for(let i=0;i<current.length;i++){await page.getByPlaceholder('清单内搜索',{exact:true}).fill(current[i].requestNo);const cell=page.locator('.sheet-cell.cell-editable[data-field="finalUnitPrice"]');await cell.click();await cell.locator('input').fill(String(originals[i].estimated_unit_price));await page.locator('.sheet-footer > div').first().click({position:{x:8,y:8}})}
await page.getByPlaceholder('清单内搜索',{exact:true}).fill('');const response=page.waitForResponse(r=>new URL(r.url()).pathname==='/dev-api/warehouse/purchase/sheet'&&r.request().method()==='POST',{timeout:60000});response.catch(()=>{});await page.getByRole('button',{name:group.batchId?/保存清单\s*\/\s*报价/:'保存未组批明细',exact:true}).click();assert.equal((await(await response).json()).code,200)
for(const original of originals){const saved=(await get('/warehouse/purchase/'+mapped('purchase_request',original.id))).data;assert.equal(Number(saved.finalUnitPrice),Number(original.estimated_unit_price));assert.equal(!!saved.priceLocked,false)}state.operations.push({api:'/warehouse/purchase/sheet',method:'POST',purpose:'preserve-original-draft-quotes',rows:originals.length,at:new Date().toISOString()});persist();console.log('draft quote fields preserved '+key+' '+originals.length)
}
}
async function verify(){
const result=(await get('/system/data-replay/verify')).data;fs.writeFileSync(path.join(directory,'verification.json'),JSON.stringify(result,null,2));console.log(JSON.stringify(result));assert.equal(result.passed,true,'real-data final checks')
for(const [name,route]of [['projects','/project/info'],['catalog','/businessBasics/product'],['purchase','/procurement/details'],['arrival','/procurement/arrival'],['stock','/warehouse/stock'],['pending','/warehouse/pending'],['roles','/system/role'],['logs','/system/operlog']]){await ready(route);await page.screenshot({path:path.join(directory,'final-'+name+'.png')});assert.equal(await page.locator('.el-message--error:visible').count(),0,'page error '+route)}
}
async function purchasing(){
assert.ok(state.extra?.supplierId,'historical supplier must exist');await context.grantPermissions(['clipboard-read','clipboard-write'],{origin:frontend})
const products=(await get('/warehouse/product/optionselect')).data
const groups=[{key:'original-batch',name:rows('purchase_batch')[0].batch_name,date:rows('purchase_batch')[0].create_time.slice(0,10),rows:rows('purchase_request').filter(r=>r.purchase_batch_id!=null),sourceBatch:rows('purchase_batch')[0].id},
{key:'legacy-without-batch',name:'历史未分批采购',date:'2026-10-10',rows:rows('purchase_request').filter(r=>r.purchase_batch_id==null&&r.purchase_status===4)},
{key:'drafts',unbatched:true,rows:rows('purchase_request').filter(r=>r.purchase_batch_id==null&&r.purchase_status!==4)}]
state.purchaseGroups||={}
for(const group of groups){
if(group.rows.every(r=>mapped('purchase_request',r.id))){if(!group.unbatched)await confirmGroup(group,state.purchaseGroups[group.key].batchId);continue}
await ready('/procurement/details');await page.getByRole('button',{name:group.unbatched?'新增未组批':'新增采购批次',exact:true}).click();await page.locator('.sheet-grid').waitFor()
if(!group.unbatched){const form=page.locator('.batch-form');await fill(form,'名称',group.name);await fill(form,'日期',group.date);const control=field(form,'供应商').locator('.el-select');await control.click();await page.locator('.el-select-dropdown__item:visible').filter({hasText:'历史供应商(源库未记录)'}).click();await page.locator('.sheet-footer > div').first().click({position:{x:8,y:8}})}
await page.locator('.sheet-toolbar').getByText('更多列',{exact:true}).click()
const text=group.rows.map(row=>{const item=products.find(p=>p.id===mapped('product_info',row.product_id));assert.ok(item);const arrival=rows('purchase_arrival').find(a=>a.purchase_request_id===row.id);return [item.productName,item.spec,row.quantity,item.unit,arrival?.actual_unit_price??'',rows('project_info').find(p=>p.id===row.project_id).project_name,rows('expense_category').find(c=>c.id===row.expense_category_id).category_name,item.brand,item.category,row.purchase_link,'','SELF','','WMS-REPLAY:PURCHASE:'+row.id].map(tsvCell).join('\t')}).join('\n')
const cell=page.locator('.sheet-grid .sheet-cell.cell-editable[data-field="materialName"]').first();await cell.click();await cell.locator('input').first().focus();await page.evaluate(value=>navigator.clipboard.writeText(value),text);await page.keyboard.press('Control+V')
await page.locator('.sheet-footer > div').first().click({position:{x:8,y:8}})
const response=page.waitForResponse(r=>new URL(r.url()).pathname==='/dev-api/warehouse/purchase/sheet'&&r.request().method()==='POST',{timeout:60000});response.catch(()=>{});await page.getByRole('button',{name:group.unbatched?'保存未组批明细':/保存清单\s*\/\s*报价/}).click();const body=await(await response).json();assert.equal(body.code,200,body.msg)
for(const row of group.rows){const saved=body.data.rows.find(r=>r.remark==='WMS-REPLAY:PURCHASE:'+row.id);assert.ok(saved,'purchase source marker saved '+row.id);remember('purchase_request',row.id,saved.id)}
if(group.sourceBatch)remember('purchase_batch',group.sourceBatch,body.data.batch.id)
state.purchaseGroups[group.key]={batchId:body.data.batch?.id,sourceIds:group.rows.map(r=>r.id)};state.operations.push({api:'/warehouse/purchase/sheet',method:'POST',rows:group.rows.length,at:new Date().toISOString()});persist();await page.screenshot({path:path.join(directory,'purchase-'+group.key+'.png')})
if(!group.unbatched)await confirmGroup(group,body.data.batch.id)
console.log('purchase group '+group.key+' rows='+group.rows.length)
}
}
async function login(){
const saved=path.join(directory,'browser-state.json');context=await browser.newContext({viewport:{width:1440,height:960},...(fs.existsSync(saved)?{storageState:saved}:{})});page=await context.newPage();page.setDefaultTimeout(15000);page.on('pageerror',e=>{state.issues.push({kind:'pageerror',message:e.message});persist()});
await page.goto(frontend+'/system/data-replay',{waitUntil:'domcontentloaded'});await page.waitForFunction(()=>document.querySelector('input[placeholder="账号"]')||document.querySelector('.desktop-viewport > .app-container'),{timeout:60000});if(await page.getByPlaceholder('账号').isVisible()){await page.getByPlaceholder('账号').fill(username);await page.getByPlaceholder('密码').fill(password);await page.getByRole('button',{name:/^登\s*录$/}).click();await page.waitForURL('**/system/data-replay',{timeout:60000})}await page.locator('.desktop-viewport > .app-container').waitFor();token=(await context.cookies()).find(r=>r.name==='Admin-Token')?.value;assert.ok(token,'UI login session');await context.storageState({path:saved})
}
async function reset(){assert.equal(state.reset,false,'Reset already completed; continue with the next stage');await ready('/system/data-replay');await page.getByPlaceholder('输入目标库名称确认清理').fill('cmvr-project-dev');const response=page.waitForResponse(r=>new URL(r.url()).pathname==='/dev-api/system/data-replay/reset'&&r.request().method()==='POST',{timeout:300000});await page.getByRole('button',{name:'清理目标并开始演练',exact:true}).click();await page.locator('.el-message-box:visible').getByRole('button',{name:/确定|确认/}).click();const body=await(await response).json();assert.equal(body.code,200,body.msg);state.reset=true;persist();await page.screenshot({path:path.join(directory,'target-reset.png')});console.log('RESET target=cmvr-project-dev; source read-only; current menus retained')}
const actions={dictionaries,areas,departments,posts,categories,projects,budgets,items,roles,users,configurations,notices,jobs,mappings,reset,supplier,purchasing,arrivals,verify,'zero-balances':()=>restore('zero-balances','恢复历史零库存关联'),'draft-quotes':draftQuotes,'cleanup-demo':cleanupDemo,'cancel-rejected':cancelRejected,'manual-in':manualInbound,'out-history':outHistory,'accounts':()=>restore('accounts','恢复原密码与账号历史'),'audit':()=>restore('audit','恢复系统运行历史'),'stock-history':()=>restore('stock-history','恢复库存来源历史'),'business-history':()=>restore('business-history','恢复历史流水与关系'),'metadata':()=>restore('metadata','恢复原单号和原时间')}
;(async()=>{browser=await chromium.launch();try{await login();if(mode==='plan'){await page.screenshot({path:path.join(directory,'source-target-plan.png')});const plan=(await get('/system/data-replay/plan')).data;console.log(JSON.stringify({source:plan.source,target:plan.target,menus:plan.menus,tables:plan.tables.length,sourceRows:plan.tables.reduce((s,r)=>s+Number(r.sourceCount),0)}));return}if(mode!=='reset')assert.equal(state.reset,true,'Target reset must complete before business creation');assert.ok(actions[mode],'Unknown phase '+mode);await actions[mode]();if(!['reset','mappings'].includes(mode)&&limit===Infinity){state.completed.push(mode);persist()}console.log('PAGE PHASE PASS '+mode+'; real UI requests='+state.operations.length)}catch(error){await page?.screenshot({path:path.join(directory,'failure-'+mode+'.png')}).catch(()=>{});throw error}finally{await browser?.close()}})().catch(error=>{console.error(error);process.exitCode=1})