合入主线登录和营业时段策略,对齐旧界面与 React 访问流程

This commit is contained in:
黄健铭 committed 2026-12-05 21:46:55 -08:00
commit 42395de23a
113 files changed
+1915 -558

No files matched your search

+173
View File
@@ -0,0 +1,173 @@
'use strict';
const test = require('node:test'),
assert = require('node:assert/strict');
const { Ledger } = require('../core/ledger'),
{ createApp, createUser } = require('../server');
const { accessWindow } = require('../domains/team/business-hours');
const at = time => Date.parse('2026-12-04T' + time + ':00+08:00');
function saleInput(date, member) {
return {
date,
customer: '测试营业时段',
internal_note: '合成测试备注',
salesperson: '测试经手人',
payment_account: member === 'owner' ? '麦麦微信' : '助理微信',
rounding_mode: 'cent',
discount: '0',
lines: [{ name: '测试商品', unit: '件', quantity: '1', pocket: '', payer: member, cost: '40', sale: '100' }],
fee_items: [],
};
}
test('北京时间开门当分可用,关门当分停止,包括跨午夜营业', () => {
const hours = { open: '22:00', close: '02:00' };
assert.equal(accessWindow(hours, at('00:01')).closesAt, at('02:00'));
assert.equal(accessWindow(hours, at('02:00')).state, 'closed');
assert.equal(accessWindow(hours, at('21:59')).state, 'closed');
assert.equal(accessWindow(hours, at('22:00')).closesAt, at('02:00') + 86400000);
});
test('营业时间只限制员工:超级管理员在未设置和闭店期间均可登录、开单、打印和管理账本', async t => {
const ledger = new Ledger(':memory:'),
password = 'synthetic-hours-only';
for (const member of ['owner', 'assistant']) createUser(ledger, member, member, password, member);
let now = at('09:00');
const app = createApp({ mode: 'trial', ledger, hoursPolicy: true, hoursClock: () => now, feishuConfig: {} });
await new Promise(resolve => app.server.listen(0, '127.0.0.1', resolve));
t.after(async () => {
await new Promise(resolve => app.server.close(resolve));
ledger.close();
});
const base = 'http://127.0.0.1:' + app.server.address().port;
const call = (route, cookie, data) =>
fetch(base + route, {
method: data ? 'POST' : 'GET',
headers: {
...(cookie && { Cookie: cookie }),
...(data && {
Origin: base,
'Idempotency-Key': require('node:crypto').randomUUID(),
'Content-Type': 'application/json',
'X-Requested-With': 'maimai-ledger',
}),
},
body: data && JSON.stringify(data),
});
const sign = member => call('/api/login', null, { member, password });
const token = res => res.headers.get('set-cookie').split(';')[0];
assert.doesNotMatch(await (await call('/')).text(), /<option value="assistant">/);
assert.equal((await sign('assistant')).status, 403);
const owner = token(await sign('owner'));
const ownerPage = await (await call('/', owner)).text();
assert.match(ownerPage, /src="\/app.js"/);
assert.doesNotMatch(ownerPage, /business-hours-lock\.js/);
assert.equal((await call('/api/state', owner)).status, 200);
const setting = { revision: 0, businessHours: { open: '09:00', close: '18:00' } };
assert.notEqual((await call('/api/shop-settings', null, setting)).status, 200);
assert.equal((await call('/api/shop-settings', owner, setting)).status, 200);
const staff = token(await sign('assistant'));
assert.equal((await call('/api/state', staff)).status, 200);
for (const path of ['/next/', '/next/create', '/next/index.html']) {
const employeeHtml = await (await call(path, staff)).text();
assert.match(employeeHtml, /src="\/next\/assets\//);
assert.match(employeeHtml, /src="\/business-hours-lock\.js" data-remaining="32400000"/);
assert.doesNotMatch(await (await call(path, owner)).text(), /business-hours-lock\.js/);
}
assert.match(await (await call('/', staff)).text(), /business-hours-lock\.js/);
assert.equal((await (await call('/api/access-window', staff)).json()).window.closesAt, at('18:00'));
assert.doesNotMatch(await (await call('/', owner)).text(), /business-hours-lock\.js/);
now = at('18:00');
for (const route of ['/api/session', '/api/state', '/print/example', '/api/access-window']) {
assert.equal((await call(route, staff)).status, 403);
}
assert.equal((await call('/api/shop-settings', staff, { revision: 1, businessHours: null })).status, 403);
assert.equal((await sign('assistant')).status, 403);
assert.equal((await call('/api/login', owner, { member: 'assistant', password })).status, 403);
assert.equal((await call('/api/login', null, { member: 'owner', password: 'wrong' })).status, 401);
for (const cookie of [null, staff]) {
const page = await call('/', cookie);
assert.equal(page.status, 200);
const html = await page.text();
assert.match(html, /非营业时间/);
assert.match(html, /<option value="owner">/);
assert.doesNotMatch(html, /<option value="assistant">|src="\/app.js"/);
}
assert.equal((await call('/api/state')).status, 403);
for (const cookie of [null, staff]) {
const page = await call('/next/create', cookie);
assert.equal(page.status, 200);
const source = await page.text();
assert.match(source, /data-standalone-login/);
assert.match(source, /<option value="owner">/);
assert.doesNotMatch(source, /src="\/next\/assets\//);
}
const lateOwner = token(await sign('owner'));
for (const cookie of [owner, lateOwner]) {
assert.equal((await call('/api/state', cookie)).status, 200);
assert.equal((await (await call('/api/access-window', cookie)).json()).window, null);
}
const { today } = await (await call('/api/session', lateOwner)).json();
const sale = await call('/api/orders/issue', lateOwner, saleInput(today, 'owner'));
assert.equal(sale.status, 200, await sale.clone().text());
const { id } = await sale.json();
const printed = await call('/print/' + id, owner);
assert.equal(printed.status, 200);
assert.doesNotMatch(await printed.text(), /business-hours-lock\.js/);
assert.equal((await call('/print/' + id, staff)).status, 403);
assert.equal((await call('/api/shop-settings', lateOwner, { revision: 1, businessHours: null })).status, 200);
assert.equal((await call('/api/state', staff)).status, 403);
assert.equal((await call('/api/state', lateOwner)).status, 200);
});
test('开门时到达、关门后才读完的员工写入被拒绝,已有账本和操作号记录不变', async t => {
const http = require('node:http');
const ledger = new Ledger(':memory:'),
password = 'synthetic-hours-only';
for (const member of ['owner', 'assistant']) createUser(ledger, member, member, password, member);
let now = at('17:59');
const app = createApp({ mode: 'trial', ledger, hoursPolicy: true, hoursClock: () => now, feishuConfig: {} });
await new Promise(resolve => app.server.listen(0, '127.0.0.1', resolve));
t.after(async () => {
await new Promise(resolve => app.server.close(resolve));
ledger.close();
});
const base = 'http://127.0.0.1:' + app.server.address().port;
const headers = { Origin: base, 'X-Requested-With': 'maimai-ledger', 'Content-Type': 'application/json' };
const post = (url, data, cookie) =>
fetch(base + url, {
method: 'POST',
headers: { ...headers, ...(cookie && { Cookie: cookie }) },
body: JSON.stringify(data),
});
const owner = (await post('/api/login', { member: 'owner', password })).headers.get('set-cookie').split(';')[0];
assert.equal(
(await post('/api/business-hours/setup', { revision: 0, businessHours: { open: '09:00', close: '18:00' } }, owner))
.status,
200,
);
const staff = (await post('/api/login', { member: 'assistant', password })).headers.get('set-cookie').split(';')[0];
const { today } = await (await fetch(base + '/api/session', { headers: { Cookie: staff } })).json();
const payload = JSON.stringify(saleInput(today, 'assistant'));
const before = ledger.rows('SELECT * FROM operations');
const started = new Promise(resolve => app.server.prependOnceListener('request', req => req.once('data', resolve)));
const { promise: response, resolve, reject } = Promise.withResolvers();
const req = http.request(
base + '/api/orders/issue',
{ method: 'POST', headers: { ...headers, Cookie: staff, 'Idempotency-Key': require('node:crypto').randomUUID() } },
res => {
let body = '';
res.setEncoding('utf8');
res.on('data', part => (body += part));
res.on('end', () => resolve([res.statusCode, JSON.parse(body)]));
},
);
req.on('error', reject);
req.write(payload.slice(0, -1));
await started;
now = at('18:00');
req.end(payload.slice(-1));
const [status, error] = await response;
assert.equal(status, 403);
assert.equal(error.code, 'BUSINESS_HOURS');
assert.deepEqual(ledger.rows('SELECT * FROM operations'), before);
assert.equal(ledger.one('SELECT count(*) AS n FROM orders').n, 0);
});
@@ -0,0 +1,43 @@
'use strict';
const assert = require('node:assert/strict');
const test = require('node:test');
const { compare } = require('../e2e/lib/diff');
const { expectedTranscript, expectedTables } = require('../e2e/lib/main-business-hours');
test('营业时间的黄金期望仍拒绝缺失、错误时段、员工可见和原金额变化', () => {
const config = { version: 1, revision: 3, storeName: '测试', profitShareHistory: [], feeDefaults: { shipping: '6' } };
const staff = { storeName: '测试' };
const original = [
{ actor: 'owner', method: 'GET', path: '/api/state', status: 200, body: { shopSettings: config } },
{ actor: 'assistant', method: 'GET', path: '/api/shop-settings', status: 200, body: staff },
];
const expected = expectedTranscript(original);
assert.deepEqual(expected[1], original[1]);
assert.equal(Object.hasOwn(config, 'businessHours'), false);
assert.equal(expected[0].body.shopSettings.businessHours, null);
const changes = [
rows => delete rows[0].body.shopSettings.businessHours,
rows => (rows[0].body.shopSettings.businessHours = { open: '09:00', close: '18:00' }),
rows => (rows[1].body.businessHours = null),
rows => (rows[0].body.shopSettings.feeDefaults.shipping = '6.01'),
];
for (const change of changes) {
const candidate = structuredClone(expected);
change(candidate);
assert.equal(compare(expected, candidate).diffs.length, 1);
}
const audit = { before: config, after: { ...config, revision: 4 }, note: '原值' };
const result = { ok: true, shopSettings: config, printing: { rows: 8 } };
const tables = {
audit: [{ entity: 'shop-settings', action: '更新店铺配置', detail: JSON.stringify(audit) }],
meta: [{ key: 'shop-settings-v1', value: JSON.stringify(config) }],
operations: [{ id: 'old-op', hash: 'frozen', result }],
};
const expectedDb = expectedTables(tables);
assert.deepEqual(JSON.parse(expectedDb.audit[0].detail).after, { ...audit.after, businessHours: null });
assert.deepEqual(JSON.parse(expectedDb.meta[0].value), { ...config, businessHours: null });
assert.deepEqual(expectedDb.operations[0].result, { ...result, shopSettings: { ...config, businessHours: null } });
assert.equal(tables.operations[0].result.shopSettings.businessHours, undefined);
});
+9 -1
View File
@@ -663,5 +663,13 @@ test('新纯helper资源可由隔离服务器提供,浏览器和Node构造一
JSON.stringify(context.OrderCopy.fromOrder(original, { today: NEXT, newId: factory() })),
JSON.stringify(Copy.fromOrder(original, { today: NEXT, newId: factory() })),
);
assert.ok((await (await fetch(base + '/')).text()).includes('src="/order-copy.js"'));
const signedIn = await fetch(base + '/api/demo-login', {
method: 'POST',
headers: { Origin: base, 'X-Requested-With': 'maimai-ledger', 'Content-Type': 'application/json' },
body: JSON.stringify({ member: 'owner' }),
});
assert.equal(signedIn.status, 200);
const cookie = signedIn.headers.get('set-cookie').split(';')[0];
const shell = await fetch(base + '/', { headers: { Cookie: cookie } });
assert.ok((await shell.text()).includes('src="/order-copy.js"'));
});
+39
View File
@@ -72,6 +72,8 @@ function harness(
});
const run = code => vm.runInContext(code, context),
json = code => JSON.parse(JSON.stringify(run(code)));
for (const file of ['login-diagnostics.js', 'login-ui.js'])
run(fs.readFileSync(path.join(__dirname, '../public', file), 'utf8'));
run(source);
run(
`session={user:__user};state={user:__user,today:'${D}'};applyAfterSaleRestrictions=function(){};updateOrderDetailNavigation=function(){};toast=function(){};showSavedPeopleCount=async function(date){globalThis.__finished=date;};`,
@@ -516,3 +518,40 @@ test('二进制Excel读取沿用账号校验与有限GET重试,HTML成功页
);
assert.equal(denied.calls.length, 1);
});
test('登录诊断区分传输中断、超时、服务端拒绝和读取响应失败,隐藏提交内容', async () => {
const cases = [
{
fetcher: () => {
throw new TypeError('Load failed');
},
text: ['提交登录失败', 'HTTP 状态:未收到', '浏览器提示:Load failed'],
},
{
fetcher: (_url, { signal }) =>
new Promise((_, reject) => signal.addEventListener('abort', () => reject(new Error('fetch is aborted')))),
timeout: true,
text: ['等待超过 25 秒', 'HTTP 状态:未收到'],
},
{ fetcher: () => httpError(401, '账号或密码不正确'), text: ['账号或密码不正确', 'HTTP 状态:401'] },
{ fetcher: () => new Response('private-response-content'), text: ['未能读取完整', 'HTTP 状态:200'] },
];
for (const c of cases) {
const h = harness(c.fetcher, { timeout: c.timeout });
const html = await h.run("api('/api/login',{password:'secret-input'}).catch(err=>loginErrorHTML(err,'提交登录'))");
for (const text of [...c.text, '北京时间', 'POST /api/login', '复制诊断信息']) assert.ok(html.includes(text), text);
assert.doesNotMatch(html, /secret-input|private-response-content/);
assert.equal(h.calls.length, 1);
}
for (const [route, stage] of [
['/api/session', '检查登录状态'],
['/api/state', '读取账本'],
]) {
const h = harness(() => {
throw new TypeError('Load failed');
});
const html = await h.run(`api('${route}').catch(err=>loginErrorHTML(err,'打开账本页面'))`);
assert.ok(html.includes(stage + '失败'));
assert.ok(html.includes('GET ' + route));
}
});
+2 -1
View File
@@ -71,6 +71,7 @@ test('路由匹配器:重叠路径按声明顺序与参数约束区分', () =>
// 由 git show 2b9cb82:新账系统/server.js 中全部 owner(actor) 调用整理:[方法, 示例地址]。
const OWNER_ONLY = [
['POST', '/api/shop-settings'],
['POST', '/api/business-hours/setup'],
['POST', '/api/printing'],
['GET', '/api/employees'],
['POST', '/api/employees'],
@@ -130,7 +131,7 @@ test('路由声明字段合法', () => {
const name = route.method + ' ' + route.path;
assert.ok(['GET', 'POST'].includes(route.method), name);
assert.equal(typeof route.handler, 'function', name);
assert.ok([undefined, 'public', 'user'].includes(route.auth), name);
assert.ok([undefined, 'public', 'user', 'session'].includes(route.auth), name);
assert.ok([undefined, 'owner'].includes(route.role), name);
if (route.write) assert.equal(route.method, 'POST', name);
if (route.direct) assert.ok(!route.write, name);
@@ -0,0 +1,56 @@
'use strict';
const test = require('node:test');
const assert = require('node:assert/strict');
const { Ledger } = require('../core/ledger');
const { createApp, createUser } = require('../server');
test('店内账号均可登录;离店后重新检查账号,包括已有会话', async t => {
const ledger = new Ledger(':memory:');
const password = 'synthetic-network-check';
createUser(ledger, '店主', 'owner', password, 'owner');
createUser(ledger, '员工', 'assistant', password, 'assistant');
const app = createApp({ ledger, shopAccessPolicy: true, mode: 'trial', feishuConfig: {} });
await new Promise(resolve => app.server.listen(0, '127.0.0.1', resolve));
t.after(async () => {
await new Promise(resolve => app.server.close(resolve));
ledger.close();
});
const base = 'http://127.0.0.1:' + app.server.address().port;
const call = (url, zone, cookie, data) =>
fetch(base + url, {
method: data ? 'POST' : 'GET',
headers: {
...(zone && { 'X-Ledger-Access-Zone': zone }),
...(cookie && { Cookie: cookie }),
...(data && { Origin: base, 'Content-Type': 'application/json', 'X-Requested-With': 'maimai-ledger' }),
},
body: data ? JSON.stringify(data) : undefined,
});
const login = (zone, member) => call('/api/login', zone, null, { member, password });
assert.equal((await call('/api/session')).status, 403);
assert.deepEqual(
(await (await call('/api/session', 'owner')).json()).loginOptions.map(x => x.member),
['owner'],
);
const page = await call('/', 'store');
const html = await page.text();
assert.equal(page.status, 200);
assert.match(html, /<select name="member"/);
assert.match(html, /<option value="assistant">/);
assert.doesNotMatch(html, /<script[^>]+src=|<link[^>]+stylesheet|src="\/app.js"/);
const script = html.match(/<script>([\s\S]+?)<\/script>/)[1];
const hash = require('node:crypto').createHash('sha256').update(script).digest('base64');
assert.ok(page.headers.get('content-security-policy').includes("script-src 'sha256-" + hash + "'"));
assert.doesNotMatch(await (await call('/', 'owner')).text(), /<option value="assistant">/);
const staff = await login('store', 'assistant');
assert.equal(staff.status, 200);
const cookie = staff.headers.get('set-cookie').split(';')[0];
assert.match(await (await call('/', 'store', cookie)).text(), /src="\/app.js"/);
for (const route of ['/', '/api/session', '/api/state', '/print/missing'])
assert.equal((await call(route, 'owner', cookie)).status, 403);
assert.equal((await call('/api/stock', 'owner', cookie, {})).status, 403);
assert.equal((await login('owner', 'assistant')).status, 403);
const boss = await login('owner', 'owner');
assert.equal(boss.status, 200);
assert.equal((await call('/api/state', 'owner', boss.headers.get('set-cookie').split(';')[0])).status, 200);
assert.equal((await call('/api/state', 'store', cookie)).status, 200);
});
+24 -6
View File
@@ -151,6 +151,24 @@ test('保存店铺配置使用revision且不提交员工资料;未改分成时
fields.profitShareEffectiveMonth.value = '2026-10';
assert.throws(() => h.run('shopSettingsInput(__form)'), /本月或以后/);
});
test('营业时间原值不随其他字段提交;两项留空清除,跨日有效', () => {
const h = harness();
h.run("state.shopSettings.businessHours={open:'09:00',close:'18:00'}");
const { fields } = h.form();
const input = () => h.json('shopSettingsInput(__form)');
assert.equal(fields.businessOpen.value, '09:00');
assert.equal(fields.businessClose.value, '18:00');
assert.equal(Object.hasOwn(input(), 'businessHours'), false);
fields.businessOpen.value = '20:30';
fields.businessClose.value = '02:00';
assert.deepEqual(input().businessHours, { open: '20:30', close: '02:00' });
fields.businessClose.value = '20:30';
assert.throws(input, /开始和结束时间不能相同/);
fields.businessOpen.value = '';
assert.throws(input, /请完整填写开始和结束时间/);
fields.businessClose.value = '';
assert.equal(input().businessHours, null);
});
test('店铺配置校验阻止错误费率、过大默认费及非店主保存', () => {
const h = harness(),
{ fields } = h.form();
@@ -209,12 +227,12 @@ test('店名、成员及登录文本均转义,配置名不能变成HTML元素'
const people = h.run('peopleCountHTML(null)');
assert.match(people, /&lt;i&gt;成员&lt;\/i&gt;/);
assert.doesNotMatch(people, /<i>成员/);
const login = { innerHTML: '' };
h.nodes.set('#login', login);
h.nodes.set('#shell', { hidden: false });
h.run('login()');
assert.match(login.innerHTML, /&lt;img src=x&gt;/);
assert.doesNotMatch(login.innerHTML, /<img|<b>店东/);
const login = require('../server/login-page').loginPage({
brand: { storeName: h.run('shopBrandName()') },
loginOptions: [{ member: 'owner', label: '<b>店东</b>' }],
});
assert.match(login, /&lt;img src=x&gt;/);
assert.doesNotMatch(login, /<img|<b>店东/);
});
test('历史转账方向、负数返款说明与垫付标题转义配置成员名', () => {
const h = harness();
+28
View File
@@ -423,3 +423,31 @@ test('账号下拉按固定成员登录,密码仍必校验,停用或未知
!(await f.call('/api/session', undefined, 'none')).body.loginOptions.some(row => row.member === 'assistant'),
);
});
test('店主可配置和清除每日营业时段,员工无权修改,旧客户端保存其他字段保留时段', async t => {
const f = await fixture(t);
const route = '/api/shop-settings',
hours = { open: '20:30', close: '02:00' };
assert.equal((await f.call(route)).body.businessHours, null);
assert.equal((await f.call(route, { revision: 0, businessHours: hours }, 'assistant')).status, 403);
for (const invalid of [{ open: '08:00' }, { open: '24:00', close: '18:00' }, { open: '09:00', close: '09:00' }]) {
assert.equal((await f.call(route, { revision: 0, businessHours: invalid })).status, 400);
}
assert.deepEqual((await f.call(route, { revision: 0, businessHours: hours })).body.shopSettings.businessHours, hours);
assert.deepEqual((await f.call(route, { revision: 1, contact: '测试门店' })).body.shopSettings.businessHours, hours);
assert.equal((await f.call(route, { revision: 1, businessHours: null })).status, 409);
const staff = await f.call(route, undefined, 'assistant');
assert.equal(staff.status, 200);
assert.equal(Object.hasOwn(staff.body, 'businessHours'), false);
assert.equal((await f.call(route, { revision: 2, businessHours: null })).body.shopSettings.businessHours, null);
assert.equal(f.ledger.meta(Settings.KEY).businessHours, null);
const changes = f.ledger
.rows("SELECT detail FROM audit WHERE entity='shop-settings' ORDER BY id")
.map(({ detail }) => JSON.parse(detail))
.map(({ before, after }) => [before.businessHours, after.businessHours]);
assert.deepEqual(changes, [
[null, hours],
[hours, hours],
[hours, null],
]);
});
+4 -4
View File
@@ -572,10 +572,10 @@ test('娜娜和小昊统一显示,姓名与账户转换不更改选项值、
};
assert.equal(h.run('readPaymentAccount(__form)'), '助理2支付宝');
assert.match(h.run('field("开单人","salesperson","历史开单人助理2")'), /value="历史开单人助理2"/);
h.nodes.set('#shell', { hidden: false });
h.nodes.set('#login', { innerHTML: '' });
h.run("session.mode='trial';session.setup=false;login();");
const login = h.nodes.get('#login').innerHTML;
const login = require('../server/login-page').loginPage({
brand: { storeName: '测试珠宝' },
loginOptions: [{ member: 'assistant', label: '娜娜' }],
});
assert.match(login, /登录账号/);
assert.match(login, /<select name="member"[^>]*autocomplete="username"/);
assert.doesNotMatch(login, /<input[^>]*name="name"/);
+2 -1
View File
@@ -156,7 +156,8 @@ test('HTTP:试用模式提供 /next/ 页面与资源,带安全响应头;
assert.equal((await request(port, '/next/..%2Fpackage.json')).status, 404);
const old = await request(port, '/');
assert.equal(old.status, 200);
assert.match(old.body, /\/app\.js/);
assert.match(old.body, /data-standalone-login/);
assert.doesNotMatch(old.body, /src="\/app\.js"/);
assert.equal((await request(port, '/nextx')).status, 404);
const post = await request(port, '/next/', {
method: 'POST',