新旧开单对照与新版界面浏览器检查;verify.sh 增加 --with-next

parity-create-order.mjs:12 个场景各起两台相同时钟与种子的服务,旧界面与新界面同样输入后逐表比较数据库,
并核对成交合计与纸单号;browser-next.mjs:演示、初始化、密码登录,桌面与 390px 开单,CSP 与请求检查,
新旧开单页对照截图。

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
黄健铭andClaude Opus 5.5 committed 2026-12-04 19:15:24 -08:00
1 parent 03155ca33a
commit 6949b23d35
3 files changed
+1016 -3

No files matched your search

+270
View File
@@ -0,0 +1,270 @@
#!/usr/bin/env node
// 新版界面(/next/)浏览器检查:演示一键登录、试用空库初始化、密码登录,桌面与手机宽度(390px)开单。
// 断言:无页面错误、无控制台错误、无 CSP 违规、无失败请求、手机宽度无横向溢出。
// 截图:e2e/out/next/;新旧开单页对照截图:e2e/out/compare/。
// node e2e/browser-next.mjs [--headed]
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 HERE = path.dirname(fileURLToPath(import.meta.url));
const SHOTS = path.join(HERE, 'out', 'next'),
COMPARE = path.join(HERE, 'out', 'compare');
const headed = process.argv.includes('--headed');
const D = '2026-11-20';
const at = hour => Date.parse(D + 'T00:00:00Z') - 8 * 3600 * 1000 + hour * 3600 * 1000;
const PW = { owner: 'next-owner-pass-123', assistant: 'next-assistant-pass1', assistant2: 'next-assistant2-pass' };
const DESKTOP = { width: 1400, height: 1000 },
MOBILE = { width: 390, height: 844 };
const failures = [];
const fail = message => {
failures.push(message);
console.error(' ✗ ' + message);
};
const ok = message => console.log(' ✓ ' + message);
fs.rmSync(SHOTS, { recursive: true, force: true });
fs.rmSync(COMPARE, { recursive: true, force: true });
fs.mkdirSync(SHOTS, { recursive: true });
fs.mkdirSync(COMPARE, { recursive: true });
async function context(browser, base, label, viewport, mobile = false) {
const ctx = await browser.newContext({
viewport,
locale: 'zh-CN',
timezoneId: 'Asia/Shanghai',
...(mobile ? { isMobile: true, hasTouch: true, deviceScaleFactor: 2 } : {}),
});
await ctx.addInitScript(() => {
window.__cspViolations = [];
document.addEventListener('securitypolicyviolation', e =>
window.__cspViolations.push(e.violatedDirective + ' ' + (e.blockedURI || '')),
);
});
const watch = page => {
page.on('pageerror', e => fail(`[${label}] 页面未捕获错误:${e.message}`));
page.on('console', m => {
if (m.type() === 'error' || /Content Security Policy/i.test(m.text())) fail(`[${label}] 控制台错误:${m.text()}`);
});
page.on('requestfailed', r =>
fail(`[${label}] 请求未完成 ${r.method()} ${r.url().replace(base, '')} ${r.failure()?.errorText}`),
);
page.on('response', r => {
if (r.status() >= 400)
fail(`[${label}] 请求失败 ${r.status()} ${r.request().method()} ${r.url().replace(base, '')}`);
});
};
ctx.on('page', watch);
const page = await ctx.newPage();
page.setDefaultTimeout(10000);
return { ctx, page };
}
async function csp(page, label) {
const violations = await page.evaluate(() => window.__cspViolations || []);
if (violations.length) fail(`[${label}] CSP 违规:${violations.join(';')}`);
}
async function overflow(page, label) {
const width = await page.evaluate(() => document.documentElement.scrollWidth);
if (width > MOBILE.width + 1) fail(`[${label}] 手机宽度出现横向滚动(页面宽 ${width}px)`);
else ok(`${label} 390px 宽度无横向溢出`);
}
async function choose(page, scope, field, label) {
await scope.locator(`[data-field="${field}"] .ant-select-selector`).click();
await page
.locator(`.ant-select-dropdown:not(.ant-select-dropdown-hidden) .ant-select-item-option[title="${label}"]`)
.last()
.click();
// 选中后下拉框应收起(手机宽度同样)。
await page.waitForTimeout(400);
if (await page.locator('.ant-select-dropdown:not(.ant-select-dropdown-hidden)').count())
fail(`选择「${label}」后下拉框未收起`);
}
async function loginNext(page, label) {
await page.waitForSelector('.login-form');
await page.locator('.login-form .ant-select-selector').click();
await page
.locator(`.ant-select-dropdown:not(.ant-select-dropdown-hidden) .ant-select-item-option[title="${label}"]`)
.last()
.click();
await page.fill('.login-form input[name=password]', PW.owner);
await page.locator('.login-form button[type=submit]').click();
await page.waitForSelector('#order-form');
}
async function fillOrder(page, customer, { external = false } = {}) {
const form = page.locator('#order-form'),
line = form.locator('[data-line]').first();
const fill = (scope, field, value) =>
scope.locator(`[data-field="${field}"] input, [data-field="${field}"] textarea`).first().fill(value);
await fill(form, 'customer', customer);
await form.locator('[data-field="customer_type"] .ant-radio-button-wrapper', { hasText: '新客户' }).click();
await fill(line, 'quantity', '2.5');
await fill(line, 'goldPrice', '950');
await fill(line, 'laborRate', '30');
await line.locator('[data-action="add-charge"]').click();
await choose(page, line.locator('[data-charge]').last(), 'chargeType', '证书');
// 新开店铺尚未登记库存,选外配/不扣黄金。
if (external) await choose(page, line, 'pocket', '外配/不扣黄金');
await fill(line, 'cost-materialRate', '880');
await fill(line, 'cost-labor', '25');
const preset = form.locator('[data-preset] input[type=checkbox]');
if (await preset.count()) await preset.first().check();
await fill(form, 'internal_note', '#浏览器 新版开单');
}
async function issue(page, label, expectedTotal) {
const total = (await page.locator('[data-testid="create-total"]').innerText()).trim();
if (total === expectedTotal) ok(`${label} 表单合计 ${total}`);
else fail(`[${label}] 表单合计 ${total},期望 ${expectedTotal}`);
await page.locator('button[data-action="issue"]').click();
await page.waitForSelector('[data-testid="issued-paper-number"], [data-testid="order-error"]', { timeout: 15000 });
if (await page.getByTestId('order-error').count())
throw new Error(label + ' 开单失败:' + (await page.getByTestId('order-error').innerText()));
const paper = (await page.locator('[data-testid="issued-paper-number"]').innerText()).trim();
const shown = (await page.locator('[data-testid="issued-total"]').innerText()).trim();
if (/^\d{11}$/.test(paper) && shown === expectedTotal) ok(`${label} 开单成功:纸单号 ${paper},合计 ${shown}`);
else fail(`[${label}] 开单结果异常:纸单号 ${paper},合计 ${shown}`);
return paper;
}
const browser = await chromium.launch({ headless: !headed });
const servers = [];
const start = async (mode, seed) => {
const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'ledger-next-'));
const server = startServer({
mode,
dataDir,
clockStart: new Date(at(10)).toISOString(),
seed: 'next-' + mode,
tickMs: 1,
});
servers.push({ server, dataDir });
const info = await server.ready();
return { server, base: info.base };
};
try {
// 1. 演示模式:一键进入
console.log('▶ 演示模式一键登录');
{
const { base } = await start('demo');
const { ctx, page } = await context(browser, base, '演示', DESKTOP);
await page.goto(base + '/next/');
await page.waitForSelector('.login-card');
await page.screenshot({ path: path.join(SHOTS, '01-demo-login.png'), fullPage: true });
await page.getByRole('button', { name: /以麦麦身份进入演示/ }).click();
await page.waitForSelector('#order-form');
ok('演示模式以麦麦身份进入开单页');
if ((await page.locator('a.old-ui-link').getAttribute('href')) === '/') ok('顶栏有“返回旧版界面”链接');
else fail('顶栏缺少返回旧版界面链接');
await page.screenshot({ path: path.join(SHOTS, '02-demo-create.png'), fullPage: true });
await page.getByRole('button', { name: /退\s*出/ }).click();
await page.waitForSelector('.login-card');
ok('退出后回到登录页');
await csp(page, '演示');
await ctx.close();
}
// 2. 试用空库:初始化后直接进入开单,桌面开单并打开打印预览
console.log('▶ 试用空库初始化与桌面开单');
{
const { base } = await start('trial');
const { ctx, page } = await context(browser, base, '试用初始化', DESKTOP);
await page.goto(base + '/next/');
await page.waitForSelector('.setup-form');
await page.fill('.setup-form input[name=storeName]', '新版对照珠宝');
await page.fill('.setup-form input[name=ownerPassword]', PW.owner);
await page.screenshot({ path: path.join(SHOTS, '03-trial-setup.png'), fullPage: true });
await page.locator('.setup-form button[type=submit]').click();
await page.waitForSelector('#order-form');
if ((await page.getByTestId('store-name').innerText()) === '新版对照珠宝')
ok('初始化后进入开单页,顶栏显示店铺名称');
else fail('初始化后店铺名称不符');
await fillOrder(page, '新版桌面客户', { external: true });
await page.screenshot({ path: path.join(SHOTS, '04-desktop-filled.png'), fullPage: true });
await issue(page, '桌面', '¥2,460');
await page.screenshot({ path: path.join(SHOTS, '05-desktop-issued.png'), fullPage: true });
const [popup] = await Promise.all([
ctx.waitForEvent('page'),
page.locator('[data-action="print-preview"]').click(),
]);
await popup.waitForLoadState('load');
if ((await popup.textContent('body')).includes('新版桌面客户')) ok('打印预览 /print/<订单号> 显示新订单');
else fail('打印预览未显示新订单');
await popup.screenshot({ path: path.join(SHOTS, '06-print-preview.png'), fullPage: true });
await popup.close();
await page.locator('[data-action="new-order"]').click();
await page.waitForSelector('#order-form');
if ((await page.locator('[data-field="customer"] input').inputValue()) === '') ok('开始新的一单后表单已清空');
else fail('开始新的一单后表单未清空');
await page.getByRole('button', { name: /退\s*出/ }).click();
await loginNext(page, '店主');
ok('密码登录(店主)');
await csp(page, '试用初始化');
await ctx.close();
}
// 3. 三人账号:手机宽度密码登录并开单;新旧开单页对照截图
console.log('▶ 手机宽度开单与新旧对照截图');
{
const { server, base } = await start('trial');
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('owner', '/api/stock', {
date: D,
kind: 'opening',
pocket: '现货',
grams: '100',
note: '浏览器检查起始库存',
});
if (s.problems.length) throw new Error(s.problems.join('\n'));
for (const [name, viewport, mobile] of [
['desktop', DESKTOP, false],
['mobile', MOBILE, true],
]) {
const label = name === 'mobile' ? '手机' : '桌面对照';
const { ctx, page } = await context(browser, base, label, viewport, mobile);
await page.goto(base + '/next/');
await loginNext(page, '麦麦');
await page.waitForTimeout(400);
await page.screenshot({ path: path.join(COMPARE, `create-${name}-new.png`), fullPage: true });
if (mobile) {
await overflow(page, '新版开单页');
await page.screenshot({ path: path.join(SHOTS, '07-mobile-login-create.png'), fullPage: true });
await fillOrder(page, '新版手机客户');
await overflow(page, '新版开单页(已填写)');
await page.screenshot({ path: path.join(SHOTS, '08-mobile-filled.png'), fullPage: true });
await issue(page, '手机', '¥2,460');
await page.screenshot({ path: path.join(SHOTS, '09-mobile-issued.png'), fullPage: true });
}
await csp(page, label);
// 旧界面同一账号同一宽度的开单页
const old = await ctx.newPage();
// 共用 mm_session cookie:新界面登录后旧界面直接进入,无需再次登录。
await old.goto(base + '/');
await old.waitForSelector('#order-form');
ok(`${label}:新界面登录后旧界面共用同一会话`);
await old.waitForTimeout(400);
await old.screenshot({ path: path.join(COMPARE, `create-${name}-old.png`), fullPage: true });
await ctx.close();
}
ok('新旧开单页对照截图已保存(桌面、手机)');
}
} catch (error) {
fail('流程中断:' + error.message.split('\n')[0]);
} finally {
await browser.close();
for (const { server, dataDir } of servers) {
await server.stop();
fs.rmSync(dataDir, { recursive: true, force: true });
}
}
console.log(
`browser-next ${failures.length ? 'FAIL' : 'PASS'}:${failures.length} 个问题(截图在 e2e/out/next/,对照截图在 e2e/out/compare/)`,
);
process.exitCode = failures.length ? 1 : 0;
+734
View File
@@ -0,0 +1,734 @@
#!/usr/bin/env node
// 开单对照(新旧界面同结果):每个场景启动两台时钟与随机源相同的全新服务,用同一份种子数据,
// 在一台上操作旧界面、另一台上操作新界面(/next/),同一账号做同样的输入后生成销售单据。
// 停服后转储两个数据库,除 operations(操作号与原始请求体)、sessions(登录令牌)外逐表逐行比较,
// 并核对两边页面显示的成交合计与纸单号一致。
// node e2e/parity-create-order.mjs [--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 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 = 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;
+12 -3
View File
@@ -1,11 +1,12 @@
#!/usr/bin/env bash #!/usr/bin/env bash
# 一键验证:黄金对照、旧库兼容、浏览器流程;--with-unit 追加全部单元测试。 # 一键验证:黄金对照、旧库兼容、浏览器流程;--with-unit 追加全部单元测试。
# 用法:bash e2e/verify.sh [--with-unit] [--skip-browser] # 用法:bash e2e/verify.sh [--with-unit] [--skip-browser] [--with-next]
# --with-next:追加新版界面(/next/)的新旧开单对照与浏览器检查(使用已提交的 web/dist)。
# 首次运行浏览器检查前:(cd e2e && PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1 npm ci) # 首次运行浏览器检查前:(cd e2e && PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1 npm ci)
set -u set -u
HERE="$(cd "$(dirname "$0")" && pwd)"; APP="$(dirname "$HERE")"; cd "$APP" HERE="$(cd "$(dirname "$0")" && pwd)"; APP="$(dirname "$HERE")"; cd "$APP"
WITH_UNIT=0; SKIP_BROWSER=0 WITH_UNIT=0; SKIP_BROWSER=0; WITH_NEXT=0
for arg in "$@"; do case "$arg" in --with-unit) WITH_UNIT=1;; --skip-browser) SKIP_BROWSER=1;; *) echo "未知参数:$arg"; exit 2;; esac; done for arg in "$@"; do case "$arg" in --with-unit) WITH_UNIT=1;; --skip-browser) SKIP_BROWSER=1;; --with-next) WITH_NEXT=1;; *) echo "未知参数:$arg"; exit 2;; esac; done
declare -a NAMES RESULTS TIMES; FAILED=0 declare -a NAMES RESULTS TIMES; FAILED=0
run(){ local name="$1"; shift; echo; echo "════ $name ════"; local start=$SECONDS run(){ local name="$1"; shift; echo; echo "════ $name ════"; local start=$SECONDS
if "$@"; then RESULTS+=("PASS"); else RESULTS+=("FAIL"); FAILED=1; fi if "$@"; then RESULTS+=("PASS"); else RESULTS+=("FAIL"); FAILED=1; fi
@@ -16,6 +17,14 @@ if [ "$SKIP_BROWSER" = 0 ]; then
if [ -d "$HERE/node_modules/playwright" ]; then run "浏览器流程(browser)" node e2e/browser.mjs --check if [ -d "$HERE/node_modules/playwright" ]; then run "浏览器流程(browser)" node e2e/browser.mjs --check
else echo "缺少 e2e/node_modules/playwright,请先执行:(cd e2e && PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1 npm ci)"; NAMES+=("浏览器流程(browser)"); RESULTS+=("FAIL"); TIMES+=("0s"); FAILED=1; fi else echo "缺少 e2e/node_modules/playwright,请先执行:(cd e2e && PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1 npm ci)"; NAMES+=("浏览器流程(browser)"); RESULTS+=("FAIL"); TIMES+=("0s"); FAILED=1; fi
fi fi
if [ "$WITH_NEXT" = 1 ]; then
# 已提交的 web/dist 必须与源码重新构建的结果一致(需先在 web/ 下 npm ci)。
if [ -d "$APP/web/node_modules" ]; then
run "新版构建与提交一致(web/dist)" bash -c 'cd web && npx vite build --logLevel error && git diff --quiet --exit-code -- dist && test -z "$(git ls-files --others --exclude-standard -- dist)"'
fi
run "新旧开单对照(parity)" node e2e/parity-create-order.mjs
run "新版界面浏览器(browser-next)" node e2e/browser-next.mjs
fi
[ "$WITH_UNIT" = 1 ] && run "单元测试(node --test test/)" node --test test/ [ "$WITH_UNIT" = 1 ] && run "单元测试(node --test test/)" node --test test/
echo; echo "════ 汇总 ════" echo; echo "════ 汇总 ════"
for i in "${!NAMES[@]}"; do printf '%-6s %-28s %s\n' "${RESULTS[$i]}" "${NAMES[$i]}" "${TIMES[$i]}"; done for i in "${!NAMES[@]}"; do printf '%-6s %-28s %s\n' "${RESULTS[$i]}" "${NAMES[$i]}" "${TIMES[$i]}"; done