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 dialog and shared Axios adapter, isolated return/receipt state only. // No procurement or warehouse write is sent to the live backend. ;(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 fixtures = new Map(), writes = [], errors = [], scenarios = [] const fixture = (id, extra = {}) => { const row = { id, accepted: 10, received: 0, history: [], supported: true, ...extra } fixtures.set(id, row); return row } fixture(99911, { received: 4, history: [{ quantity: 2, business_key: 'earlier-return' }] }) fixture(99912, { accepted: 8, received: 8 }) fixture(99913, { accepted: 9, history: [{ quantity: 9 }] }) fixture(99914, { supported: false, message: '该历史验收未建立分次入库来源,请先核对历史记录' }) fixture(99915, { availabilityFailures: 1 }) fixture(99916, { historyFailures: 1 }) fixture(99917, { accepted: 6, concurrentReceipt: true }) fixture(99918, { accepted: 3, loseResponse: true }) fixture(99919, { accepted: 3, loseResponse: true }) fixture(99920, { availabilityDelay: 180, availabilityFailures: 1 }) fixture(99921, { accepted: 7, availabilityDelay: 10 }) 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 }]) 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 } }) const fail = msg => route.fulfill({ json: { code: 500, msg } }) if (/^\/warehouse\/purchase\/returns\/\d+\/availability$/.test(path)) { assert.equal(method, 'GET') const row = fixtures.get(Number(path.split('/').at(-2))); assert.ok(row) await delay(row.availabilityDelay || 0) if (row.availabilityFailures > 0) { row.availabilityFailures--; return fail('模拟退货数量加载失败') } const returned = row.history.reduce((sum, entry) => sum + entry.quantity, 0) return ok({ arrivalId: row.id, acceptedQuantity: row.accepted, returnedQuantity: returned, receivedQuantity: row.received, returnableQuantity: row.supported ? row.accepted - returned - row.received : 0, supported: row.supported, message: row.message || '' }) } if (path === '/warehouse/purchase/returns' && method === 'GET') { const row = fixtures.get(Number(url.searchParams.get('arrivalId'))); assert.ok(row) if (row.historyFailures > 0) { row.historyFailures--; return fail('模拟退货记录加载失败') } return ok(row.history) } if (path === '/warehouse/purchase/returns' && method === 'POST') { const payload = req.postDataJSON(), row = fixtures.get(payload.arrivalId); assert.ok(row) writes.push(payload) const existing = row.history.find(record => record.business_key === payload.key) if (existing) { assert.equal(existing.quantity, payload.quantity); return ok({}) } if (row.concurrentReceipt) { row.concurrentReceipt = false; row.received = 4; return fail('退货超过待入库数量,请先撤销对应入库') } const available = row.accepted - row.received - row.history.reduce((sum, entry) => sum + entry.quantity, 0) assert.ok(payload.quantity > 0 && payload.quantity <= available) row.history.push({ quantity: payload.quantity, cancel_purchase: payload.cancelPurchase, business_key: payload.key }) if (row.loseResponse) { row.loseResponse = false; return fail('模拟退货已保存但响应失败') } return ok({}) } if (!['GET', 'HEAD'].includes(method)) throw Error('Unexpected live write blocked: ' + method + ' ' + path) return route.continue() }) const page = await context.newPage() page.on('pageerror', error => errors.push(error.message)); page.setDefaultTimeout(15000) await page.goto(frontend + '/index') await page.locator('.app-main').waitFor() await page.evaluate(async () => { const { createApp, h, ElementPlus } = await import('/tests/browser-runtime.js') const { default: Component } = await import('/src/components/ReceiptDialog/PurchaseReturn.vue') const host = document.createElement('div'); document.body.append(host) window.returnWarnings = []; window.returnChanged = 0; window.returnSuccess = [] const app = createApp({ render: () => h(Component, { onChanged: () => window.returnChanged++ }) }).use(ElementPlus) Object.assign(app.config.globalProperties, { parseTime: () => '2026-10-14', $modal: { msgSuccess: text => window.returnSuccess.push(text), msgWarning: text => window.returnWarnings.push(text) } }) app.mount(host); window.returnAudit = { app, host, vm: app._instance.subTree.component.proxy } }) const open = async id => { await page.evaluate(async id => { await window.returnAudit.vm.open({ id, materialName: '回归测试物品', arrivalNo: 'DH' + id, arrivalQuantity: 1000, defectiveQuantity: 0 }) }, id) await page.getByRole('dialog', { name: '采购退货', exact: true }).waitFor() } const close = async () => { await page.getByRole('dialog', { name: '采购退货', exact: true }).getByRole('button', { name: '取消', exact: true }).click() await page.getByRole('dialog', { name: '采购退货', exact: true }).waitFor({ state: 'hidden' }) await page.waitForTimeout(350) } const state = () => page.evaluate(() => { const v = window.returnAudit.vm return { visible: v.visible, quantity: v.form.quantity, maximum: v.maximum, canReturn: v.canReturn, loadError: v.loadError, submitError: v.submitError, key: v.form.key, reason: v.unavailableReason } }) const pass = text => { scenarios.push(text); console.log('PASS ' + text) } await open(99911) assert.equal((await state()).quantity, 4) assert.equal((await state()).maximum, 4) const dialog = page.getByRole('dialog', { name: '采购退货', exact: true }) assert.deepEqual(await dialog.locator('.return-quantities strong').allTextContents(), ['4', '4', '2']) await page.evaluate(async () => { const v = window.returnAudit.vm; v.form.quantity = 5; await v.save(); v.form.quantity = 4 }) assert.equal(writes.length, 0) fixtures.get(99911).received = 2 await dialog.getByRole('button', { name: '刷新数量', exact: true }).click() await page.waitForFunction(() => !window.returnAudit.vm.opening) assert.equal((await state()).maximum, 6) assert.equal((await state()).quantity, 4, 'Refresh must not increase the entered return quantity') fs.mkdirSync('.codex-tmp/vue3-purchase-return', { recursive: true }) await page.setViewportSize({ width: 1024, height: 600 }) await page.waitForTimeout(400) assert.equal(await dialog.evaluate(el => el.scrollWidth > el.clientWidth + 1), false) await page.screenshot({ path: '.codex-tmp/vue3-purchase-return/availability.png' }) await close() pass('Server availability ignores stale row totals, excludes received/returned goods and grows after receipt withdrawal without increasing the entered quantity') for (const [id, message] of [[99912, '已入库部分需先'], [99913, '已全部退货'], [99914, '历史验收未建立']]) { await open(id) assert.equal((await state()).canReturn, false) assert.ok((await state()).reason.includes(message)) assert.equal(await dialog.getByRole('button', { name: '确认退货', exact: true }).isDisabled(), true) await page.evaluate(() => window.returnAudit.vm.save()) await close() } assert.equal(writes.length, 0) pass('Fully received, fully returned and unsupported legacy arrivals explain why return is unavailable and block writes') for (const id of [99915, 99916]) { await open(id) assert.equal((await state()).loadError, true) assert.equal((await state()).visible, true) assert.equal((await state()).canReturn, false) await dialog.getByRole('button', { name: '重新加载', exact: true }).click() await page.waitForFunction(() => !window.returnAudit.vm.opening) assert.equal((await state()).quantity, 10) assert.equal((await state()).loadError, false) fixtures.get(id).availabilityFailures = 1 await dialog.getByRole('button', { name: '刷新数量', exact: true }).click() await page.waitForFunction(() => !window.returnAudit.vm.opening) assert.equal((await state()).canReturn, false, 'Failed refresh must not leave an old limit actionable') await dialog.getByRole('button', { name: '重新加载', exact: true }).click() await page.waitForFunction(() => !window.returnAudit.vm.opening) assert.equal((await state()).canReturn, true) await close() } pass('Availability/history failures retain the dialog with reload, and a failed refresh never permits stale quantity submission') await open(99917) await dialog.getByRole('button', { name: '确认退货', exact: true }).click() await page.waitForFunction(() => !window.returnAudit.vm.saving) assert.equal((await state()).submitError, true) assert.equal(writes.length, 1, 'A business rejection must not automatically repeat the mutation') const originalKey = (await state()).key await dialog.getByRole('button', { name: '刷新数量', exact: true }).click() await page.waitForFunction(() => !window.returnAudit.vm.opening) assert.equal((await state()).quantity, 2) assert.equal((await state()).maximum, 2) assert.equal((await state()).key, originalKey) assert.equal(writes.length, 1) await dialog.getByRole('button', { name: '确认退货', exact: true }).click() await dialog.waitFor({ state: 'hidden' }); await page.waitForTimeout(350) assert.equal(writes.length, 2) assert.deepEqual(writes.map(row => row.quantity), [6, 2]) pass('Concurrent receipt is rejected without automatic resubmission; explicit refresh reduces the limit and the reviewed retry succeeds') await open(99918) await dialog.getByRole('button', { name: '确认退货', exact: true }).click() await page.waitForFunction(() => !window.returnAudit.vm.saving) assert.equal((await state()).submitError, true) const beforeRefresh = writes.length, changedBefore = await page.evaluate(() => window.returnChanged) await dialog.getByRole('button', { name: '刷新数量', exact: true }).click() await dialog.waitFor({ state: 'hidden' }); await page.waitForTimeout(350) assert.equal(writes.length, beforeRefresh) assert.equal(fixtures.get(99918).history.length, 1) assert.equal(await page.evaluate(() => window.returnChanged), changedBefore + 1) assert.equal(await page.evaluate(() => window.returnSuccess.at(-1)), '已确认此前退货成功') pass('Lost success response followed by refresh recognizes the saved business key, confirms completion and sends no second return') await open(99919) await dialog.getByRole('button', { name: '确认退货', exact: true }).click() await page.waitForFunction(() => !window.returnAudit.vm.saving) const retryKey = (await state()).key await dialog.getByRole('button', { name: '确认退货', exact: true }).click() await dialog.waitFor({ state: 'hidden' }); await page.waitForTimeout(350) assert.equal(fixtures.get(99919).history.length, 1) assert.deepEqual(writes.filter(row => row.arrivalId === 99919).map(row => row.key), [retryKey, retryKey]) pass('Lost success response can also be retried immediately using the original idempotency key without duplicate return') await page.evaluate(async () => { const v = window.returnAudit.vm; await Promise.all([v.open({ id: 99920 }), v.open({ id: 99921 })]) }) assert.equal((await state()).quantity, 7) assert.equal((await state()).loadError, false) await close() pass('Late failed requests from an earlier arrival cannot replace the latest arrival quantity or error state') assert.deepEqual(errors, []) await page.evaluate(() => { window.returnAudit.app.unmount(); window.returnAudit.host.remove() }) fs.writeFileSync('.codex-tmp/vue3-purchase-return/result.json', JSON.stringify({ at: new Date().toISOString(), scenarios, simulatedWrites: writes.length, actualBusinessWrites: 0, errors }, null, 2)) console.log('PURCHASE RETURN PASS', JSON.stringify({ scenarios: scenarios.length, simulatedWrites: writes.length, actualBusinessWrites: 0 })) } finally { await browser.close() } })().catch(error => { console.error(error); process.exitCode = 1 })