cmvr-wms/scripts/projectdev/vue3-procurement-lifecycle-regression.cjs

298 lines
26 KiB
JavaScript

const assert = require('node:assert/strict')
const fs = require('node:fs')
const { chromium, frontend, backend, username, password } = require('./vue3-test-runtime.cjs')
const delay = ms => new Promise(resolve => setTimeout(resolve, ms))
// Real Vue dialogs and request adapters, with an isolated stateful supplier/delivery fixture.
// No procurement, warehouse, dictionary or inventory mutation reaches the database.
;(async () => {
const login = await (await fetch(backend + '/login', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ username, password }) })).json()
assert.equal(login.code, 200)
const browser = await chromium.launch()
try {
const context = await browser.newContext({ viewport: { width: 1366, height: 768 } })
await context.addCookies([{ name: 'Admin-Token', value: login.token, url: frontend }])
const page = await context.newPage(), errors = [], writes = [], warnings = []
page.on('pageerror', error => errors.push(error.message)); page.setDefaultTimeout(15000)
const requests = new Map([99101, 99102].map((id, index) => [id, { id, quantity: 10, priceLocked: true, purchaseStatus: 2, remainingQuantity: 10, supplierId: 991, projectId: index + 1, projectName: '测试项目 ' + (index + 1), purchaseBatchNo: 'CG2610001', materialName: '测试物品 ' + id, unit: '个' }]))
const arrivals = new Map(), receiptBalances = new Map(), returns = new Map(), acceptanceAttempts = new Map()
let nextArrival = 99500, nextReceipt = 99600, returnAttempts = 0, groupAttempts = 0, sheetVersion = 0, sheetState, singleArrivalMode = false, singleResponseLost = false
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 (path === '/warehouse/purchase/batch/list' && url.searchParams.get('keyword') === 'AUDIT-GROUP-FAIL') return route.fulfill({ json: { code: 500, msg: '模拟组批搜索失败' } })
if (path === '/warehouse/purchase/batch/list' && url.searchParams.get('keyword') === 'AUDIT-GROUP-RETRY') return route.fulfill({ json: { code: 200, rows: [{ id: 99080, batchNo: 'CG2610001', purchaseStatus: 1, requestCount: 2, unlockedCount: 2 }], total: 1 } })
if (path === '/warehouse/purchase/sheet/prepare' && method === 'POST') {
writes.push({ path, payload: req.postDataJSON(), batchId: url.searchParams.get('batchId') }); groupAttempts++
await delay(50)
if (groupAttempts === 1) return route.fulfill({ json: { code: 500, msg: '模拟组批失败' } })
return ok(sheetState)
}
if (path === '/warehouse/purchase/sheet' && method === 'POST') {
const payload = req.postDataJSON(); writes.push({ path, payload })
sheetState = { ...payload, batch: { ...payload.batch, id: 99080, batchNo: 'CG2610001' }, version: String(++sheetVersion), rows: payload.rows.map((row, i) => ({ ...row, ...requests.get(99101 + i), priceLocked: false })) }
return ok(sheetState)
}
if (path === '/warehouse/purchase/sheet/99080') return ok(sheetState)
if (path === '/warehouse/purchase/sheet/99080/confirm' && method === 'POST') {
writes.push({ path, payload: req.postDataJSON() }); await delay(120)
sheetState = { ...sheetState, version: String(++sheetVersion), rows: sheetState.rows.map(r => ({ ...r, priceLocked: true, lockedAmount: r.quantity * r.finalUnitPrice })) }
return ok(sheetState)
}
if (/^\/warehouse\/purchase\/9910[12]$/.test(path) && method === 'GET') return ok(requests.get(Number(path.split('/').pop())))
if (singleArrivalMode && path === '/warehouse/purchase/list') return route.fulfill({ json: { code: 200, rows: [requests.get(99101)], total: 1 } })
if (path === '/warehouse/purchase/99102/cancel-remaining' && method === 'POST') {
const payload = req.postDataJSON(); writes.push({ path, payload }); const row = requests.get(99102)
assert.equal(payload.expectedQuantity, row.quantity); assert.ok(payload.reason.trim())
row.quantity -= row.remainingQuantity; row.remainingQuantity = 0
return ok({})
}
if (path === '/warehouse/in/revoke/99701' && method === 'PUT') { writes.push({ path, payload: req.postDataJSON() }); return ok({}) }
if (/^\/warehouse\/purchase\/returns\/\d+\/availability$/.test(path) && method === 'GET') {
const id = Number(path.split('/').at(-2))
if (id === 99901 || id === 99902) {
await delay(id === 99901 ? 220 : 10)
return ok({ arrivalId: id, acceptedQuantity: id === 99901 ? 9 : 5, returnedQuantity: id === 99901 ? 3 : 1, receivedQuantity: 0, returnableQuantity: id === 99901 ? 6 : 4, supported: true })
}
const arrival = arrivals.get(id), receipt = [...receiptBalances.values()].find(row => row.arrivalId === id)
assert.ok(arrival, 'Missing isolated return fixture')
const acceptedQuantity = arrival.arrivalQuantity - Number(arrival.defectiveQuantity || 0)
const returnedQuantity = (returns.get(id) || []).reduce((sum, row) => sum + row.quantity, 0)
const receivedQuantity = receipt?.receivedQuantity || 0
return ok({ arrivalId: id, acceptedQuantity, returnedQuantity, receivedQuantity, returnableQuantity: acceptedQuantity - returnedQuantity - receivedQuantity, supported: true })
}
if (path === '/warehouse/purchase/returns' && method === 'GET') {
const id = Number(url.searchParams.get('arrivalId'))
if (id === 99901) { await delay(220); return ok([{ quantity: 3 }]) }
if (id === 99902) { await delay(10); return ok([{ quantity: 1 }]) }
return ok(returns.get(id) || [])
}
if (/^\/warehouse\/in\/9990[12]$/.test(path) && method === 'GET') {
const id = Number(path.split('/').pop()); await delay(id === 99901 ? 220 : 10)
return ok({ id, receiptRoot: true, inNum: id === 99901 ? 3 : 7, productName: '快速切换 ' + id })
}
if (path === '/warehouse/area/optionselect') return ok([{ id: 991, areaName: '测试库区' }])
if (/^\/warehouse\/purchase\/arrival\/9910[12]$/.test(path) && method === 'GET') return ok([...arrivals.values()].filter(a => a.purchaseRequestId === Number(path.split('/').pop())))
if (path === '/warehouse/purchase/arrival' && method === 'POST') {
const payload = req.postDataJSON(); writes.push({ path, payload }); const purchase = requests.get(payload.purchaseRequestId)
const existing = [...arrivals.values()].find(a => a.requestKey === payload.requestKey)
if (existing) return ok(existing)
assert.ok(payload.arrivalQuantity > 0 && payload.arrivalQuantity <= purchase.remainingQuantity)
const row = { ...payload, id: ++nextArrival, arrivalNo: 'DH' + nextArrival, acceptanceStatus: 0 }
arrivals.set(row.id, row); purchase.remainingQuantity -= payload.arrivalQuantity
if (singleArrivalMode && !singleResponseLost) { singleResponseLost = true; return route.fulfill({ json: { code: 500, msg: '模拟登记成功但响应失败' } }) }
return ok(row)
}
if (/^\/warehouse\/purchase\/arrival\/995\d+\/accept$/.test(path) && method === 'PUT') {
const id = Number(path.split('/').at(-2)), payload = req.postDataJSON(); writes.push({ path, payload })
acceptanceAttempts.set(id, (acceptanceAttempts.get(id) || 0) + 1)
// A delivery registration succeeds but its first automatic acceptance fails.
if (id === 99502 && acceptanceAttempts.get(id) === 1) return route.fulfill({ json: { code: 500, msg: '模拟验收网络失败' } })
const row = arrivals.get(id); Object.assign(row, payload)
const receipt = { id: ++nextReceipt, receiptRoot: true, inStatus: 0, inNum: row.arrivalQuantity - Number(row.defectiveQuantity || 0), arrivalId: id, receivedQuantity: 0, productName: requests.get(row.purchaseRequestId).materialName }
receiptBalances.set(receipt.id, receipt)
return ok({})
}
if (/^\/warehouse\/in\/996\d+$/.test(path) && method === 'GET') return ok(receiptBalances.get(Number(path.split('/').pop())))
if (/^\/warehouse\/in\/receive\/996\d+$/.test(path) && method === 'POST') {
const payload = req.postDataJSON(), row = receiptBalances.get(Number(path.split('/').pop())); writes.push({ path, payload })
assert.ok(payload.quantity > 0 && payload.quantity <= row.inNum)
row.inNum -= payload.quantity; row.receivedQuantity += payload.quantity
return ok({})
}
if (path === '/warehouse/purchase/returns' && method === 'POST') {
const payload = req.postDataJSON(); writes.push({ path, payload }); returnAttempts++
if (returnAttempts === 1) return route.fulfill({ json: { code: 500, msg: '模拟退货失败,请重试' } })
const records = returns.get(payload.arrivalId) || []; records.push({ quantity: payload.quantity, cancel_purchase: payload.cancelPurchase, business_key: payload.key }); returns.set(payload.arrivalId, records)
return ok({})
}
if (!['GET', 'HEAD'].includes(method)) { writes.push({ path, blocked: true }); return route.abort('blockedbyclient') }
return route.continue()
})
await page.goto(frontend + '/procurement/details')
await page.getByRole('button', { name: '新增采购批次', exact: true }).waitFor()
// Supplier is deliberately absent while preparing the initial list.
await page.getByRole('button', { name: '新增采购批次', exact: true }).click();await page.locator('.sheet-grid').waitFor()
await page.locator('.purchase-sheet').evaluate(el => {
const v = el.__vueParentComponent.proxy, item = v.items.find(i => i.unit && i.category)
if (!item || !v.projects.length || !v.categories.length) throw Error('Missing reference fixtures')
v.sheet.rows = [0, 1].map(i => ({ ...v.emptyRow(), productId: item.id, materialName: item.productName, materialBrand: item.brand || '', materialParams: item.spec || '', unit: item.unit, category: item.category, projectId: v.projects[i % v.projects.length].id, expenseCategoryId: v.categories[0].id, quantity: 10, finalUnitPrice: 12 }))
})
await page.getByRole('button', { name: '保存清单', exact: true }).click()
await page.waitForFunction(() => { const v = document.querySelector('.purchase-sheet').__vueParentComponent.proxy; return !v.saving && !!v.sheet?.batch.id })
assert.equal(sheetState.batch.supplierId, null)
await page.getByRole('button', { name: '确认采购', exact: true }).click()
await page.getByText('清单可以先保存;请编辑并补选供应商后再确认采购', { exact: true }).waitFor()
assert.equal(writes.filter(w => w.path.endsWith('/confirm')).length, 0)
await page.getByRole('button', { name: '编辑', exact: true }).click()
await page.locator('.purchase-sheet').evaluate(el => { el.__vueParentComponent.proxy.sheet.batch.supplierId = 991 })
await page.getByRole('button', { name: '保存清单', exact: true }).click()
await page.waitForFunction(() => { const v = document.querySelector('.purchase-sheet').__vueParentComponent.proxy; return !v.saving && !v.isEditing })
await page.getByRole('button', { name: '确认采购', exact: true }).click()
await page.locator('.el-message-box:visible').waitFor()
assert.equal(await page.locator('.purchase-sheet').evaluate(el => el.__vueParentComponent.proxy.saving), true)
assert.equal(await page.getByRole('button', { name: '批次列表', exact: true }).isDisabled(), true)
await page.locator('.el-message-box:visible').getByRole('button', { name: '取消', exact: true }).click()
await page.waitForFunction(() => !document.querySelector('.purchase-sheet').__vueParentComponent.proxy.saving)
assert.equal(writes.filter(w => w.path.endsWith('/confirm')).length, 0)
await page.getByRole('button', { name: '确认采购', exact: true }).click()
await page.locator('.el-message-box:visible').getByRole('button', { name: '确定', exact: true }).click()
await page.waitForFunction(() => { const v = document.querySelector('.purchase-sheet').__vueParentComponent.proxy; return !v.saving && v.sheet.rows.every(r => r.priceLocked) })
assert.equal(writes.filter(w => w.path.endsWith('/confirm')).length, 1)
assert.equal(sheetState.rows.reduce((sum, r) => sum + r.lockedAmount, 0), 240)
console.log('PASS supplier-optional preparation, explicit edit/save, supplier-required confirmation, cancel confirmation and price locking')
await page.evaluate(async () => {
const { createApp, h, ElementPlus } = await import('/tests/browser-runtime.js')
const imports = {
returns: '/src/components/ReceiptDialog/PurchaseReturn.vue', receipt: '/src/components/ReceiptDialog/index.vue',
batch: '/src/components/ReceiptDialog/Batch.vue', exception: '/src/components/ReceiptDialog/AcceptanceException.vue',
cancel: '/src/components/ReceiptDialog/CancelPurchase.vue', withdraw: '/src/components/ReceiptDialog/Withdraw.vue',
group: '/src/components/PurchaseSheet/GroupDialog.vue'
}
window.auditComponents = {}; window.auditApps = []; window.auditWarnings = []
for (const [key, path] of Object.entries(imports)) {
const { default: Component } = await import(path), host = document.createElement('div'); document.body.append(host)
const app = createApp({ render: () => h(Component) }).use(ElementPlus)
Object.assign(app.config.globalProperties, { parseTime: () => '2026-10-14', $modal: { msgSuccess() {}, msgWarning(text) { window.auditWarnings.push(text) }, msgError(text) { window.auditWarnings.push(text) } } })
app.mount(host); window.auditApps.push({ app, host }); window.auditComponents[key] = app._instance.subTree.component.proxy
}
})
const race = await page.evaluate(async () => {
const v = window.auditComponents.returns
const first = v.open({ id: 99901, arrivalQuantity: 10, defectiveQuantity: 1 })
const second = v.open({ id: 99902, arrivalQuantity: 5, defectiveQuantity: 0 })
await Promise.all([first, second]); const state = { id: v.form.arrivalId, quantity: v.form.quantity, history: v.history.map(r => r.quantity) }
v.visible = false; return state
})
assert.deepEqual(race, { id: 99902, quantity: 4, history: [1] })
const receiptRace = await page.evaluate(async () => {
const v = window.auditComponents.receipt
await Promise.all([v.open({ id: 99901 }), v.open({ id: 99902 })])
const state = { id: v.record.id, quantity: v.form.quantity }; v.visible = false; return state
})
assert.deepEqual(receiptRace, { id: 99902, quantity: 7 })
console.log('PASS rapid switching keeps return history/quantity and receipt target on the latest record')
await page.evaluate(async () => {
const v = window.auditComponents.group; v.open([{ id: 99101 }, { id: 99102 }]); v.mode = 'existing'
await v.search('AUDIT-GROUP-FAIL')
if (v.batches.length || v.loading || !v.searchFailed) throw Error('Failed group search left stale options or a loading mask')
await v.search('AUDIT-GROUP-RETRY')
if (v.batches[0]?.id !== 99080 || v.searchFailed) throw Error('Group search did not recover')
await v.save()
})
assert.equal(groupAttempts, 0)
await page.evaluate(async () => { const v = window.auditComponents.group; v.batchId = 99080; await v.save(); if (!v.visible || v.saving) throw Error('Failed grouping discarded form'); await v.save() })
assert.equal(groupAttempts, 2)
assert.deepEqual(writes.filter(w => w.path === '/warehouse/purchase/sheet/prepare').map(w => w.payload), [[99101, 99102], [99101, 99102]])
console.log('PASS grouping search failure/retry, required target and failed grouping immediate retry')
// Two projects in one supplier batch, partial delivery, automatic acceptance, partial failure/retry.
await page.evaluate(async input => { const v = window.auditComponents.batch; await v.open(input, 'arrival'); v.rows[0].quantity = 4; v.rows[1].quantity = 3 }, [...requests.values()])
await page.locator('.receipt-batch-dialog:visible').getByRole('button', { name: '确认本次到货', exact: true }).click()
await page.waitForFunction(() => !window.auditComponents.batch.saving)
fs.mkdirSync('.codex-tmp/vue3-procurement-lifecycle', { recursive: true })
await page.waitForTimeout(3300) // Let notification and dialog transitions settle for visual evidence.
await page.screenshot({ path: '.codex-tmp/vue3-procurement-lifecycle/partial-arrival-failure.png' })
assert.deepEqual(await page.evaluate(() => window.auditComponents.batch.rows.map(r => ({ done: r.done, failed: r.failed, quantity: r.quantity }))), [{ done: true, failed: false, quantity: 4 }, { done: false, failed: true, quantity: 3 }])
assert.deepEqual(await page.evaluate(() => { const v=window.auditComponents.batch;return v.rows.map(r=>v.remainingQuantity(r)) }), [6,7])
await page.locator('.receipt-batch-dialog:visible').getByRole('button', { name: '重试失败', exact: true }).click()
await page.waitForFunction(() => window.auditComponents.batch.rows.every(r => r.done))
assert.equal(writes.filter(w => w.path === '/warehouse/purchase/arrival').length, 2)
assert.equal(arrivals.size, 2)
await page.locator('.receipt-batch-dialog:visible').getByRole('button', { name: '关闭', exact: true }).click()
console.log('PASS mixed-project partial delivery; retry resumes acceptance without registering delivery twice')
// Next delivery is registered only, then separately accepted with one defective unit.
await page.evaluate(async input => { const v = window.auditComponents.batch; await v.open(input, 'arrival'); v.acceptAll = false; v.rows[0].quantity = 2 }, [requests.get(99101)])
await page.locator('.receipt-batch-dialog:visible').getByRole('button', { name: '确认本次到货', exact: true }).click()
await page.waitForFunction(() => window.auditComponents.batch.rows.every(r => r.done))
assert.equal(arrivals.get(99503).acceptanceStatus, 0)
await page.locator('.receipt-batch-dialog:visible').getByRole('button', { name: '关闭', exact: true }).click()
await page.evaluate(async input => { const v = window.auditComponents.batch; await v.open(input, 'acceptance'); v.rows[0].defectiveQuantity = 1 }, [requests.get(99101)])
await page.locator('.receipt-batch-dialog:visible').getByRole('button', { name: '确认本次验收', exact: true }).click()
await page.waitForFunction(() => window.auditComponents.batch.rows.every(r => r.done))
assert.equal(arrivals.get(99503).defectiveQuantity, 1)
assert.deepEqual(await page.evaluate(() => { const v=window.auditComponents.batch;return v.rows.map(r=>v.remainingQuantity(r)) }), [0])
assert.equal([...receiptBalances.values()].find(r => r.arrivalId === 99503).inNum, 1)
await page.locator('.receipt-batch-dialog:visible').getByRole('button', { name: '关闭', exact: true }).click()
console.log('PASS separate acceptance deducts defects before creating pending stock receipt')
// Receive only two units into a selected warehouse area, then receive the remaining two.
const root = [...receiptBalances.values()].find(r => r.arrivalId === 99501)
for (let part = 0; part < 2; part++) {
await page.evaluate(async input => { const v = window.auditComponents.batch; await v.open([input], 'receipt'); v.rows[0].quantity = 2; v.commonArea = 991; v.setArea(991) }, root)
await page.locator('.receipt-batch-dialog:visible').getByRole('button', { name: '确认本次入库', exact: true }).click()
await page.waitForFunction(() => window.auditComponents.batch.rows.every(r => r.done))
await page.locator('.receipt-batch-dialog:visible').getByRole('button', { name: '关闭', exact: true }).click()
}
assert.equal(root.inNum, 0); assert.equal(root.receivedQuantity, 4)
console.log('PASS partial stock receipt + remainder receipt have distinct idempotency keys and correct quantities')
const acceptanceWrites = writes.filter(w => w.path.endsWith('/accept')).length
await page.evaluate(async () => { const v = window.auditComponents.exception; v.open({ id: 99503, arrivalQuantity: 2 }); v.quantity = null; await v.save(); v.quantity = 3; await v.save(); v.visible = false })
assert.equal(writes.filter(w => w.path.endsWith('/accept')).length, acceptanceWrites)
console.log('PASS missing and excessive defective quantities are blocked before acceptance requests')
// Return validation must block empty/excessive input, keep the form after failure and permit an immediate retry.
await page.evaluate(async () => { const v = window.auditComponents.returns; await v.open({ id: 99502, arrivalQuantity: 3, defectiveQuantity: 0 }); v.form.quantity = 4; await v.save(); v.form.quantity = null; await v.save() })
assert.equal(writes.filter(w => w.path === '/warehouse/purchase/returns').length, 0)
await page.evaluate(async () => { const v = window.auditComponents.returns; v.form.quantity = 1; await v.save(); if (!v.visible) throw Error('Failed return closed the editable dialog'); await v.save() })
assert.equal(writes.filter(w => w.path === '/warehouse/purchase/returns').length, 2)
assert.equal(returns.get(99502)[0].quantity, 1)
assert.equal(await page.evaluate(() => window.auditComponents.returns.visible), false)
const saved = writes.filter(w => w.path === '/warehouse/purchase/returns').map(w => w.payload); assert.deepEqual(saved[0], saved[1])
await page.evaluate(async () => { const v = window.auditComponents.returns; await v.open({ id: 99502, arrivalQuantity: 3, defectiveQuantity: 0 }); if (v.form.quantity !== 2) throw Error('Returned quantity was not deducted'); v.form.cancelPurchase = true })
await page.setViewportSize({ width: 1024, height: 600 })
await page.getByRole('dialog', { name: '采购退货', exact: true }).waitFor()
await page.waitForTimeout(3300)
await page.screenshot({ path: '.codex-tmp/vue3-procurement-lifecycle/return-limit.png' })
await page.evaluate(() => window.auditComponents.returns.save())
await page.setViewportSize({ width: 1366, height: 768 })
assert.equal(returns.get(99502)[1].cancel_purchase, true)
console.log('PASS return limits, replenish/cancel choices, failed request immediate retry and stable idempotency key')
await page.evaluate(() => { const v=window.auditComponents.cancel; window.auditCancel = Promise.all([v.open({ id: 99102 }),v.open({ id: 99102 })]) })
await page.locator('.el-message-box:visible').locator('input').fill('测试取消尚未送来的剩余采购')
await page.locator('.el-message-box:visible').getByRole('button', { name: '确定', exact: true }).click()
await page.evaluate(() => window.auditCancel)
assert.equal(requests.get(99102).quantity, 3); assert.equal(requests.get(99102).remainingQuantity, 0)
assert.equal(writes.filter(w=>w.path.endsWith('/cancel-remaining')).length,1)
await page.evaluate(() => window.auditComponents.withdraw.open({ id: 99701, parentInId: 99601, inNum: 2, productName: '测试已入库物品' }))
await page.evaluate(async () => { const v = window.auditComponents.withdraw; v.reason = '测试撤销'; v.quantity = null; await v.save(); v.quantity = 3; await v.save(); v.quantity = 2 })
assert.equal(writes.some(w => w.path === '/warehouse/in/revoke/99701'), false)
const withdraw = page.getByRole('dialog', { name: '撤销入库至待入库' })
await withdraw.locator('textarea').fill('测试实物退回供应商,撤销部分入库')
await withdraw.getByRole('spinbutton').fill('1')
await withdraw.getByRole('button', { name: '确认撤销', exact: true }).click()
await withdraw.waitFor({ state: 'hidden' })
assert.equal(writes.find(w => w.path === '/warehouse/in/revoke/99701').payload.quantity, 1)
console.log('PASS cancellation retains delivered units; partial stock withdrawal requires a reason')
warnings.push(...await page.evaluate(() => window.auditWarnings))
assert.ok(warnings.length >= 2)
await page.evaluate(() => window.auditApps.forEach(({ app, host }) => { app.unmount(); host.remove() }))
// The single-item entry on the real arrival page must also survive a lost registration response.
singleArrivalMode = true
await page.evaluate(async () => { await document.querySelector('#app').__vue_app__.config.globalProperties.$router.push('/procurement/arrival') })
await page.locator('.arrival-workbench-page .el-table__body').getByRole('button', { name: '登记到货', exact: true }).click()
const singleDialog = page.getByRole('dialog', { name: '到货与验收', exact: true })
await singleDialog.waitFor()
await page.waitForFunction(() => !document.querySelector('.arrival-workbench-page').__vueParentComponent.proxy.arrivalBusy)
await singleDialog.getByRole('spinbutton').fill('3')
const countBeforeSingle = arrivals.size, writesBeforeSingle = writes.filter(w => w.path === '/warehouse/purchase/arrival').length
await singleDialog.getByRole('button', { name: '登记到货', exact: true }).click()
await page.getByText('模拟登记成功但响应失败', { exact: true }).waitFor()
await page.waitForFunction(() => !document.querySelector('.arrival-workbench-page').__vueParentComponent.proxy.arrivalSubmitting)
assert.equal(await singleDialog.getByRole('spinbutton').inputValue(), '3.0000')
await singleDialog.getByRole('button', { name: '登记到货', exact: true }).click()
await page.waitForFunction(() => { const v = document.querySelector('.arrival-workbench-page').__vueParentComponent.proxy; return !v.arrivalBusy && v.arrivalForm.arrivalQuantity === 0 })
assert.equal(arrivals.size, countBeforeSingle + 1)
const singleWrites = writes.filter(w => w.path === '/warehouse/purchase/arrival').slice(writesBeforeSingle)
assert.equal(singleWrites.length, 2); assert.ok(singleWrites[0].payload.requestKey)
assert.equal(singleWrites[0].payload.requestKey, singleWrites[1].payload.requestKey)
assert.notEqual(await page.locator('.arrival-workbench-page').evaluate(el => el.__vueParentComponent.proxy.arrivalForm.requestKey), singleWrites[0].payload.requestKey)
console.log('PASS real arrival-page entry keeps the registration key after a lost response; retry creates no duplicate and successful next entry receives a new key')
assert.deepEqual(errors, []); assert.equal(writes.some(w => w.blocked), false)
console.log('PROCUREMENT LIFECYCLE PASS', JSON.stringify({ businessRequestsSimulated: writes.length, actualBusinessWrites: 0, errors }))
} finally { await browser.close() }
})().catch(error => { console.error(error); process.exitCode = 1 })