Files
weiguang-jewelry-ledger/新账系统/e2e/parity-create-order.mjs
T

741 lines
29 KiB
JavaScript
Raw 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.
#!/usr/bin/env node
// 开单对照(新旧界面同结果):每个场景启动两台时钟与随机源相同的全新服务,用同一份种子数据,
// 在一台上操作旧界面、另一台上操作新界面(/next/),同一账号做同样的输入后生成销售单据。
// 停服后转储两个数据库,除 operations(操作号与原始请求体)、sessions(登录令牌)外逐表逐行比较,
// 并核对两边页面显示的成交合计与纸单号一致。
// node e2e/parity-create-order.mjs [--reference-app 旧版应用目录] [--only 场景关键字] [--headed] [--keep]
// PARITY_SELF_TEST=1:自检,新界面第一处附加金额多填 1 元,对照必须报告不一致。
import { createRequire } from 'node:module';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
const require = createRequire(import.meta.url);
const { chromium } = require('playwright');
const { startServer } = require('./lib/server.js');
const { Session } = require('./lib/client.js');
const { Normalizer } = require('./lib/normalize.js');
const { dumpDatabase } = require('./lib/db-dump.js');
const { compare, report } = require('./lib/diff.js');
const HERE = path.dirname(fileURLToPath(import.meta.url));
const OUT = path.join(HERE, 'out', 'parity');
const args = process.argv.slice(2),
headed = args.includes('--headed'),
only = args.includes('--only') ? args[args.indexOf('--only') + 1] : '';
const referenceArg = args.indexOf('--reference-app');
const referenceApp = referenceArg < 0 ? process.env.LEDGER_REFERENCE_APP : args[referenceArg + 1];
if (referenceArg >= 0 && !referenceApp) throw new Error('--reference-app 需要旧版新账系统目录');
const referenceServer = referenceApp
? require(path.resolve(referenceApp, 'e2e/lib/server.js')).startServer
: startServer;
const D = '2026-11-20';
const SHANGHAI = 8 * 3600 * 1000;
const at = (hour, minute = 0, second = 0) =>
Date.parse(D + 'T00:00:00Z') - SHANGHAI + ((hour * 60 + minute) * 60 + second) * 1000;
const PW = { owner: 'parity-owner-pass-1', assistant: 'parity-assistant-pass', assistant2: 'parity-assistant2-pass' };
const LABEL = { owner: '麦麦', assistant: '娜娜', assistant2: '小昊' };
const EXCLUDED_TABLES = new Set(['operations', 'sessions']);
// —— 场景:seed 为两边相同的 HTTP 前置数据;steps 为界面输入(两种界面各自翻译成操作)——
const baseLine = [
['line', 0, 'quantity', '2.5'],
['line', 0, 'goldPrice', '950'],
['line', 0, 'laborRate', '30'],
['line', 0, 'cost-materialRate', '880'],
['line', 0, 'cost-labor', '25'],
];
const scenarios = [
{
name: '01 按克计价+克工费,附加项目编绳(改价)/证书(填0)/包装/快递,常用成本勾选',
user: 'owner',
steps: [
['customer', '对照客户一'],
['customerType', 'new'],
...baseLine,
['addCharge', 0, '编绳'],
['charge', 0, 0, 'amount', '60'],
['addCharge', 0, '证书'],
['charge', 0, 1, 'amount', '0'],
['addCharge', 0, '包装'],
['addCharge', 0, '快递'],
['feeIndex', 0, 'amount', '5'],
['blankFees', '0'],
['preset', 'jd', true],
['preset', 'box', true],
['presetQuantity', 'box', '2'],
['internalNote', '#对照 按克开单'],
],
},
{
name: '02 件工费,多件计工费',
user: 'owner',
steps: [
['customer', '对照客户二'],
['customerType', 'returning'],
['line', 0, 'quantity', '6.18'],
['line', 0, 'goldPrice', '948'],
['line', 0, 'laborMode', 'piece'],
['line', 0, 'laborRate', '80'],
['line', 0, 'pieces', '3'],
['line', 0, 'cost-materialRate', '870'],
['line', 0, 'cost-labor', '90'],
['internalNote', '三件对戒'],
],
},
{
name: '03 直接填写金额(按件,银饰)',
user: 'owner',
steps: [
['customer', '对照客户三'],
['customerType', 'new'],
['line', 0, 'nameType', '纯银925'],
['line', 0, 'unit', '件'],
['line', 0, 'quantity', '2'],
['line', 0, 'baseSale', '388'],
['line', 0, 'priceNote', '银手镯两只'],
['line', 0, 'cost-material', '120'],
['line', 0, 'cost-labor', '30'],
['payment', '支付宝'],
['internalNote', '银饰直接金额'],
],
},
{
name: '04 多行+整单优惠,取整 x.49 舍去',
user: 'owner',
steps: [
['customer', '对照客户四'],
['customerType', 'new'],
['line', 0, 'quantity', '1.237'],
['line', 0, 'goldPrice', '950'],
['line', 0, 'laborRate', '25'],
['line', 0, 'cost-materialRate', '880'],
['line', 0, 'cost-labor', '20'],
['addLine'],
['line', 1, 'pricingMode', 'manual'],
['line', 1, 'quantity', '1.5'],
['line', 1, 'baseSale', '1500.37'],
['line', 1, 'pocket', '金料'],
['line', 1, 'cost-materialMode', 'total'],
['line', 1, 'cost-material', '1300'],
['line', 1, 'cost-labor', '0'],
['discount', '100.50'],
['note', '优惠已含抹零'],
['internalNote', '两件合单'],
],
},
{
name: '05 多行+整单优惠,取整 x.50 进位',
user: 'owner',
steps: [
['customer', '对照客户五'],
['customerType', 'returning'],
['line', 0, 'pricingMode', 'manual'],
['line', 0, 'quantity', '1'],
['line', 0, 'baseSale', '1000.30'],
['line', 0, 'cost-materialMode', 'total'],
['line', 0, 'cost-material', '800'],
['line', 0, 'cost-labor', '10'],
['addLine'],
['line', 1, 'pricingMode', 'manual'],
['line', 1, 'quantity', '2'],
['line', 1, 'baseSale', '500.40'],
['line', 1, 'cost-materialMode', 'total'],
['line', 1, 'cost-material', '400'],
['line', 1, 'cost-labor', '5'],
['discount', '0.20'],
['internalNote', '取整进位'],
],
},
{
name: '06 信用卡收款(6‰ 手续费,付款人娜娜)',
user: 'owner',
steps: [
['customer', '对照客户六'],
['customerType', 'new'],
...baseLine,
['payment', '信用卡'],
['cardFeePayer', 'assistant'],
['internalNote', '刷卡付款'],
],
},
{
name: '07 内部成本不同付款人(料费店主、工费娜娜),进货工费按克与总额',
user: 'owner',
steps: [
['customer', '对照客户七'],
['customerType', 'new'],
['line', 0, 'quantity', '3.456'],
['line', 0, 'goldPrice', '952'],
['line', 0, 'laborRate', '28'],
['line', 0, 'cost-materialRate', '881.5'],
['line', 0, 'cost-laborMode', 'gram'],
['line', 0, 'cost-laborRate', '12.5'],
['line', 0, 'cost-materialPayer', 'owner'],
['line', 0, 'cost-laborPayer', 'assistant'],
['addLine'],
['line', 1, 'quantity', '1.2'],
['line', 1, 'goldPrice', '952'],
['line', 1, 'laborRate', '30'],
['line', 1, 'cost-materialMode', 'total'],
['line', 1, 'cost-material', '1050'],
['line', 1, 'cost-labor', '33'],
['line', 1, 'cost-laborPayer', 'assistant'],
['addFee', '镶嵌外加工', '40'],
['feeIndex', 0, 'payer', 'assistant'],
['internalNote', '分人垫付'],
],
},
{
name: '08 关联当日购料(加权料价自动核算料费)',
user: 'owner',
seed: async s => {
await s.post('owner', '/api/material-purchases', {
date: D,
grams: '10',
total: '9000',
payer: 'owner',
note: '对照购料',
});
await s.post('owner', '/api/material-purchases', {
date: D,
grams: '5',
total: '4600',
payer: 'assistant',
note: '对照购料二',
});
},
steps: [
['customer', '对照客户八'],
['customerType', 'new'],
['line', 0, 'quantity', '12'],
['line', 0, 'goldPrice', '960'],
['line', 0, 'laborRate', '20'],
['line', 0, 'materialSource', 'pool'],
['line', 0, 'cost-labor', '60'],
['internalNote', '用当日购料'],
],
},
{
name: '09 店员娜娜开单:老客户+备注快捷标签+其他成本',
user: 'assistant',
seed: async s => {
await s.post('assistant', '/api/orders/issue', seedOrder('assistant', '标签来源客户', '#回访 #自提 店员'));
},
steps: [
['customer', '对照客户九'],
['customerType', 'returning'],
...baseLine,
['addCharge', 0, '证书'],
['internalNote', '电话 #回'],
['tag', '#回访'],
['preset', 'yt', true],
['addFee', '打磨', '15'],
['payment', '现金'],
],
},
{
name: '10 旧草稿继续填写后开单',
user: 'owner',
seed: async (s, ctx) => {
const r = await s.post('owner', '/api/orders', {
date: D,
customer: '草稿客户',
salesperson: '麦麦',
customer_type: 'returning',
internal_note: '草稿备注',
payment_account: '麦麦微信',
rounding_mode: 'cent',
member: 'owner',
lines: [
{
name: '足金999',
unit: 'g',
quantity: '1.5',
pocket: '现货',
payer: 'owner',
pricingMode: 'auto',
goldPrice: '900',
laborRate: '20',
laborMode: 'gram',
charges: [],
costParts: { material: '1200', labor: '', accessories: '0', other: '0' },
costPayers: { material: 'owner', labor: 'owner' },
costMaterial: { mode: 'total' },
costLabor: { mode: 'total' },
},
],
fee_items: [],
});
ctx.draftId = r.id;
},
draft: true,
steps: [
['line', 0, 'cost-labor', '18'],
['discount', '0.4'],
['internalNote', '草稿补齐后开单'],
],
},
{
name: '11 填写后刷新页面,暂存内容继续开单',
user: 'owner',
steps: [
['customer', '对照客户十一'],
['customerType', 'new'],
...baseLine,
['addCharge', 0, '编绳'],
['fee', '编绳', 'amount', '3'],
['reload'],
['internalNote', '刷新后继续'],
],
},
{
name: '12 公式快速开单(两件)',
user: 'owner',
steps: [
['customer', '对照客户十二'],
['customerType', 'new'],
['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', '公式开单'],
],
},
];
function seedOrder(member, customer, note) {
return {
date: D,
customer,
customer_type: 'returning',
internal_note: note,
salesperson: LABEL[member],
payment_account: { owner: '麦麦微信', assistant: '助理微信', assistant2: '助理2微信' }[member],
rounding_mode: 'cent',
member,
lines: [
{
name: '足金999',
unit: 'g',
quantity: '1',
pocket: '现货',
payer: member,
pricingMode: 'manual',
sale: '1000',
cost: '850',
},
],
fee_items: [],
};
}
async function seed(server, base, scenario, ctx) {
const s = new Session({ base, server });
await s.day(D, 9);
await s.post('owner', '/api/setup', {
ownerPassword: PW.owner,
assistantPassword: PW.assistant,
assistant2Password: PW.assistant2,
});
await s.post('assistant', '/api/login', { name: '娜娜', password: PW.assistant });
for (const [pocket, grams] of [
['现货', '200'],
['金料', '80'],
])
await s.post('owner', '/api/stock', { date: D, kind: 'opening', pocket, grams, note: '对照起始库存' });
if (scenario.seed) await scenario.seed(s, ctx);
if (s.problems.length) throw new Error('前置数据写入失败:\n' + s.problems.join('\n'));
}
// —— 两种界面的操作翻译 ——
const OLD_FIELDS = {
'cost-materialMode': 'select',
'cost-laborMode': 'select',
'cost-materialPayer': 'select',
'cost-laborPayer': 'select',
materialSource: 'select:cost-materialSource',
nameType: 'select',
pricingMode: 'select',
unit: 'select',
laborMode: 'select',
pocket: 'select',
};
const oldUi = {
label: '旧界面',
async open(page, base) {
await page.goto(base + '/');
},
async login(page, user) {
await page.selectOption('#login-form select[name=member]', user);
await page.fill('#login-form input[name=password]', PW[user]);
await page.click('#login-form button.primary');
await page.waitForSelector('#order-form');
},
async openDraft(page, id) {
await page.click('nav [data-tab="orders"]');
await page.locator(`[data-action="open-order"][data-id="${id}"]`).first().click();
await page.locator('#order-dialog [data-action="edit"]').click();
await page.waitForSelector('#order-form input[name="orderId"][value="' + id + '"]', { state: 'attached' });
},
line: (page, i) => page.locator('#order-form .line-item').nth(i),
async step(page, [kind, ...rest]) {
const form = page.locator('#order-form');
if (kind === 'customer') return form.locator('input[name=customer]').fill(rest[0]);
if (kind === 'customerType') return form.locator(`input[name=customer_type][value=${rest[0]}]`).check();
if (kind === 'line') {
const [i, name, value] = rest,
line = this.line(page, i),
type = OLD_FIELDS[name];
if (type)
return line.locator(`select[name="${type.includes(':') ? type.split(':')[1] : name}"]`).selectOption(value);
return line.locator(`input[name="${name}"]`).fill(value);
}
if (kind === 'addLine') return form.locator('[data-action="add-line"]').click();
if (kind === 'addCharge') {
const line = this.line(page, rest[0]);
await line.locator('[data-action="add-charge"]').click();
if (rest[1] !== '编绳')
await line.locator('.charge-row').last().locator('select[name=chargeType]').selectOption(rest[1]);
return;
}
if (kind === 'charge')
return this.line(page, rest[0])
.locator('.charge-row')
.nth(rest[1])
.locator('input[name=chargeAmount]')
.fill(rest[3]);
if (kind === 'fee') {
const row = page
.locator('#fee-rows .fee-row')
.filter({ has: page.locator('.fee-name', { hasText: new RegExp('^' + rest[0] + '$') }) });
return rest[1] === 'amount'
? row.locator('input[name=feeAmount]').fill(rest[2])
: row.locator('select[name=feePayer]').selectOption(rest[2]);
}
if (kind === 'feeIndex') {
const row = page.locator('#fee-rows .fee-row').nth(rest[0]);
return rest[1] === 'amount'
? row.locator('input[name=feeAmount]').fill(rest[2])
: row.locator('select[name=feePayer]').selectOption(rest[2]);
}
if (kind === 'blankFees') {
for (const input of await page.locator('#fee-rows input[name=feeAmount]').all())
if (!(await input.inputValue())) await input.fill(rest[0]);
return;
}
if (kind === 'addFee') {
await form.locator('[data-action="add-fee"]').click();
// 旧界面同步后把整单费用排在附加项目费用之前,按名称输入框定位新加的一行。
const row = page
.locator('#fee-rows .fee-row')
.filter({ has: page.locator('input[name=feeNote]') })
.last();
await row.locator('input[name=feeNote]').fill(rest[0]);
return row.locator('input[name=feeAmount]').fill(rest[1]);
}
if (kind === 'preset') {
const box = form.locator(`input[name=cost_${rest[0]}]`);
return rest[1] ? box.check() : box.uncheck();
}
if (kind === 'presetQuantity') return form.locator(`input[name=cost_${rest[0]}_quantity]`).fill(rest[1]);
if (kind === 'payment') return form.locator('select[name=payment_method]').selectOption(rest[0]);
if (kind === 'cardFeePayer') return form.locator('select[name=credit_card_fee_payer]').selectOption(rest[0]);
if (kind === 'discount') return form.locator('input[name=discount]').fill(rest[0]);
if (kind === 'note') return form.locator('textarea[name=note]').fill(rest[0]);
if (kind === 'internalNote') return form.locator('textarea[name=internal_note]').fill(rest[0]);
if (kind === 'tag') return page.locator(`[data-order-note-tag="${rest[0]}"]`).click();
if (kind === 'reload') {
await page.reload();
return page.waitForSelector('#order-form');
}
if (kind === 'formula') {
await page.locator('.order-formula-panel > summary').click();
await page.fill('#order-formula-input', rest[0]);
await page.click('[data-action="order-formula-fill"]');
return page.waitForSelector('#order-formula-result .note');
}
throw new Error('旧界面不认识的步骤 ' + kind);
},
total: page => page.locator('#create-total').innerText(),
async submit(page) {
await page.click('#order-form button[type=submit]');
await page.waitForSelector('#order-dialog[open] .order-detail-identifiers', { timeout: 15000 });
const ids = await page.locator('#order-dialog .order-detail-identifiers').innerText();
return { paper: ids.match(/纸单号 (\S+)/)?.[1] };
},
};
const NEW_RADIO = new Set([
'pricingMode',
'unit',
'laborMode',
'cost-materialMode',
'cost-laborMode',
'materialSource',
]);
const NEW_SELECT = new Set(['nameType', 'pocket', 'cost-materialPayer', 'cost-laborPayer']);
const RADIO_LABEL = {
pricingMode: { auto: '按金价与工费计算', manual: '直接填写金额' },
laborMode: { gram: '克工费', piece: '件工费' },
'cost-materialMode': { gram: '按克料价', total: '直接填总料费' },
'cost-laborMode': { gram: '克工费', total: '总工费' },
materialSource: { manual: '手动填写成本', pool: '当日加权料价' },
};
const selectLabel = value => LABEL[value] || value;
async function chooseNew(page, scope, field, label) {
await scope.locator(`[data-field="${field}"] .ant-select-selector`).click();
const option = page.locator(
`.ant-select-dropdown:not(.ant-select-dropdown-hidden) .ant-select-item-option[title="${label}"]`,
);
await option.last().click();
await page.waitForTimeout(150);
}
async function radioNew(scope, field, label) {
await scope.locator(`[data-field="${field}"] .ant-radio-button-wrapper`, { hasText: label }).first().click();
}
const newUi = {
label: '新界面',
async open(page, base) {
await page.goto(base + '/next/');
},
async login(page, user) {
await page.waitForSelector('.login-form');
await chooseNew(page, page.locator('.login-form'), 'x', LABEL[user]).catch(async () => {
await page.locator('.login-form .ant-select-selector').click();
await page
.locator('.ant-select-dropdown:not(.ant-select-dropdown-hidden) .ant-select-item-option:visible', {
hasText: LABEL[user],
})
.first()
.click();
});
await page.fill('.login-form input[name=password]', PW[user]);
await page.locator('.login-form button[type=submit]').click();
await page.waitForSelector('#order-form');
},
async openDraft(page, id, base) {
await page.goto(base + '/next/?draft=' + id);
await page.waitForSelector('#order-form');
await page.waitForFunction(() => document.body.innerText.includes('正在继续填写旧草稿'));
},
line: (page, i) => page.locator('#order-form [data-line]').nth(i),
async step(page, [kind, ...rest]) {
if (process.env.PARITY_SELF_TEST && kind === 'charge') rest = [...rest.slice(0, 3), String(Number(rest[3]) + 1)];
const form = page.locator('#order-form');
const fill = (scope, field, value) =>
scope.locator(`[data-field="${field}"] input, [data-field="${field}"] textarea`).first().fill(value);
if (kind === 'customer') return fill(form, 'customer', rest[0]);
if (kind === 'customerType') return radioNew(form, 'customer_type', rest[0] === 'new' ? '新客户' : '老客户');
if (kind === 'line') {
const [i, name, value] = rest,
line = this.line(page, i);
if (NEW_RADIO.has(name)) return radioNew(line, name, RADIO_LABEL[name]?.[value] ?? value);
if (NEW_SELECT.has(name))
return chooseNew(page, line, name, name === 'pocket' && value === '' ? '外配/不扣黄金' : selectLabel(value));
return fill(line, name, value);
}
if (kind === 'addLine') return form.locator('[data-action="add-line"]').click();
if (kind === 'addCharge') {
const line = this.line(page, rest[0]);
await line.locator('[data-action="add-charge"]').click();
if (rest[1] !== '编绳') await chooseNew(page, line.locator('[data-charge]').last(), 'chargeType', rest[1]);
return;
}
if (kind === 'charge')
return fill(this.line(page, rest[0]).locator('[data-charge]').nth(rest[1]), 'chargeAmount', rest[3]);
const feeAction = (row, field, value) =>
field === 'amount' ? fill(row, 'feeAmount', value) : chooseNew(page, row, 'feePayer', selectLabel(value));
if (kind === 'fee')
return feeAction(
page
.locator('.fee-row')
.filter({ has: page.locator('.fee-name', { hasText: new RegExp('^' + rest[0] + '$') }) }),
rest[1],
rest[2],
);
if (kind === 'feeIndex') return feeAction(page.locator('.fee-row').nth(rest[0]), rest[1], rest[2]);
if (kind === 'blankFees') {
for (const input of await page.locator('.fee-row [data-field="feeAmount"] input').all())
if (!(await input.inputValue())) await input.fill(rest[0]);
return;
}
if (kind === 'addFee') {
await form.locator('[data-action="add-fee"]').click();
const row = page
.locator('.fee-row')
.filter({ has: page.locator('[data-field="feeNote"]') })
.last();
await fill(row, 'feeNote', rest[0]);
return fill(row, 'feeAmount', rest[1]);
}
if (kind === 'preset') {
const box = form.locator(`[data-preset="${rest[0]}"] input[type=checkbox]`);
return rest[1] ? box.check() : box.uncheck();
}
if (kind === 'presetQuantity') return fill(form, `cost_${rest[0]}_quantity`, rest[1]);
if (kind === 'payment') return radioNew(form, 'payment_method', rest[0]);
if (kind === 'cardFeePayer') return chooseNew(page, form, 'credit_card_fee_payer', selectLabel(rest[0]));
if (kind === 'discount') return fill(form, 'discount', rest[0]);
if (kind === 'note') return fill(form, 'note', rest[0]);
if (kind === 'internalNote') return fill(form, 'internal_note', rest[0]);
if (kind === 'tag') return page.locator(`[data-note-tag="${rest[0]}"]`).click();
if (kind === 'reload') {
await page.reload();
return page.waitForSelector('#order-form');
}
if (kind === 'formula') {
await page.locator('.entry-tools .ant-collapse-header', { hasText: '公式快速开单' }).click();
await page.locator('textarea[aria-label="粘贴销售公式"]').fill(rest[0]);
await page.locator('.formula-panel button', { hasText: '识别并预填' }).click();
return page.waitForSelector('.formula-panel .ant-alert-success');
}
throw new Error('新界面不认识的步骤 ' + kind);
},
total: page => page.locator('[data-testid="create-total"]').innerText(),
async submit(page) {
await page.locator('button[data-action="issue"]').click();
await page.waitForSelector('[data-testid="issued-paper-number"]', { timeout: 15000 });
return {
paper: (await page.locator('[data-testid="issued-paper-number"]').innerText()).trim(),
total: (await page.locator('[data-testid="issued-total"]').innerText()).trim(),
};
},
};
// —— 单边运行 ——
async function runSide(browser, ui, scenario, tag) {
const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'ledger-parity-'));
const server = (ui === oldUi ? referenceServer : startServer)({
mode: 'trial',
dataDir,
clockStart: new Date(at(9)).toISOString(),
seed: 'parity-seed',
});
const problems = [];
let context,
stopped = null;
const stop = () => (stopped ??= server.stop());
try {
const info = await server.ready();
const ctx = {};
await seed(server, info.base, scenario, ctx);
await server.setTime(at(10));
context = await browser.newContext({
viewport: { width: 1400, height: 1000 },
locale: 'zh-CN',
timezoneId: 'Asia/Shanghai',
});
const page = await context.newPage();
page.setDefaultTimeout(10000);
await page.clock.setFixedTime(new Date(at(10)));
page.on('pageerror', e => problems.push(`${ui.label} 页面错误:${e.message}`));
page.on('console', m => m.type() === 'error' && problems.push(`${ui.label} 控制台错误:${m.text()}`));
await ui.open(page, info.base);
await ui.login(page, scenario.user);
if (scenario.draft) await ui.openDraft(page, ctx.draftId, info.base);
for (const step of scenario.steps) {
try {
await ui.step(page, step);
} catch (error) {
fs.mkdirSync(OUT, { recursive: true });
await page.screenshot({
path: path.join(OUT, `${tag}-${ui === oldUi ? 'old' : 'new'}-failure.png`),
fullPage: true,
});
throw new Error(`${ui.label} 步骤 ${JSON.stringify(step)} 失败:${error.message}`);
}
await page.waitForTimeout(60);
}
await page.waitForTimeout(400);
const total = (await ui.total(page)).trim();
fs.mkdirSync(OUT, { recursive: true });
await page.screenshot({
path: path.join(OUT, `${tag}-${ui === oldUi ? 'old' : 'new'}-filled.png`),
fullPage: true,
});
await server.setTime(at(10, 30));
const shown = await ui.submit(page);
await page.waitForTimeout(500);
await page.screenshot({
path: path.join(OUT, `${tag}-${ui === oldUi ? 'old' : 'new'}-issued.png`),
fullPage: true,
});
await context.close();
context = null;
await stop();
const dump = dumpDatabase(path.join(dataDir, 'ledger.sqlite'));
return { total, shown, dump, problems };
} finally {
await context?.close().catch(() => {});
await stop();
if (!args.includes('--keep')) fs.rmSync(dataDir, { recursive: true, force: true });
}
}
function normalized(dump) {
const n = new Normalizer(),
out = {};
for (const [name, table] of Object.entries(dump.tables)) {
if (EXCLUDED_TABLES.has(name)) continue;
out[name] = {
columns: table.columns,
rows: table.rows.map(row =>
row.map(value => {
if (typeof value === 'string' && /^[[{]/.test(value))
try {
return n.value(JSON.parse(value));
} catch {
/* 非 JSON 文本按普通字符串处理 */
}
return n.value(value);
}),
),
};
}
return out;
}
const results = [];
const browser = await chromium.launch({ headless: !headed });
try {
for (const scenario of scenarios) {
if (only && !scenario.name.includes(only)) continue;
const tag = scenario.name.slice(0, 2);
console.log('▶ ' + scenario.name);
const result = { name: scenario.name, ok: false, notes: [] };
try {
const oldSide = await runSide(browser, oldUi, scenario, tag);
const newSide = await runSide(browser, newUi, scenario, tag);
const diff = compare(normalized(oldSide.dump), normalized(newSide.dump));
const counts = Object.fromEntries(
['orders', 'payments', 'expenses', 'movements', 'journal', 'material_pool_usages', 'team_fund_entries'].map(
t => [t, newSide.dump.tables[t]?.rows.length ?? 0],
),
);
result.problems = [...oldSide.problems, ...newSide.problems];
if (oldSide.total !== newSide.total)
result.problems.push(`成交合计不同:旧 ${oldSide.total},新 ${newSide.total}`);
if (newSide.shown.total !== newSide.total)
result.problems.push(`新界面开单后显示合计 ${newSide.shown.total} 与表单合计 ${newSide.total} 不同`);
if (!oldSide.shown.paper || oldSide.shown.paper !== newSide.shown.paper)
result.problems.push(`纸单号不同:旧 ${oldSide.shown.paper},新 ${newSide.shown.paper}`);
if (diff.diffs.length) result.problems.push(report('数据库', diff, 20));
result.ok = result.problems.length === 0;
result.detail = `合计 ${newSide.total} · 纸单号 ${newSide.shown.paper} · 行数 ${JSON.stringify(counts)}`;
} catch (error) {
result.problems = [`运行中断:${error.message.split('\n').slice(0, 3).join(' ')}`];
}
results.push(result);
console.log(` ${result.ok ? '✓ 一致' : '✗ 不一致'} ${result.detail || ''}`);
for (const p of result.problems) console.log(' ' + p.replace(/\n/g, '\n '));
}
} finally {
await browser.close();
}
const failed = results.filter(r => !r.ok);
console.log(
`\nparity ${failed.length ? 'FAIL' : 'PASS'}:${results.length - failed.length}/${results.length} 个场景新旧界面结果一致(截图在 e2e/out/parity/)`,
);
process.exitCode = failed.length ? 1 : 0;