import assert from 'node:assert/strict'; import { newUi, oldUi } from '../parity-create-order.mjs'; async function seedReturnedLot(session, day) { const post = async (path, params) => { const result = await session.postRaw('owner', path, params); assert.equal(result.status, 200, path + ' ' + JSON.stringify(result.body)); return result.body; }; await post('/api/stock', { date: day, kind: 'opening', pocket: '现货', grams: '60', note: '真实开单对照库存' }); // 真实售后生成完好现货批次,取消选择应恢复普通开单输入,实际再售应继承原工费与付款人。 const sale = await post('/api/orders/issue', { date: day, customer: '供退回现货的原单', member: 'owner', customer_type: 'new', salesperson: '麦麦', internal_note: '退回现货对照', payment_account: '麦麦微信', rounding_mode: 'cent', fee_items: [], lines: [ { name: '足金999', code: 'A031', unit: 'g', quantity: '2', pocket: '现货', payer: 'owner', sale: '1420', costParts: { material: '1200', labor: '50', accessories: '0', other: '0' }, costPayers: { material: 'owner', labor: 'assistant' }, }, ], }); const original = await session.get('owner', '/api/orders/' + sale.id); await post('/api/orders/' + sale.id + '/return', { date: day, revision: original.revision, reason: '按实物退回整件', verified: true, afterSale: { lines: [{ lineIndex: 0, quantity: '2', pocket: '现货', disposition: 'stock' }], refund: { account: '麦麦微信', payer: 'owner', amount: '1420', reference: '' }, deductionReason: '', expenses: [], }, }); const lots = () => session.get('owner', '/api/returned-stock-lots?member=owner&date=' + day); const lot = (await lots()).lots[0]; assert.ok(lot?.id); assert.equal(lot.laborCost, 5000); return { lot, lots }; } export default async function issue({ version, base, day, pageFor, session, step }) { const ui = version === 'old' ? oldUi : newUi; const page = await pageFor('owner'); const line = () => ui.line(page, 0); const control = name => line() .locator(version === 'old' ? '[name="' + name + '"]' : '[data-field="' + name + '"] input') .first(); const selectLot = () => line().locator('[name=returnedStockId]'); const clickSubmit = () => page.locator(version === 'old' ? '#order-form button[type=submit]' : 'button[data-action=issue]').click(); const isIssue = r => r.method() === 'POST' && new URL(r.url()).pathname === '/api/orders/issue'; async function steps(items) { for (const item of items) await ui.step(page, item); } let issued = false; async function start(customer) { if (issued) { if (version === 'new') { await page.locator('[data-action=new-order]').click(); } else { await page.locator('#order-dialog[open] [data-action=close-dialog]').click(); await page.locator('nav [data-tab=create]').click(); } await page.locator('#order-form').waitFor(); } else await ui.open(page, base); await page.locator('#order-form').waitFor(); await steps([ ['customer', customer], ['customerType', 'new'], ]); } async function issueSale(label) { let result; await step(label, async () => { const [response, shown] = await Promise.all([page.waitForResponse(r => isIssue(r.request())), ui.submit(page)]); assert.equal(response.status(), 200, await response.text()); assert.ok(shown.paper); const saved = await response.json(); result = { payload: response.request().postDataJSON(), order: await session.get('owner', '/api/orders/' + saved.id), }; assert.equal(result.order.paper_number, shown.paper); }); issued = true; return result; } async function rejected(label) { const issues = []; const watch = r => { if (isIssue(r)) issues.push(r.postDataJSON()); }; page.on('request', watch); try { await step(label, async () => { await clickSubmit(); await page.waitForLoadState('networkidle'); assert.deepEqual(issues, [], '本应被表单拦截的开单已发送请求'); assert.ok(await page.locator('#order-form').isVisible()); }); } finally { page.off('request', watch); } } const { lot, lots } = await seedReturnedLot(session, day); await start('公式两件开单'); await steps([ ['formula', '0.79×822+120=769\n0.58×(822+45)+55=558\n769+558=1327'], ['line', 0, 'cost-materialRate', '800'], ['line', 0, 'cost-labor', '10'], ['line', 1, 'cost-materialRate', '800'], ['line', 1, 'cost-labor', '10'], ['fee', '附加费', 'amount', '0'], ['internalNote', '按公式核对两件商品'], ]); const formula = await issueSale('多件公式识别后实际开单'); assert.equal(formula.order.lines.length, 2); assert.equal(formula.order.total, 132700); await start('金额和克重精度'); await steps([ ['line', 0, 'quantity', '0.0001'], ['line', 0, 'goldPrice', '999.50'], ['line', 0, 'laborRate', '0.00'], ['line', 0, 'cost-materialRate', '860.20'], ['line', 0, 'cost-labor', '0.00'], ['internalNote', '精度边界'], ]); await rejected('拒绝四位小数克重且保留表单'); await steps([ ['line', 0, 'quantity', '0.001'], ['line', 0, 'goldPrice', '999.501'], ]); await rejected('拒绝三位小数金额且保留表单'); await steps([['line', 0, 'goldPrice', '1e3']]); await rejected('拒绝科学计数法金额且保留表单'); await steps([ ['line', 0, 'goldPrice', '999.50'], ['line', 0, 'quantity', '0'], ]); await rejected('拒绝零克重且保留表单'); await steps([['line', 0, 'quantity', '0.001']]); await steps([ ['line', 0, 'goldPrice', '00999.50'], ['line', 0, 'cost-materialRate', '00860.20'], ]); const precision = await issueSale('毫克克重与含前导零的分位金额实际开单'); assert.equal(precision.order.lines[0].quantity, 1); assert.equal(precision.order.total, 100); assert.equal(typeof precision.payload.lines[0].quantity, 'string'); const ordinary = [ ['line', 0, 'quantity', '1.250'], ['line', 0, 'goldPrice', '971.25'], ['line', 0, 'laborRate', '8.50'], ['line', 0, 'cost-materialRate', '832.25'], ['line', 0, 'cost-labor', '3.25'], ]; await start('取消选用退回现货'); await steps([...ordinary, ['internalNote', '改回普通开单']]); const originalQuantity = await control('quantity').inputValue(); await selectLot().selectOption(lot.id); assert.equal(await control('quantity').inputValue(), '2.000'); assert.equal(await control('cost-labor').inputValue(), '50.00'); await selectLot().selectOption(''); assert.equal(await control('quantity').inputValue(), originalQuantity); assert.equal(await control('cost-labor').inputValue(), '3.25'); const ordinarySale = await issueSale('取消退回现货选择后按原输入开单'); assert.ok(!ordinarySale.order.lines[0].returnedStockId); assert.equal(ordinarySale.order.lines[0].costParts.labor, 325); assert.equal((await lots()).lots[0].id, lot.id); await start('完好退回现货再次销售'); await selectLot().selectOption(lot.id); await steps([ ['line', 0, 'goldPrice', '988.75'], ['line', 0, 'laborRate', '3.50'], ['internalNote', '整批原工费再售'], ]); const resale = await issueSale('整批退回现货沿用原工费再次销售'); assert.equal(resale.payload.lines[0].returnedStockId, lot.id); assert.equal(resale.order.lines[0].quantity, 2000); assert.equal(resale.order.lines[0].costParts.labor, 5000); assert.equal(resale.order.lines[0].costPayers.labor, 'assistant'); assert.ok(!(await lots()).lots.some(item => item.id === lot.id)); } // 使用同一个账号的两个真实标签页,验证首单成交后重新进入首页的草稿和下一张订单。 export async function exerciseIssueReopen({ version, base, day, session, pageFor, step }) { const ui = version === 'old' ? oldUi : newUi; const first = await pageFor('owner'); await session.post('owner', '/api/stock', { date: day, kind: 'opening', pocket: '现货', grams: '20', note: '两笔独立销售', }); const fill = async (page, items) => { for (const item of items) await ui.step(page, item); }; const line = (idx, quantity, price) => [ ['line', idx, 'quantity', quantity], ['line', idx, 'goldPrice', price], ['line', idx, 'laborRate', '0'], ['line', idx, 'cost-materialRate', '850'], ['line', idx, 'cost-labor', '0'], ]; const issue = async page => { const [response, shown] = await Promise.all([ page.waitForResponse(r => r.request().method() === 'POST' && new URL(r.url()).pathname === '/api/orders/issue'), ui.submit(page), ]); assert.equal(response.status(), 200); const { id } = await response.json(), saved = await session.get('owner', '/api/orders/' + id); assert.equal(saved.paper_number, shown.paper); await page.waitForLoadState('networkidle'); return saved; }; const draftKeyFor = id => (version === 'old' ? 'mm-draft-' : 'mm-next-draft-') + id; const ownerKey = draftKeyFor((await session.get('owner', '/api/session')).user.id); const assistantKey = draftKeyFor((await session.get('assistant', '/api/session')).user.id); const rawDraft = (page, key) => page.evaluate(k => localStorage.getItem(k), key); const customerInput = page => page.locator(version === 'old' ? '#order-form input[name=customer]' : '#order-form [data-field=customer] input'); // 同一浏览器轮流登录两位用户,两份草稿共享 localStorage,能抓到误清整个存储的问题。 async function openAs(role) { await first.context().addCookies([{ name: 'mm_session', value: session.cookies[role].slice(11), url: base }]); await ui.open(first, base); } await openAs('assistant'); await fill(first, [ ['customer', '店员未成交草稿'], ['line', 0, 'quantity', '0.625'], ]); await first.waitForFunction( key => JSON.parse(localStorage.getItem(key) || 'null')?.lines[0].quantity === '0.625', assistantKey, ); const assistantDraft = await rawDraft(first, assistantKey); await openAs('owner'); await fill(first, [ ['customer', '上一笔两件商品'], ['customerType', 'new'], ...line(0, '1', '899'), ['addLine'], ...line(1, '2', '900'), ['internalNote', '上一笔普通开单'], ]); await first.reload(); await first.locator('#order-form').waitFor(); assert.equal(await customerInput(first).inputValue(), '上一笔两件商品'); assert.equal(JSON.parse(await rawDraft(first, ownerKey)).lines.length, 2); await step('首笔普通两件商品完成销售', async () => { const saved = await issue(first); assert.equal(saved.lines.length, 2); assert.equal(saved.total, 269900); }); assert.equal(await rawDraft(first, assistantKey), assistantDraft); const draftKey = ownerKey; const persisted = await first.evaluate(key => { const raw = localStorage.getItem(key); if (!raw) return null; const d = JSON.parse(raw); return { customer: d.customer, lines: d.lines.map(row => ({ quantity: row.quantity, sale: row.sale })) }; }, draftKey); const next = await pageFor('owner', { fresh: true }); await next.locator('#order-form').waitFor(); const initialRows = await next .locator(version === 'old' ? '#order-form .line-item' : '#order-form [data-line]') .count(); await fill(next, [ ['customer', '新标签页第二笔'], ['customerType', 'new'], ...line(0, '0.001', '999.50'), ['internalNote', '第二笔应只收一元'], ]); await step('新标签页从首页录入第二笔销售', async () => { // 已真实入账、回应尚未到达时,在另一标签页填写第三笔。迟到的第二笔回执只能清第二笔。 await next.evaluate(() => { const fetch = window.fetch.bind(window); window.fetch = async (...args) => { const res = await fetch(...args); if (new URL(res.url).pathname === '/api/orders/issue') { await new Promise(resolve => { window.releaseIssuedReceipt = resolve; }); } return res; }; }); const pending = issue(next); const editThirdDraft = async () => { await next.waitForFunction(() => typeof window.releaseIssuedReceipt === 'function'); const third = await pageFor('owner', { fresh: true }); await fill(third, [ ['customer', '第三笔未成交草稿'], ['line', 0, 'quantity', '1.375'], ]); await third.waitForFunction( key => JSON.parse(localStorage.getItem(key) || 'null')?.lines[0].quantity === '1.375', ownerKey, ); const input = await rawDraft(third, ownerKey); await next.evaluate(() => window.releaseIssuedReceipt()); return input; }; const [saved, thirdDraft] = await Promise.all([pending, editThirdDraft()]); if (version === 'new') assert.equal(await rawDraft(next, ownerKey), thirdDraft, '第二笔回执清除了另一页填写的第三笔'); assert.equal(await rawDraft(next, assistantKey), assistantDraft, '第二笔回执清除了店员的草稿'); const evidence = JSON.stringify({ persisted, initialRows, total: saved.total, lines: saved.lines.map(l => ({ quantity: l.quantity, sale: l.sale })), }); assert.equal(saved.total, 100, '第二单沿用了已成交订单的商品:' + evidence); assert.equal(saved.lines.length, 1, evidence); assert.equal(initialRows, 1, evidence); assert.ok(!persisted || (!persisted.customer && persisted.lines.every(l => !l.quantity)), evidence); }); } // 已确认差异 D2(旧版缺陷登记,见 e2e/逐笔写入基线.md): // 料价日期默认跟随业务日期,只有手动选过料价日期才固定。旧版选中退回现货时把料价日期固定为批次日期, // 取消选择只恢复输入值、不恢复「跟随业务日期」,之后业务日期往返会把订单钉在前一天的料池。 // 对照只读取表单:同样的日期往返但不经过退回现货,证明旧版自身的规则也是跟随业务日期。 export async function exerciseIssuePoolDate({ version, base, day, session, pageFor, step, selectOrderDatePool = false, }) { const yesterday = '2026-11-19', ui = version === 'old' ? oldUi : newUi; const { lot } = await seedReturnedLot(session, day); await session.post('owner', '/api/material-purchases', { date: yesterday, grams: '8', total: '4000', payer: 'owner', note: '昨日购料', }); await session.post('owner', '/api/material-purchases', { date: day, grams: '5', total: '4500', payer: 'owner', note: '当日购料', }); const page = await pageFor('owner'); const fillSale = async customer => { for (const input of [ ['customer', customer], ['customerType', 'new'], ['internalNote', '核实重新选用料池'], ['line', 0, 'quantity', '1.250'], ['line', 0, 'goldPrice', '971.25'], ['line', 0, 'laborRate', '8.50'], ['line', 0, 'cost-materialRate', '832.25'], ['line', 0, 'cost-labor', '3.25'], ]) await ui.step(page, input); }; const toggleDate = async () => { const date = page .locator(version === 'old' ? '#order-form [name=date]' : '#order-form [data-field=date] input') .first(); for (const d of [yesterday, day]) { await date.fill(d); await date.blur(); await page.waitForLoadState('networkidle'); } }; const issue = async () => { const [response, shown] = await Promise.all([ page.waitForResponse(r => r.request().method() === 'POST' && new URL(r.url()).pathname === '/api/orders/issue'), ui.submit(page), ]); assert.equal(response.status(), 200); const { id } = await response.json(), order = await session.get('owner', '/api/orders/' + id); assert.equal(order.paper_number, shown.paper); await page.waitForLoadState('networkidle'); return { poolId: order.lines[0].costMaterial?.poolId, sale: order.total, material: order.lines[0].costParts.material, profit: order.profit, }; }; // 对照:同样输入和日期往返,但不经过退回现货,只读取表单选中的料价日期,不提交,不改变账本。 // 旧版在这里跟随业务日期回到当天,证明 D2 是取消退回现货时的状态残留,而非旧版的业务规则。 const selectedPoolDate = async () => { const field = ui.line(page, 0); if (version === 'old') return field.locator('[name="cost-materialPoolId"]').inputValue(); const label = await field.locator('[data-field="materialPoolId"] .ant-select-selection-item').innerText(); return label.match(/\d{4}-\d{2}-\d{2}/)?.[0]; }; await ui.open(page, base); await fillSale('料池日期对照'); await ui.step(page, ['line', 0, 'materialSource', 'pool']); await toggleDate(); assert.equal(await selectedPoolDate(), day, version + ' 未经退回现货时料价日期应跟随业务日期'); await page.evaluate(() => { for (const key of Object.keys(localStorage)) if (key.startsWith('mm-draft-') || key.startsWith('mm-next-draft-')) localStorage.removeItem(key); }); // 1.250g × 当日加权料价 814.29 元/克 = 1,017.86 元;前一天料池为 500 元/克,即 625.00 元。 await ui.open(page, base); await fillSale('退回现货切换日期'); const select = ui.line(page, 0).locator('[name=returnedStockId]'); await select.selectOption(lot.id); await select.selectOption(''); await ui.step(page, ['line', 0, 'materialSource', 'pool']); await toggleDate(); await step('撤销退回现货选择并切换日期后按料池实际开单', async () => { const result = await issue(), evidence = JSON.stringify(result); assert.equal(result.sale, 122500, evidence); if (version === 'old') { // 登记的旧版缺陷仍可复现:仅因选过又取消退回现货,订单被钉在前一天料池。 assert.equal(result.poolId, yesterday, '旧版缺陷 D2 未复现:' + evidence); assert.equal(result.material, 62500, evidence); assert.equal(result.profit, 59675, evidence); } else { // 已确认行为:取消退回现货后料价日期回到跟随业务日期。 assert.equal(result.poolId, day, '取消退回现货后料价日期应跟随业务日期:' + evidence); assert.equal(result.material, 101786, evidence); assert.equal(result.profit, 20389, evidence); } }); }