188 lines
16 KiB
JavaScript
188 lines
16 KiB
JavaScript
|
|
const assert = require('node:assert/strict')
|
||
|
|
const fs = require('node:fs')
|
||
|
|
const path = require('node:path')
|
||
|
|
const { chromium, frontend, backend, username, password } = require('./vue3-test-runtime.cjs')
|
||
|
|
|
||
|
|
// Real Vue editor/request adapter with a transactional-receipt mock. All business
|
||
|
|
// writes are intercepted; database idempotency is covered by PurchaseSheetDatabaseTest.
|
||
|
|
;(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()
|
||
|
|
const output = path.resolve('.codex-tmp/vue3-sheet-submission'); fs.mkdirSync(output, { recursive: true })
|
||
|
|
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(), receipts = new Map(), sheets = new Map(), writes = [], blocked = [], errors = []
|
||
|
|
let nextBatch = 99700, nextRow = 997000, mutations = 0, loseNext = false, failBeforeCommit = false
|
||
|
|
page.on('pageerror', error => errors.push(error.message)); page.setDefaultTimeout(15000)
|
||
|
|
const copy = value => JSON.parse(JSON.stringify(value))
|
||
|
|
const canonical = value => Array.isArray(value) ? value.map(canonical) : value && typeof value === 'object' ? Object.fromEntries(Object.keys(value).sort().filter(key => !key.startsWith('_')).map(key => [key, canonical(value[key])])) : value
|
||
|
|
await context.route('**/dev-api/**', async route => {
|
||
|
|
const req = route.request(), url = new URL(req.url()), endpoint = url.pathname.replace('/dev-api', ''), ok = data => route.fulfill({ json: { code: 200, data } })
|
||
|
|
if (endpoint.startsWith('/warehouse/purchase/sheet/submission/')) return ok(receipts.get(decodeURIComponent(endpoint.split('/').pop()))?.saved || null)
|
||
|
|
if (/^\/warehouse\/purchase\/sheet\/997\d+$/.test(endpoint)) return ok(sheets.get(Number(endpoint.split('/').pop())))
|
||
|
|
if (endpoint === '/warehouse/purchase/sheet' && req.method() === 'POST') {
|
||
|
|
const input = req.postDataJSON(), fingerprint = JSON.stringify(canonical(input))
|
||
|
|
writes.push(copy(input)); assert.match(input.submissionKey, /^[A-Za-z0-9_-]{16,100}$/)
|
||
|
|
if (failBeforeCommit) { failBeforeCommit = false; return route.abort('connectionreset') }
|
||
|
|
const prior = receipts.get(input.submissionKey)
|
||
|
|
if (prior) return prior.fingerprint === fingerprint ? ok(prior.saved) : route.fulfill({ json: { code: 500, msg: '上次保存已成功,但本次内容不同,当前修改未保存。请先核对上次保存,再继续编辑' } })
|
||
|
|
const id = input.unbatched ? null : input.batch.id || ++nextBatch
|
||
|
|
const saved = { ...input, submissionKey: null, batch: { ...input.batch, id, batchNo: id ? 'CG2610TEST' + id : null }, rows: input.rows.map(row => ({ ...row, id: row.id || ++nextRow })), deletedIds: [], version: 'saved-' + (++mutations) }
|
||
|
|
receipts.set(input.submissionKey, { fingerprint, saved: copy(saved) }); if (id) sheets.set(id, copy(saved))
|
||
|
|
if (loseNext) { loseNext = false; return route.abort('connectionreset') }
|
||
|
|
return ok(saved)
|
||
|
|
}
|
||
|
|
if (!['GET', 'HEAD'].includes(req.method())) { blocked.push(endpoint); return route.abort('blockedbyclient') }
|
||
|
|
return route.continue()
|
||
|
|
})
|
||
|
|
await page.goto(frontend + '/procurement/details')
|
||
|
|
await page.getByRole('button', { name: '新增采购批次', exact: true }).waitFor()
|
||
|
|
await page.waitForFunction(() => !document.querySelector('.purchase-sheet').__vueParentComponent.proxy.loading)
|
||
|
|
const state = expression => page.locator('.purchase-sheet').evaluate((el, source) => Function('v', 'return (' + source + ')')(el.__vueParentComponent.proxy), expression)
|
||
|
|
const waitIdle = () => page.waitForFunction(() => !document.querySelector('.purchase-sheet').__vueParentComponent.proxy.saving)
|
||
|
|
async function create(unbatched = false) {
|
||
|
|
await page.locator('.purchase-sheet').evaluate(async (el, mode) => {
|
||
|
|
const v = el.__vueParentComponent.proxy; await v.create(mode)
|
||
|
|
const item = v.items.find(row => row.unit && row.category)
|
||
|
|
if (!item || !v.projects.length || !v.categories.length) throw Error('Missing catalog references')
|
||
|
|
v.sheet.rows = [{ ...v.emptyRow(), productId: item.id, materialName: item.productName, materialBrand: item.brand || '', materialParams: item.spec || '', unit: item.unit, category: item.category, projectId: v.projects[0].id, expenseCategoryId: v.categories[0].id, quantity: 1, finalUnitPrice: 10 }]
|
||
|
|
}, unbatched)
|
||
|
|
}
|
||
|
|
async function save() {
|
||
|
|
await page.getByRole('button', { name: /保存清单|保存未组批明细/ }).click(); await waitIdle()
|
||
|
|
}
|
||
|
|
|
||
|
|
// A failed response never turns the next click into a second batch.
|
||
|
|
await create(); loseNext = true; await save()
|
||
|
|
const originalKey = await state('v.sheet.submissionKey'); assert.ok(originalKey)
|
||
|
|
await page.getByRole('button', { name: '核对上次保存', exact: true }).waitFor()
|
||
|
|
await page.screenshot({ path: path.join(output, 'uncertain-save.png'), fullPage: false })
|
||
|
|
await save(); assert.equal(mutations, 1); assert.equal(writes[1].submissionKey, originalKey)
|
||
|
|
assert.equal(await state('v.sheet.submissionKey'), null)
|
||
|
|
|
||
|
|
// Adding a line to an existing sheet is also one logical save on retry.
|
||
|
|
await page.getByRole('button', { name: '编辑', exact: true }).click()
|
||
|
|
await page.locator('.purchase-sheet').evaluate(el => { const v = el.__vueParentComponent.proxy; v.sheet.rows.push({ ...v.sheet.rows[0], id: null, _key: v.emptyRow()._key }) })
|
||
|
|
loseNext = true; await save(); const appendKey = await state('v.sheet.submissionKey')
|
||
|
|
await save(); assert.equal(mutations, 2); assert.equal(await state('v.sheet.rows.length'), 2)
|
||
|
|
assert.equal(writes.at(-1).submissionKey, appendKey)
|
||
|
|
|
||
|
|
// Changing content after an uncertain response keeps the key and cannot create
|
||
|
|
// another batch. Recovery requires an explicit discard-modifications confirmation.
|
||
|
|
await state('v.back()'); await create(); loseNext = true; await save()
|
||
|
|
const changedKey = await state('v.sheet.submissionKey')
|
||
|
|
await page.locator('.purchase-sheet').evaluate(el => { el.__vueParentComponent.proxy.sheet.rows[0].quantity = 2 })
|
||
|
|
await save(); assert.equal(mutations, 3); assert.equal(writes.at(-1).submissionKey, changedKey)
|
||
|
|
assert.equal(await state('v.sheet.rows[0].quantity'), 2)
|
||
|
|
await page.getByRole('button', { name: '核对上次保存', exact: true }).click()
|
||
|
|
await page.getByRole('button', { name: '保留当前修改', exact: true }).click(); await waitIdle()
|
||
|
|
assert.equal(await state('v.sheet.rows[0].quantity'), 2); assert.equal(await state('v.sheet.submissionKey'), changedKey)
|
||
|
|
await page.getByRole('button', { name: '核对上次保存', exact: true }).click()
|
||
|
|
await page.getByRole('button', { name: '恢复已保存内容', exact: true }).click(); await waitIdle()
|
||
|
|
assert.equal(await state('v.sheet.rows[0].quantity'), 1); assert.equal(await state('v.sheet.submissionKey'), null)
|
||
|
|
|
||
|
|
// Pending new-sheet keys survive page reload through the existing draft storage.
|
||
|
|
await state('v.back()'); await create(true); loseNext = true; await save()
|
||
|
|
const draftKey = await state('v.draftPrefix()+v.draftId()'), unbatchedKey = await state('v.sheet.submissionKey')
|
||
|
|
await page.reload(); await page.getByRole('button', { name: '新增采购批次', exact: true }).waitFor()
|
||
|
|
await page.waitForFunction(() => !document.querySelector('.purchase-sheet').__vueParentComponent.proxy.loading)
|
||
|
|
await page.locator('.purchase-sheet').evaluate(async (el, key) => { await el.__vueParentComponent.proxy.restoreDraft(key) }, draftKey)
|
||
|
|
assert.equal(await state('v.sheet.submissionKey'), unbatchedKey)
|
||
|
|
await save(); assert.equal(mutations, 4); assert.equal(writes.at(-1).submissionKey, unbatchedKey)
|
||
|
|
assert.equal(await state('v.sheet'), null)
|
||
|
|
|
||
|
|
// The production-shortage entry uses the same persistent request contract.
|
||
|
|
loseNext = true
|
||
|
|
await page.evaluate(async () => {
|
||
|
|
const { default: component } = await import('/src/components/Production/ShortagePurchase.vue')
|
||
|
|
const vm = { ...component.data(), selected: [{ projectId: 1, taskId: 2, itemId: 3, itemName: '测试物品', brand: '', spec: '', unit: '个', category: '测试类别', quantity: 1, expenseCategoryId: 1 }], $modal: { msgWarning() {} }, parseTime: () => '2026-10-14', $emit() {}, $router: { push() {} } }
|
||
|
|
Object.assign(vm, component.methods); vm.rows=vm.selected; window.__shortageSubmissionAudit = vm
|
||
|
|
await vm.save(); window.__shortageFirstKey = vm.submissionKey
|
||
|
|
})
|
||
|
|
const shortageKey=await page.evaluate(() => window.__shortageFirstKey)
|
||
|
|
await page.reload()
|
||
|
|
await page.evaluate(async () => {
|
||
|
|
const { default: component } = await import('/src/components/Production/ShortagePurchase.vue')
|
||
|
|
const vm = { ...component.data(), $refs:{}, $nextTick:callback=>callback(), $modal:{msgWarning(){}}, parseTime:()=> '2026-10-14', $emit(){}, $router:{push(){}} }
|
||
|
|
Object.assign(vm,component.methods); await vm.open([{id:2}]);window.__shortageSubmissionAudit=vm
|
||
|
|
})
|
||
|
|
assert.equal(await page.evaluate(() => window.__shortageSubmissionAudit.submissionKey),shortageKey)
|
||
|
|
await page.evaluate(async()=>{await window.__shortageSubmissionAudit.save()})
|
||
|
|
assert.equal(mutations, 5); assert.equal(writes.at(-1).submissionKey, shortageKey)
|
||
|
|
assert.equal(await page.evaluate(() => window.__shortageSubmissionAudit.submissionKey), null)
|
||
|
|
// Refuse to send a mutation when the browser cannot retain its retry identity.
|
||
|
|
await page.locator('.purchase-sheet').waitFor()
|
||
|
|
await page.waitForFunction(() => !document.querySelector('.purchase-sheet').__vueParentComponent.proxy.loading)
|
||
|
|
await create()
|
||
|
|
const beforeStorageFailure=writes.length
|
||
|
|
await page.evaluate(()=>{window.__originalStorageSetItem=Storage.prototype.setItem;Storage.prototype.setItem=function(key,value){if(key.startsWith('purchase-sheet-draft:'))throw new Error('Simulated quota exceeded');return window.__originalStorageSetItem.call(this,key,value)}})
|
||
|
|
await save();assert.equal(writes.length,beforeStorageFailure)
|
||
|
|
const storageKey=await state('v.sheet.submissionKey')
|
||
|
|
await page.evaluate(()=>{Storage.prototype.setItem=window.__originalStorageSetItem})
|
||
|
|
await save();assert.equal(mutations,6);assert.equal(writes.at(-1).submissionKey,storageKey)
|
||
|
|
|
||
|
|
// Two cached dialogs may both be open before either reserves the session slot.
|
||
|
|
// A failed response from A must not strand a never-sent key on B or replace B's edits.
|
||
|
|
await page.evaluate(async () => {
|
||
|
|
const { default: component } = await import('/src/components/Production/ShortagePurchase.vue')
|
||
|
|
window.__newShortageAudit = (owner, name, quantity) => {
|
||
|
|
const vm = { ...component.data(), visible:true, batchName:name, selected:[{projectId:1,taskId:2,itemId:3,itemName:'测试物品',brand:'',spec:'',unit:'个',category:'测试类别',quantity,expenseCategoryId:1}], $store:{getters:{userId:owner}}, $refs:{}, $nextTick:callback=>callback(), parseTime:()=> '2026-10-14', $emit(){}, navigations:[], confirmations:0, rejectConfirmation:false }
|
||
|
|
vm.$router={push:route=>vm.navigations.push(route)}
|
||
|
|
vm.$modal={msgWarning(){},msgSuccess(){},confirm:async()=>{vm.confirmations++;if(vm.rejectConfirmation)throw Error('cancel')}}
|
||
|
|
Object.assign(vm,component.methods);vm.rows=vm.selected
|
||
|
|
return vm
|
||
|
|
}
|
||
|
|
window.__shortageA=window.__newShortageAudit(99001,'清单 A',1)
|
||
|
|
window.__shortageB=window.__newShortageAudit(99001,'本地清单 B',2)
|
||
|
|
})
|
||
|
|
loseNext=true
|
||
|
|
await page.evaluate(async()=>{await window.__shortageA.save()})
|
||
|
|
const collisionAKey=await page.evaluate(()=>window.__shortageA.submissionKey)
|
||
|
|
const beforeCollision=writes.length
|
||
|
|
await page.evaluate(async()=>{await window.__shortageB.save();await window.__shortageB.open([{id:2}])})
|
||
|
|
assert.equal(writes.length,beforeCollision)
|
||
|
|
assert.deepEqual(await page.evaluate(()=>{const v=window.__shortageB;return {key:v.submissionKey,date:v.submissionDate,blocked:v.blockedSubmissionKey,name:v.batchName,quantity:v.rows[0].quantity,pending:v.pendingSubmission().submissionKey}}),{key:null,date:null,blocked:collisionAKey,name:'本地清单 B',quantity:2,pending:collisionAKey})
|
||
|
|
await page.evaluate(async()=>{await window.__shortageB.recoverSubmission()})
|
||
|
|
assert.deepEqual(await page.evaluate(()=>{const v=window.__shortageB;return {key:v.submissionKey,blocked:v.blockedSubmissionKey,name:v.batchName,quantity:v.rows[0].quantity,pending:v.pendingSubmission(),visible:v.visible,navigations:v.navigations}}),{key:null,blocked:null,name:'本地清单 B',quantity:2,pending:null,visible:true,navigations:[]})
|
||
|
|
loseNext=true
|
||
|
|
await page.evaluate(async()=>{await window.__shortageB.save()})
|
||
|
|
const collisionBKey=await page.evaluate(()=>window.__shortageB.submissionKey)
|
||
|
|
assert.notEqual(collisionAKey,collisionBKey)
|
||
|
|
const beforeSentKeyConflict=writes.length
|
||
|
|
await page.evaluate(async()=>{await window.__shortageA.save()})
|
||
|
|
assert.equal(writes.length,beforeSentKeyConflict)
|
||
|
|
assert.equal(await page.evaluate(()=>window.__shortageA.submissionKey),collisionAKey)
|
||
|
|
await page.evaluate(async()=>{await window.__shortageA.recoverSubmission()})
|
||
|
|
assert.equal(await page.evaluate(()=>window.__shortageB.pendingSubmission().submissionKey),collisionBKey)
|
||
|
|
await page.evaluate(async()=>{await window.__shortageB.save()})
|
||
|
|
assert.equal(mutations,8)
|
||
|
|
assert.equal(writes.at(-1).submissionKey,collisionBKey)
|
||
|
|
|
||
|
|
// If A has no receipt yet, retry its exact persisted payload only after explicit
|
||
|
|
// confirmation; cancellation leaves both A's pending request and B's edits intact.
|
||
|
|
await page.evaluate(()=>{
|
||
|
|
window.__shortageA=window.__newShortageAudit(99002,'清单 A 未完成',1)
|
||
|
|
window.__shortageB=window.__newShortageAudit(99002,'本地清单 B 保留',3)
|
||
|
|
})
|
||
|
|
failBeforeCommit=true
|
||
|
|
await page.evaluate(async()=>{await window.__shortageA.save();window.__shortageA.rows[0].quantity=9;window.__shortageA.persistSubmission();await window.__shortageB.save()})
|
||
|
|
const unresolvedKey=await page.evaluate(()=>window.__shortageA.submissionKey)
|
||
|
|
const beforeRecovery=writes.length
|
||
|
|
await page.evaluate(async()=>{window.__shortageB.rejectConfirmation=true;await window.__shortageB.recoverSubmission()})
|
||
|
|
assert.equal(writes.length,beforeRecovery)
|
||
|
|
assert.deepEqual(await page.evaluate(()=>{const v=window.__shortageB;return {blocked:v.blockedSubmissionKey,pending:v.pendingSubmission().submissionKey,quantity:v.rows[0].quantity}}),{blocked:unresolvedKey,pending:unresolvedKey,quantity:3})
|
||
|
|
await page.evaluate(async()=>{window.__shortageB.rejectConfirmation=false;await window.__shortageB.recoverSubmission()})
|
||
|
|
assert.equal(writes.at(-1).submissionKey,unresolvedKey)
|
||
|
|
assert.equal(writes.at(-1).rows[0].quantity,1)
|
||
|
|
assert.deepEqual(await page.evaluate(()=>{const v=window.__shortageB;return {blocked:v.blockedSubmissionKey,key:v.submissionKey,name:v.batchName,quantity:v.rows[0].quantity,pending:v.pendingSubmission(),navigations:v.navigations}}),{blocked:null,key:null,name:'本地清单 B 保留',quantity:3,pending:null,navigations:[]})
|
||
|
|
await page.evaluate(async()=>{await window.__shortageB.save()})
|
||
|
|
assert.notEqual(writes.at(-1).submissionKey,unresolvedKey)
|
||
|
|
assert.equal(mutations,10)
|
||
|
|
assert.deepEqual(blocked, []); assert.deepEqual(errors, [])
|
||
|
|
fs.writeFileSync(path.join(output, 'result.json'), JSON.stringify({ status: 'PASS', scenarios: 8, writes: writes.length, isolatedMutations: mutations, realBusinessWrites: 0, pageErrors: errors, checked: ['new batch retry', 'existing batch append retry', 'changed payload rejection and explicit recovery', 'unbatched reload/draft retry', 'production shortage reload/session retry', 'browser storage failure stops submission', 'cached shortage conflict preserves local edits and sent keys', 'explicit retry of another pending shortage retains exact payload and local edits'] }, null, 2))
|
||
|
|
console.log('PASS purchase sheet submission keys, safe retries, content conflict, recovery and draft persistence; 0 real business writes')
|
||
|
|
} finally { await browser.close() }
|
||
|
|
})().catch(error => { console.error(error); process.exitCode = 1 })
|