cmvr-wms/scripts/projectdev/vue3-nested-dialog-race-regression.cjs

124 lines
11 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 assert = require('node:assert/strict')
const { chromium, frontend, backend, username, password } = require('./vue3-test-runtime.cjs')
const pause = ms => new Promise(resolve => setTimeout(resolve, ms))
const gate = () => { let release; const promise = new Promise(resolve => { release = resolve }); return { promise, release } }
// Real click/close/reopen paths with isolated stock/BOM fixtures. No business write reaches the server.
;(async () => {
const login = await fetch(backend + '/login', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ username, password }) }).then(r => r.json())
assert.equal(login.code, 200)
const browser = await chromium.launch(), errors = [], writes = [], blocked = []
const stockGate = gate(); let childGate = gate(), holdChild = true, failStock = false, failChild = false
const childReads = {}
try {
const context = await browser.newContext({ viewport: { width: 1366, height: 768 } })
await context.addCookies([{ name: 'Admin-Token', value: login.token, url: frontend }])
const stocks = [11, 22].map((id, i) => ({ id: 901 + i, projectId: 1, projectName: '隔离审查项目', productId: id, productName: 'AUDIT-库存' + (i ? 'B' : 'A'), areaId: 1, areaName: '审查库区', stockNum: 2, unit: '个' }))
const bom = id => ({ id, itemId: id + 1000, itemName: 'AUDIT-BOM-' + id, versionTag: id === 311 ? 'A原版' : id === 322 ? 'B原版' : '主BOM', scopeType: id === 302 ? 'PROJECT' : 'PUBLIC', lines: [301, 302].includes(id) ? [311, 322].map(child => ({ itemId: child + 1000, itemName: 'AUDIT-用料' + (child === 311 ? 'A' : 'B'), unit: '个', unitQuantity: 1, childBomId: child, childVersionTag: child === 311 ? 'A原版' : 'B原版' })) : [] })
await context.route('**/dev-api/**', async route => {
const req = route.request(), url = new URL(req.url()), path = url.pathname.replace('/dev-api', ''), method = req.method()
const ok = data => route.fulfill({ json: { code: 200, data } })
if (!['GET', 'HEAD'].includes(method)) {
if (method === 'POST' && path === '/warehouse/stock/move/422/revoke') { writes.push({ path, data: req.postDataJSON() }); return ok({}) }
if (method === 'POST' && path === '/production/bom') { const data = req.postDataJSON(); assert.equal(data.id, 322); writes.push({ path, data }); return ok(data) }
blocked.push(method + ' ' + path); return route.abort('blockedbyclient')
}
if (path === '/warehouse/stock/list') return route.fulfill({ json: { code: 200, rows: stocks, total: 2 } })
if (path === '/warehouse/stock/events' || path === '/warehouse/stock/adjustments') {
const id = Number(url.searchParams.get('itemId'))
if (id === 11) await stockGate.promise
if (failStock && path.endsWith('/events')) return route.fulfill({ json: { code: 500, msg: 'AUDIT-流水加载失败' } })
return ok(path.endsWith('/events') ? [{ id: id === 11 ? 411 : 422, projectId: 1, itemId: id, areaId: 1, eventNo: id === 11 ? 'AUDIT-EVT-A' : 'AUDIT-EVT-B', eventKey: 'MOVE:' + id + ':in', eventType: 'RECEIPT', quantity: 2, originalCost: 20, effectiveCost: 20, active: true }] : [{ event_no: id === 11 ? 'AUDIT-COST-A' : 'AUDIT-COST-B', old_amount: 10, new_amount: 20, delta_amount: 10 }])
}
if (/^\/production\/bom\/(301|302|311|322)$/.test(path)) {
const id = Number(path.split('/').pop()); childReads[id] = (childReads[id] || 0) + 1
if (id === 311 && holdChild) await childGate.promise
if (id === 311 && failChild) return route.fulfill({ json: { code: 500, msg: 'AUDIT-下级BOM加载失败' } })
return ok(bom(id))
}
if (path === '/production/bom/options') return ok([bom(311), bom(322)])
if (path === '/production/bom/items') return ok([])
if (path === '/production/bom/items-page') return ok({ rows: [], total: 0 })
return route.continue()
})
const page = await context.newPage(); page.setDefaultTimeout(15000); page.on('pageerror', error => errors.push(error.message))
await page.goto(frontend + '/warehouse/stock')
const openStock = async name => page.getByRole('row').filter({ hasText: 'AUDIT-库存' + name }).getByRole('button', { name: '流水', exact: true }).click()
const stockDialog = page.getByRole('dialog',{name:'库存流水',exact:true})
await openStock('A'); await stockDialog.locator('.el-loading-mask').waitFor({ state: 'visible' })
await stockDialog.locator('.el-dialog__headerbtn').click(); await stockDialog.waitFor({ state: 'hidden' })
await openStock('B'); await stockDialog.getByText('AUDIT-EVT-B', { exact: true }).waitFor()
stockGate.release(); await pause(150)
assert.equal(await stockDialog.getByText('AUDIT-EVT-A', { exact: true }).count(), 0)
await stockDialog.getByRole('tab', { name: '成本调整(1)', exact: true }).click()
await stockDialog.getByText('AUDIT-COST-B',{exact:true}).waitFor();assert.equal(await page.locator('.el-dialog:visible').count(),1)
assert.equal(await page.getByText('AUDIT-COST-A', { exact: true }).count(), 0)
await stockDialog.getByRole('tab',{name:'库存流水',exact:true}).click()
await stockDialog.getByRole('button', { name: '撤销移库', exact: true }).click()
const prompt = page.locator('.el-message-box'); await prompt.locator('input').fill('隔离回归,不执行真实撤销')
await prompt.getByRole('button', { name: '确定', exact: true }).click()
await page.waitForResponse(r => r.url().includes('/warehouse/stock/events') && new URL(r.url()).searchParams.get('itemId') === '22')
assert.equal(writes[0].path, '/warehouse/stock/move/422/revoke')
console.log('PASS 库存A加载中可关闭;打开B后旧A响应不能覆盖流水/成本,撤销仅指向B行')
await stockDialog.locator('.el-dialog__headerbtn').click(); await stockDialog.waitFor({ state: 'hidden' })
failStock = true; await openStock('B'); await stockDialog.locator('.el-alert').waitFor()
assert.equal(await stockDialog.getByText('AUDIT-EVT-B', { exact: true }).count(), 0)
failStock = false; await stockDialog.locator('.el-alert').getByRole('button', { name: '重试', exact: true }).click()
await stockDialog.getByText('AUDIT-EVT-B', { exact: true }).waitFor()
await stockDialog.locator('.el-dialog__headerbtn').click(); await stockDialog.waitFor({ state: 'hidden' })
console.log('PASS 库存流水失败清空旧记录并可原地重试')
await page.evaluate(async () => {
const { createApp, h, ElementPlus, nextTick } = await import('/tests/browser-runtime.js')
const { default: store } = await import('/src/store/index.js'), { default: useUser } = await import('/src/store/modules/user.js')
const { default: business } = await import('/src/plugins/business.js'), { default: Editor } = await import('/src/components/BomEditor/index.vue')
useUser(store).permissions = ['*:*:*']; document.querySelector('#app')?.remove()
const el = document.createElement('div'); document.body.append(el)
const app = createApp({ render: () => h(Editor, { ref: 'editor' }) }); app.use(store); app.use(ElementPlus); business(app); app.config.globalProperties.$router=(await import('/src/router/index.js')).default; (await import('/src/store/modules/user.js')).default(store).permissions=['*:*:*']
Object.assign(app.config.globalProperties, { $route: { path: '/audit-bom' }, $modal: { msgSuccess() {}, msgWarning() {}, msgError() {} }, download() {} })
window.auditBomApp = app; window.auditBomRoot = app.mount(el); await nextTick(); window.editor = window.auditBomRoot.$refs.editor
await window.editor.open({ id: 301 })
})
const parent = page.locator('.el-dialog:visible').first(), child = () => page.locator('.el-dialog:visible').last()
const openChild = async name => parent.getByRole('row').filter({ hasText: 'AUDIT-用料' + name }).getByRole('button', { name: '维护', exact: true }).click()
await openChild('A'); await child().locator('.el-loading-mask').waitFor({ state: 'visible' })
await page.evaluate(() => { window.staleChildContext = window.editor.childContext })
await child().locator('.el-dialog__headerbtn').click(); await page.waitForFunction(() => !window.editor.childId)
await openChild('B'); await child().getByText('AUDIT-BOM-322', { exact: true }).waitFor()
childGate.release(); holdChild = false; await pause(150)
assert.equal(await page.evaluate(() => window.editor.$refs.child.form.id), 322)
assert.equal(childReads[322], 1, 'Opening a child should only perform one GET')
await page.evaluate(() => {
window.editor.childSaved({ id: 311, versionTag: '错误旧回填' }, window.staleChildContext)
window.editor.childSaved({ id: 311, versionTag: '错误B身份' }, window.editor.childContext)
const context = window.editor.childContext
context.row.childBomId = 399
window.editor.childSaved({ id: 322, versionTag: '已换版本不能回填' }, context)
context.row.childBomId = 322
})
assert.deepEqual(await page.evaluate(() => window.editor.form.lines.map(row => row.childVersionTag)), ['A原版', 'B原版'])
await child().locator('.el-form-item').filter({ hasText: '版本号' }).locator('input').fill('B新版')
await child().getByRole('button', { name: '保存', exact: true }).click()
await page.waitForFunction(() => window.editor.form.lines[1].childVersionTag === 'B新版' && !window.editor.childId)
assert.deepEqual(await page.evaluate(() => window.editor.form.lines.map(row => row.childVersionTag)), ['A原版', 'B新版'])
console.log('PASS 下级A加载中关闭再打开B,旧响应不串窗;保存仅回填原行且拒绝旧上下文/错误BOM ID')
failChild = true; await openChild('A'); await child().locator('.el-alert').waitFor()
assert.equal(await page.evaluate(() => window.editor.$refs.child.form.lines.length), 0)
failChild = false; await child().locator('.el-alert').getByRole('button', { name: '重试', exact: true }).click()
await child().getByText('AUDIT-BOM-311', { exact: true }).waitFor()
await child().locator('.el-dialog__headerbtn').click(); await page.waitForFunction(() => !window.editor.childId)
await page.evaluate(() => window.editor.open({ id: 302 }))
await openChild('B'); await child().getByText('AUDIT-BOM-322', { exact: true }).waitFor()
assert.equal(await child().getByRole('button', { name: '保存', exact: true }).count(), 0)
assert.equal(await page.evaluate(() => window.editor.$refs.child.readonly), true)
await child().locator('.el-dialog__headerbtn').click(); await page.waitForFunction(() => !window.editor.childId)
childGate = gate(); holdChild = true
await openChild('A'); await child().locator('.el-loading-mask').waitFor({ state: 'visible' })
await page.evaluate(() => window.auditBomApp.unmount()); childGate.release(); await pause(100)
assert.equal(await page.locator('.el-dialog:visible').count(), 0)
console.log('PASS 下级BOM失败可重试;项目引用公共BOM仍只读;卸载后旧请求不重开弹窗')
assert.deepEqual(blocked, []); assert.deepEqual(errors, []); assert.equal(writes.length, 2)
console.log('PASS 2次业务提交均在浏览器隔离模拟,真实业务写入0,页面异常0')
} finally { stockGate.release(); childGate.release(); await browser.close() }
})().catch(error => { console.error(error); process.exitCode = 1 })