Files
weiguang-jewelry-ledger/新账系统/e2e/browser-next.mjs
T

351 lines
17 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/)浏览器检查:演示一键登录、试用空库初始化、密码登录,桌面与手机宽度(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 fillShowcase(page) {
const form = page.locator('#order-form');
const fill = (scope, field, value) =>
scope.locator(`[data-field="${field}"] input, [data-field="${field}"] textarea`).first().fill(value);
const radio = (scope, field, label) =>
scope.locator(`[data-field="${field}"] .ant-radio-button-wrapper`, { hasText: label }).first().click();
await fill(form, 'customer', '林小姐');
await radio(form, 'customer_type', '老客户');
const first = form.locator('[data-line]').first();
await fill(first, 'quantity', '5.28');
await fill(first, 'goldPrice', '958');
await fill(first, 'laborRate', '28');
await first.locator('[data-action="add-charge"]').click();
await choose(page, first.locator('[data-charge]').last(), 'chargeType', '证书');
await fill(first, 'cost-materialRate', '885');
await fill(first, 'cost-labor', '60');
await form.locator('[data-action="add-line"]').click();
const second = form.locator('[data-line]').nth(1);
await choose(page, second, 'nameType', '足金999');
await radio(second, 'pricingMode', '直接填写金额');
await fill(second, 'quantity', '3.2');
await fill(second, 'priceNote', '古法手镯 · 一口价');
await fill(second, 'baseSale', '3380');
await second.locator('[data-action="add-charge"]').click();
await fill(second, 'cost-materialRate', '880');
await fill(second, 'cost-labor', '150');
const presets = form.locator('[data-preset] input[type=checkbox]');
if (await presets.count()) await presets.first().check();
const box = form.locator('[data-preset="box"] input[type=checkbox]');
if (await box.count()) {
await box.check();
await fill(form, 'cost_box_quantity', '2');
}
for (const input of await page.locator('.fee-row [data-field="feeAmount"] input').all())
if (!(await input.inputValue())) await input.fill('20');
await fill(form, 'discount', '18');
await fill(form, 'note', '手镯内圈刻字「安」');
await fill(form, 'internal_note', '#老客户 周末到店自取');
await page.locator('body').click({ position: { x: 2, y: 2 } });
await page.waitForTimeout(300);
}
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 });
await page.evaluate(() => Object.defineProperty(navigator, 'clipboard', { value: undefined }));
await page.getByRole('button', { name: '复制纸单号' }).click();
await page.getByText('请手动选择纸单号复制', { exact: true }).waitFor();
if (await page.getByText(/^已复制纸单号 /).count()) fail('剪贴板不可用时仍提示复制成功');
else ok('剪贴板不可用时提示手动复制');
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 page.waitForSelector('.login-form');
await page.waitForTimeout(300);
await page.screenshot({ path: path.join(COMPARE, `login-${name}-new.png`), fullPage: true });
{
// 旧界面登录页(尚未登录,同一宽度)
const oldLogin = await ctx.newPage();
await oldLogin.goto(base + '/');
await oldLogin.waitForSelector('#login-form');
await oldLogin.waitForTimeout(300);
await oldLogin.screenshot({ path: path.join(COMPARE, `login-${name}-old.png`), fullPage: true });
await oldLogin.close();
}
await loginNext(page, '麦麦');
await page.waitForTimeout(400);
await page.screenshot({ path: path.join(COMPARE, `create-${name}-new.png`), fullPage: true });
await page.screenshot({ path: path.join(COMPARE, `create-${name}-new-viewport.png`) });
if (!mobile) {
await fillShowcase(page);
await page.locator('#order-form [data-line]').nth(1).scrollIntoViewIfNeeded();
await page.evaluate(() => window.scrollBy(0, 180));
await page.waitForTimeout(300);
await page.screenshot({ path: path.join(COMPARE, `create-${name}-new-filled.png`) });
await page.screenshot({ path: path.join(COMPARE, `create-${name}-new-filled-full.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 page.locator('[data-action="new-order"]').click();
await page.waitForSelector('#order-form');
await fillShowcase(page);
await overflow(page, '新版开单页(两行示例单)');
// 等上一张单的成功提示消失,避免遮挡截图。
await page.locator('.ant-message-notice').first().waitFor({ state: 'detached', timeout: 8000 }).catch(() => {});
await page.locator('#order-form [data-line]').nth(1).scrollIntoViewIfNeeded();
await page.waitForTimeout(300);
await page.screenshot({ path: path.join(COMPARE, `create-${name}-new-filled.png`) });
await page.screenshot({ path: path.join(COMPARE, `create-${name}-new-filled-full.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 old.screenshot({ path: path.join(COMPARE, `create-${name}-old-viewport.png`) });
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;