559 lines
25 KiB
JavaScript
559 lines
25 KiB
JavaScript
#!/usr/bin/env node
|
||
// 对两份独立的试用数据库输入相同业务数据,逐页检查表单、交互、请求与落库结果。
|
||
// node e2e/parity-pages.mjs;--reference-app <迁移前的「新账系统」目录> 指定独立旧版。
|
||
// --legacy-only 单独复核旧界面的基线与测试数据。
|
||
import assert from 'node:assert/strict';
|
||
import fs from 'node:fs';
|
||
import os from 'node:os';
|
||
import path from 'node:path';
|
||
import { chromium } from 'playwright';
|
||
import { createRequire } from 'node:module';
|
||
import { startServer } from './lib/server.js';
|
||
import { Session } from './lib/client.js';
|
||
import { dumpDatabase } from './lib/db-dump.js';
|
||
import { Normalizer } from './lib/normalize.js';
|
||
import { compare, report } from './lib/diff.js';
|
||
|
||
const DAY = '2026-11-20';
|
||
const TIME = DAY + 'T02:00:00Z';
|
||
const pageTitles = {
|
||
'price-locks': '待交付',
|
||
'material-pools': '每日购料',
|
||
recoveries: '回收/置换',
|
||
orders: '订单',
|
||
stock: '货盘库存',
|
||
report: '每日对账',
|
||
'team-funds': '团队账目',
|
||
'private-operations': '私域运营概况',
|
||
'people-entry': '登记人数',
|
||
settings: '店铺与打印设置',
|
||
};
|
||
const roles = ['assistant', 'owner'];
|
||
|
||
async function seed(server, base) {
|
||
const session = new Session({ server, base });
|
||
const yesterday = '2026-11-19';
|
||
await session.day(yesterday);
|
||
await session.post('owner', '/api/setup', {
|
||
ownerPassword: 'page-parity-owner',
|
||
assistantPassword: 'page-parity-assistant',
|
||
assistant2Password: 'page-parity-assistant2',
|
||
});
|
||
await session.post('assistant', '/api/login', { name: '娜娜', password: 'page-parity-assistant' });
|
||
await session.post('owner', '/api/stock', {
|
||
date: yesterday,
|
||
kind: 'opening',
|
||
pocket: '现货',
|
||
grams: '100',
|
||
note: '期初',
|
||
});
|
||
const order = (date, customer) => ({
|
||
date,
|
||
customer,
|
||
customer_type: 'new',
|
||
internal_note: '页面对照旧单',
|
||
salesperson: '娜娜',
|
||
member: 'assistant',
|
||
payment_account: '助理微信',
|
||
rounding_mode: 'cent',
|
||
lines: [
|
||
{
|
||
name: '足金999',
|
||
unit: 'g',
|
||
quantity: '1',
|
||
pocket: '现货',
|
||
payer: 'assistant',
|
||
sale: '1000',
|
||
costParts: { material: '800', labor: '50', accessories: '0', other: '0' },
|
||
costPayers: { material: 'assistant', labor: 'assistant' },
|
||
},
|
||
],
|
||
fee_items: [],
|
||
});
|
||
await session.post('assistant', '/api/orders/issue', order(yesterday, '昨日对照原单'));
|
||
await session.day(DAY);
|
||
await session.post('owner', '/api/login', { name: '麦麦', password: 'page-parity-owner' });
|
||
await session.post('assistant', '/api/login', { name: '娜娜', password: 'page-parity-assistant' });
|
||
await session.post('assistant', '/api/orders/issue', order(DAY, '页面对照客户'));
|
||
assert.deepEqual(session.problems, []);
|
||
return session.cookies;
|
||
}
|
||
|
||
// 页面内切换不会重新触发 load;等后续的明细、计数和权限请求也完成再采样。
|
||
const requests = new WeakMap();
|
||
function observeRequests(page) {
|
||
const traffic = { active: new Set(), last: performance.now() };
|
||
requests.set(page, traffic);
|
||
page.on('request', request => {
|
||
traffic.active.add(request);
|
||
traffic.last = performance.now();
|
||
});
|
||
const done = request => {
|
||
traffic.active.delete(request);
|
||
traffic.last = performance.now();
|
||
};
|
||
page.on('requestfinished', done);
|
||
page.on('requestfailed', done);
|
||
}
|
||
async function settle(page) {
|
||
const traffic = requests.get(page);
|
||
const start = performance.now();
|
||
do {
|
||
await page.waitForTimeout(50);
|
||
if (performance.now() - start > 15000)
|
||
throw new Error('页面未完成加载:' + [...traffic.active].map(r => r.url()).join(', '));
|
||
} while (traffic.active.size || performance.now() - Math.max(start, traffic.last) < 300);
|
||
await page.evaluate(() => new Promise(resolve => requestAnimationFrame(resolve)));
|
||
}
|
||
|
||
// 对照字段的实际属性和值,保留隐藏字段和停用选项。表格按单元格比较,布局和 class 不参与。
|
||
async function snapshot(scope) {
|
||
return scope.evaluate(root => {
|
||
const clean = text => (text || '').replace(/\s+/g, ' ').trim();
|
||
// 新壳把弹窗容器放进 main,旧壳把它们放在 body。只对照正在检查的页面或已单独打开的表单。
|
||
const businessBody = root.matches('main') ? root.querySelector('#main') : null;
|
||
const inactivePage = businessBody?.closest('[hidden]');
|
||
const body = businessBody && !inactivePage ? businessBody : root;
|
||
const nodes = selector =>
|
||
[...body.querySelectorAll(selector)].filter(
|
||
el => !inactivePage?.contains(el) && (!root.matches('main') || !el.closest('dialog, [role="dialog"]')),
|
||
);
|
||
return {
|
||
fields: Array.from(nodes('input, select, textarea'), field => ({
|
||
name: field.name || field.id || '',
|
||
labels: Array.from(field.labels || [], label => {
|
||
const copy = label.cloneNode(true);
|
||
copy.querySelectorAll('input, select, textarea, button').forEach(el => el.remove());
|
||
return clean(copy.textContent);
|
||
}),
|
||
type: field.type,
|
||
value: field.value,
|
||
required: field.required,
|
||
disabled: field.matches(':disabled'),
|
||
readOnly: Boolean(field.readOnly),
|
||
hidden: field.type === 'hidden' || Boolean(field.closest('[hidden]')),
|
||
...(field.type === 'checkbox' || field.type === 'radio' ? { checked: field.checked } : {}),
|
||
constraints: Object.fromEntries(
|
||
[
|
||
'min',
|
||
'max',
|
||
'step',
|
||
'minlength',
|
||
'maxlength',
|
||
'pattern',
|
||
'inputmode',
|
||
'autocomplete',
|
||
'multiple',
|
||
'placeholder',
|
||
]
|
||
.filter(key => field.hasAttribute(key))
|
||
.map(key => [key, field.getAttribute(key)]),
|
||
),
|
||
...(field.options
|
||
? { options: Array.from(field.options, opt => [opt.value, clean(opt.textContent), opt.disabled]) }
|
||
: {}),
|
||
})),
|
||
actions: Array.from(nodes('button, summary, a[href]'), node => ({
|
||
label: clean(node.getAttribute('aria-label') || node.textContent),
|
||
disabled: node.matches(':disabled'),
|
||
})).sort((a, b) => a.label.localeCompare(b.label, 'zh-CN')),
|
||
tables: Array.from(nodes('table'), table =>
|
||
Array.from(table.rows, row => Array.from(row.cells, cell => clean(cell.textContent))),
|
||
),
|
||
};
|
||
});
|
||
}
|
||
|
||
function rolePages(role) {
|
||
return Object.keys(pageTitles).filter(key =>
|
||
role === 'owner' ? key !== 'people-entry' : !['team-funds', 'private-operations'].includes(key),
|
||
);
|
||
}
|
||
|
||
async function navigate(page, version, key, role) {
|
||
const tab = version === 'old' ? '[data-tab="' + key + '"]' : 'a[href="/next/' + key + '"]';
|
||
if (version === 'new' && page.viewportSize().width <= 390) {
|
||
await page.getByRole('button', { name: '打开导航', exact: true }).click();
|
||
}
|
||
await page.locator('nav:visible').locator(tab).first().click();
|
||
const title = key === 'settings' && role === 'assistant' ? '修改密码' : pageTitles[key];
|
||
await page.getByRole('heading', { name: title, exact: true, level: 1 }).waitFor();
|
||
if (version === 'new') assert.equal(new URL(page.url()).pathname, '/next/' + key);
|
||
await settle(page);
|
||
}
|
||
|
||
async function mutate(page, endpoint, click) {
|
||
const [res] = await Promise.all([
|
||
page.waitForResponse(r => {
|
||
const url = new URL(r.url()).pathname;
|
||
return r.request().method() === 'POST' && (typeof endpoint === 'string' ? url === endpoint : endpoint.test(url));
|
||
}),
|
||
click(),
|
||
]);
|
||
assert.equal(res.status(), 200, endpoint + ' ' + (await res.text()));
|
||
assert.ok(res.request().headers()['idempotency-key'], endpoint + ' 缺少操作号');
|
||
assert.ok(res.request().headers()['x-ledger-user'], endpoint + ' 缺少操作者');
|
||
await settle(page);
|
||
}
|
||
|
||
async function exercise(page, version, role, states, mobileWidths) {
|
||
const main = page.getByRole('main').last();
|
||
const action = key => page.locator('[data-action="' + key + '"]:visible').first();
|
||
const tab = key => navigate(page, version, key, role);
|
||
const capture = async (label, scope = main) => {
|
||
await settle(page);
|
||
states[role + '/' + label] = await snapshot(scope);
|
||
};
|
||
for (const key of rolePages(role)) {
|
||
await tab(key);
|
||
await capture(key);
|
||
}
|
||
// 验证导航中没有另一个角色的专用入口。
|
||
for (const key of Object.keys(pageTitles).filter(key => !rolePages(role).includes(key))) {
|
||
const selector = version === 'old' ? '[data-tab="' + key + '"]' : 'a[href="/next/' + key + '"]';
|
||
assert.equal(
|
||
await page
|
||
.locator('nav')
|
||
.locator(selector + ':visible')
|
||
.count(),
|
||
0,
|
||
role + ' 导航暴露 ' + key,
|
||
);
|
||
}
|
||
if (version === 'new') {
|
||
await page.reload();
|
||
await page
|
||
.getByRole('heading', { name: role === 'owner' ? pageTitles.settings : '修改密码', level: 1, exact: true })
|
||
.waitFor();
|
||
await settle(page);
|
||
assert.deepEqual(await snapshot(main), states[role + '/settings'], '刷新后设置页变化');
|
||
if (role === 'assistant') {
|
||
for (const key of ['team-funds', 'private-operations']) {
|
||
await page.goto(new URL('/next/' + key, page.url()).href);
|
||
await page.getByRole('heading', { name: '每日对账', exact: true, level: 1 }).waitFor();
|
||
assert.equal(new URL(page.url()).pathname, '/next/report');
|
||
}
|
||
}
|
||
}
|
||
await page.setViewportSize({ width: 390, height: 844 });
|
||
for (const key of rolePages(role)) {
|
||
await tab(key);
|
||
const label = role + '/mobile/' + key;
|
||
states[label] = await snapshot(main);
|
||
mobileWidths[label] = await page.evaluate(() => document.documentElement.scrollWidth);
|
||
}
|
||
await page.setViewportSize({ width: 1400, height: 1000 });
|
||
if (role === 'owner') {
|
||
await tab('material-pools');
|
||
const purchase = page.locator('#material-purchase-form');
|
||
await purchase.locator('[name=grams]').fill('5');
|
||
await purchase.locator('[name=total]').fill('4600');
|
||
await purchase.locator('[name=note]').fill('对照购料');
|
||
await mutate(page, '/api/material-purchases', () =>
|
||
purchase
|
||
.getByRole('button', { name: /保存|登记|确认/ })
|
||
.last()
|
||
.click(),
|
||
);
|
||
await main.getByText('对照购料', { exact: true }).first().waitFor();
|
||
await capture('material-pools/saved');
|
||
|
||
await tab('price-locks');
|
||
await action('new-price-lock').click();
|
||
const lock = page.locator('#price-lock-create-form');
|
||
await lock.waitFor();
|
||
await capture('price-locks/create', lock);
|
||
await lock.locator('[name=customer]').fill('对照锁价');
|
||
for (const [name, value] of Object.entries({
|
||
quantity: '2',
|
||
goldPrice: '900',
|
||
laborRate: '10',
|
||
material_rate: '850',
|
||
received_amount: '1000',
|
||
}))
|
||
await lock
|
||
.locator('[name="' + name + '"]')
|
||
.first()
|
||
.fill(value);
|
||
for (const check of await lock.locator('input[type=checkbox][name*=verified]:visible').all()) await check.check();
|
||
await mutate(page, '/api/price-locks', () => lock.locator('button[type=submit]').click());
|
||
await action('close-price-lock').click();
|
||
await tab('price-locks');
|
||
await main.getByText('对照锁价', { exact: false }).first().waitFor();
|
||
await capture('price-locks/saved');
|
||
await action('open-price-lock').click();
|
||
await capture('price-locks/detail', page.locator('dialog[open]'));
|
||
await action('close-price-lock').click();
|
||
await action('deliver-price-lock').click();
|
||
const delivery = page.locator('#price-lock-delivery-form');
|
||
await capture('price-locks/delivery', delivery);
|
||
if (version === 'new') {
|
||
const deliverId = new URL(page.url()).searchParams.get('deliver');
|
||
assert.ok(deliverId, '锁价交付地址缺少本单标识');
|
||
await page.reload();
|
||
await delivery.waitFor();
|
||
await settle(page);
|
||
assert.deepEqual(await snapshot(delivery), states[role + '/price-locks/delivery'], '刷新后锁价交付表单变化');
|
||
}
|
||
await action('refresh-price-locks').click();
|
||
|
||
await tab('recoveries');
|
||
await page.getByRole('button', { name: '置换', exact: true }).click();
|
||
await capture('recoveries/exchange');
|
||
await action('customer-material-new').click();
|
||
const deposit = page.locator('#customer-material-form');
|
||
await capture('recoveries/deposit', deposit);
|
||
await deposit.locator('[name=grams]').fill('3.123');
|
||
await deposit.locator('[name=memo]').fill('对照寄存');
|
||
await deposit.locator('[name=verified]').check();
|
||
await mutate(page, '/api/customer-materials', () => deposit.locator('[type=submit]').click());
|
||
await main.getByText('对照寄存', { exact: true }).first().waitFor();
|
||
await capture('recoveries/deposit-saved');
|
||
|
||
await tab('stock');
|
||
await action('pocket-manager-toggle').click();
|
||
await action('pocket-manager-add').click();
|
||
const pocketDialog = page.locator('#pocket-editor-dialog[open]');
|
||
await capture('stock/new-pocket', pocketDialog);
|
||
await action('pocket-manager-close').click();
|
||
const stock = page.locator('#stock-form');
|
||
await stock.locator('[name=kind]').selectOption('transfer');
|
||
await stock.locator('[name=grams]').fill('0.125');
|
||
await stock.locator('[name=note]').fill('对照平移');
|
||
await mutate(page, '/api/stock', () => stock.getByRole('button').last().click());
|
||
await capture('stock/transferred');
|
||
|
||
await tab('team-funds');
|
||
const month = main.locator('[name=month]');
|
||
await month.fill('2026-10');
|
||
const [profit] = await Promise.all([
|
||
page.waitForResponse(
|
||
r =>
|
||
new URL(r.url()).pathname === '/api/team-profits' && new URL(r.url()).searchParams.get('month') === '2026-10',
|
||
),
|
||
main.getByRole('button', { name: '查询', exact: true }).click(),
|
||
]);
|
||
assert.equal(profit.status(), 200);
|
||
await capture('team-funds/previous-month');
|
||
|
||
await tab('settings');
|
||
const settings = page.locator('#shop-settings-form');
|
||
const name = settings.locator('input[name=storeName]');
|
||
await name.fill('对照迁移珠宝');
|
||
// 清除临时试改数据前,两个入口都应允许取消离开设置。
|
||
await Promise.all([
|
||
page.waitForEvent('dialog', { predicate: d => ['confirm', 'beforeunload'].includes(d.type()) }),
|
||
page.locator('nav:visible [data-tab=stock]').first().click(),
|
||
]);
|
||
assert.equal(await name.inputValue(), '对照迁移珠宝');
|
||
await mutate(page, '/api/shop-settings', () =>
|
||
settings.locator('button[type=submit],button.primary').first().click(),
|
||
);
|
||
await page.getByText('店铺配置已保存', { exact: true }).waitFor();
|
||
const brand = version === 'old' ? page.locator('header [data-shop-name]') : page.getByTestId('store-name');
|
||
assert.equal(await brand.innerText(), '对照迁移珠宝', '保存后外壳没有更新店铺名称');
|
||
await capture('settings/saved');
|
||
}
|
||
await tab('orders');
|
||
await page.locator('[data-action=open-order]', { hasText: '页面对照客户' }).first().click();
|
||
const order = page.locator('#order-dialog[open]');
|
||
await order.locator('.order-detail-identifiers').waitFor();
|
||
await capture('orders/detail', order);
|
||
await action('order-after-sale-open').click();
|
||
await capture('orders/after-sale', page.locator('#order-after-sale-form'));
|
||
await action('close-dialog').click();
|
||
|
||
if (role === 'assistant') {
|
||
await main.locator('[data-action=order-period][data-period=yesterday]').click();
|
||
await page.locator('[data-action=open-order]:visible', { hasText: '昨日对照原单' }).first().click();
|
||
await action('edit-order').click();
|
||
const edit = page.locator('#order-form[data-order-edit=true]');
|
||
await capture('orders/change-form', edit);
|
||
await edit.locator('[name=customer]').fill('昨日对照更正');
|
||
await edit.locator('[name=edit_reason]').fill('核对客户称呼');
|
||
await edit.locator('[name=edit_verified]').check();
|
||
await mutate(page, /^\/api\/orders\/[^/]+\/change$/, () => edit.locator('button[type=submit]').click());
|
||
await capture('orders/requested', order);
|
||
await action('close-dialog').click();
|
||
} else {
|
||
await main.locator('details.order-review-menu > summary').click();
|
||
await action('open-order-changes').click();
|
||
await page.getByRole('button', { name: '查看并复核' }).first().click();
|
||
await page.getByRole('button', { name: '查看变更并复核' }).first().click();
|
||
const form = page.locator('#order-change-form');
|
||
await capture('orders/review', form);
|
||
await form.locator('[name=note]').fill('已核实原始记录');
|
||
await form.locator('[name=verified]').check();
|
||
await mutate(page, /^\/api\/order-changes\/[^/]+\/approve$/, () => form.locator('button[type=submit]').click());
|
||
await order.getByRole('heading', { name: '昨日对照更正' }).waitFor();
|
||
await capture('orders/approved', order);
|
||
await action('close-dialog').click();
|
||
}
|
||
|
||
await tab('report');
|
||
await main.locator('#report-month').check();
|
||
await capture('report/month');
|
||
|
||
await tab(role === 'owner' ? 'private-operations' : 'people-entry');
|
||
await main.getByRole('button', { name: '记录人数', exact: true }).first().click();
|
||
const people = page.locator('#private-people-form');
|
||
await people.locator('[name=total_count]').waitFor();
|
||
await capture('people/dialog', people);
|
||
await people.locator('[name=total_count]').fill(role === 'owner' ? '123' : '127');
|
||
await mutate(page, '/api/private-operations/people', () => people.getByRole('button', { name: '保存人数' }).click());
|
||
await people.waitFor({ state: 'hidden' });
|
||
await capture('people/saved');
|
||
if (role !== 'owner') return;
|
||
await tab('orders');
|
||
await main.locator('[data-action=order-period][data-period=today]').click();
|
||
await action('new-after-sale').click();
|
||
const separate = page.locator('#after-sale-form');
|
||
await capture('orders/new-separate-after-sale', separate);
|
||
await separate.locator('[name=project]').fill('补寄运费');
|
||
await separate.locator('[name=customer]').fill('独立售后对照');
|
||
await separate.locator('[name=amount]').fill('8.50');
|
||
await separate.locator('[name=payer]').selectOption('assistant');
|
||
await mutate(page, '/api/after-sales', () => separate.locator('[type=submit]').click());
|
||
await main.locator('[data-action=after-sale-edit]').first().click();
|
||
const savedSale = page.locator('#after-sale-edit-form');
|
||
await savedSale.waitFor();
|
||
await capture('orders/edit-separate-after-sale', savedSale);
|
||
await savedSale.locator('[name=amount]').fill('9.10');
|
||
await mutate(page, /^\/api\/after-sales\/[^/]+\/update$/, () => savedSale.locator('[type=submit]').click());
|
||
await page.locator('[data-action=open-order]:visible', { hasText: '页面对照客户' }).first().click();
|
||
await action('order-after-sale-open').click();
|
||
const after = page.locator('#order-after-sale-form');
|
||
await after.locator('[name=reason]').fill('对照实际售后退货');
|
||
await after.locator('[name=refund_amount]').fill('990.00');
|
||
await after.locator('[name=deduction_reason]').fill('约定扣除寄件费');
|
||
await action('order-after-sale-add-expense').click();
|
||
await after.locator('[name=expense_note]').fill('退件邮费');
|
||
await after.locator('[name=expense_amount]').fill('6.00');
|
||
const [preview] = await Promise.all([
|
||
page.waitForResponse(
|
||
r => r.request().method() === 'POST' && new URL(r.url()).pathname.endsWith('/after-sale-preview'),
|
||
),
|
||
action('order-after-sale-preview').click(),
|
||
]);
|
||
assert.equal(preview.status(), 200, await preview.text());
|
||
assert.ok(preview.request().headers()['x-ledger-user']);
|
||
assert.equal(preview.request().headers()['idempotency-key'], undefined, '预览只试算,不创建记账操作');
|
||
await capture('orders/after-sale-preview', after);
|
||
await after.locator('[name=verified]').check();
|
||
await mutate(page, /^\/api\/orders\/[^/]+\/return$/, () => after.locator('[type=submit]').click());
|
||
await capture('orders/after-sale-saved', order);
|
||
}
|
||
|
||
async function run(browser, version, launchServer = startServer) {
|
||
const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'ledger-page-parity-'));
|
||
const server = launchServer({ dataDir, clockStart: TIME, seed: 'page-parity' });
|
||
const states = {},
|
||
mobileWidths = {},
|
||
posts = [],
|
||
errors = [];
|
||
try {
|
||
const { base } = await server.ready();
|
||
const cookies = await seed(server, base);
|
||
for (const role of roles) {
|
||
const context = await browser.newContext({
|
||
viewport: { width: 1400, height: 1000 },
|
||
locale: 'zh-CN',
|
||
timezoneId: 'Asia/Shanghai',
|
||
});
|
||
try {
|
||
await context.addCookies([{ name: 'mm_session', value: cookies[role].slice('mm_session='.length), url: base }]);
|
||
const page = await context.newPage();
|
||
observeRequests(page);
|
||
page.setDefaultTimeout(9000);
|
||
await page.clock.setFixedTime(new Date(TIME));
|
||
page.on('pageerror', err => errors.push(err.message));
|
||
page.on('dialog', dialog => {
|
||
if (dialog.type() === 'beforeunload' || dialog.message().includes('尚未保存')) return dialog.dismiss();
|
||
return dialog.accept();
|
||
});
|
||
page.on('console', msg => {
|
||
if (msg.type() === 'error') errors.push(msg.text());
|
||
});
|
||
page.on('response', response => {
|
||
if (response.status() >= 400) errors.push(response.status() + ' ' + new URL(response.url()).pathname);
|
||
});
|
||
page.on('request', req => {
|
||
const endpoint = new URL(req.url()).pathname;
|
||
if (req.method() === 'POST' && endpoint.startsWith('/api/'))
|
||
posts.push({ role, endpoint, data: req.postDataJSON() });
|
||
});
|
||
await page.goto(base + (version === 'old' ? '/' : '/next/'));
|
||
await exercise(page, version, role, states, mobileWidths);
|
||
console.log(' ✓', version, role, rolePages(role).length + ' 个分区');
|
||
} finally {
|
||
await context.close();
|
||
}
|
||
}
|
||
assert.deepEqual(errors, []);
|
||
const { tables } = dumpDatabase(path.join(dataDir, 'ledger.sqlite'));
|
||
// 会话令牌、浏览器生成的幂等键不逐字比较。每笔写入另外核对实际 URL、操作者、请求体和落库结果。
|
||
delete tables.sessions;
|
||
delete tables.operations;
|
||
const n = new Normalizer();
|
||
return { captures: n.value({ states, posts, tables }), mobileWidths };
|
||
} finally {
|
||
await server.stop();
|
||
fs.rmSync(dataDir, { recursive: true, force: true });
|
||
}
|
||
}
|
||
|
||
const browser = await chromium.launch();
|
||
try {
|
||
const referenceFlag = process.argv.indexOf('--reference-app');
|
||
const referenceApp = referenceFlag < 0 ? process.env.LEDGER_REFERENCE_APP : process.argv[referenceFlag + 1];
|
||
if (referenceFlag >= 0 && !referenceApp) throw new Error('--reference-app 需要旧版新账系统目录');
|
||
const referenceServer = referenceApp
|
||
? createRequire(import.meta.url)(path.resolve(referenceApp, 'e2e/lib/server.js')).startServer
|
||
: startServer;
|
||
const jobs = [run(browser, 'old', referenceServer)];
|
||
if (!process.argv.includes('--legacy-only')) jobs.push(run(browser, 'new'));
|
||
// 两个版本各用独立服务、浏览器上下文和临时数据库。都完成清理后再返回失败。
|
||
const [reference, next] = (await Promise.allSettled(jobs)).map(result => {
|
||
if (result.status === 'rejected') throw result.reason;
|
||
return result.value;
|
||
});
|
||
const snapshots = Object.values(reference.captures.states);
|
||
const fieldCount = snapshots.reduce((sum, page) => sum + page.fields.length, 0);
|
||
const counts =
|
||
snapshots.length +
|
||
' 组页面及交互、' +
|
||
fieldCount +
|
||
' 个控件快照、' +
|
||
reference.captures.posts.length +
|
||
' 次业务 POST、' +
|
||
Object.keys(reference.captures.tables).length +
|
||
' 张数据库表';
|
||
if (!next) console.log('旧版基线通过,' + counts);
|
||
else {
|
||
for (const [label, width] of Object.entries(reference.mobileWidths)) {
|
||
assert.ok(
|
||
next.mobileWidths[label] <= width,
|
||
label + ' 文档宽度由 ' + width + 'px 增至 ' + next.mobileWidths[label] + 'px',
|
||
);
|
||
}
|
||
const result = compare(reference.captures, next.captures);
|
||
const output = path.join(import.meta.dirname, 'out', 'page-parity');
|
||
fs.mkdirSync(output, { recursive: true });
|
||
const summary = {
|
||
referenceApp: path.resolve(referenceApp || path.join(import.meta.dirname, '..')),
|
||
pageStates: snapshots.length,
|
||
formControls: fieldCount,
|
||
businessPosts: reference.captures.posts.length,
|
||
comparedTables: Object.keys(reference.captures.tables).length,
|
||
differences: result.diffs.length,
|
||
scenarios: Object.keys(reference.captures.states),
|
||
};
|
||
fs.writeFileSync(path.join(output, 'result.json'), JSON.stringify(summary, null, 2) + '\n');
|
||
fs.writeFileSync(path.join(output, 'differences.json'), JSON.stringify(result.diffs, null, 2) + '\n');
|
||
assert.equal(result.diffs.length, 0, report('页面、请求与数据库', result));
|
||
console.log('页面对照通过,' + counts);
|
||
}
|
||
} finally {
|
||
await browser.close();
|
||
}
|