路由表化:迁移登录/会话、报表/备份/同步路由,删除旧路由链,server.js 收为入口

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
黄健铭andClaude Opus 5.5 committed 2026-12-04 12:35:49 -08:00
1 parent d5c015f826
commit 2305900178
8 files changed
+632 -493

No files matched your search

+4 -492
View File
@@ -1,465 +1,11 @@
'use strict'; 'use strict';
const http = require('node:http'); // 入口:正式启动(运行锁 → 升级前备份 → 创建应用 → 显式迁移 → 监听);同时导出测试与 launch.js 使用的接口。
const fs = require('node:fs'); const fs = require('node:fs');
const path = require('node:path'); const path = require('node:path');
const crypto = require('node:crypto');
const { DatabaseSync, backup } = require('node:sqlite');
const TeamMembers = require('./team-members');
const ShopSettings = require('./shop-settings'); const ShopSettings = require('./shop-settings');
const PrintStatus = require('./print-status'); const { createApp } = require('./server/app');
const OrderChanges = require('./order-changes'); const { createUser, demoSeed } = require('./server/accounts');
const OrderNoteTags = require('./order-note-tags'); const { prepareTeamStartupDatabase, prepareStartupMigrations } = require('./server/startup');
const { inventoryMovementsFile } = require('./inventory-movements-export');
const { Ledger, ACCOUNTS, today, fail, text, owner } = require('./ledger');
const { receipt } = require('./printing');
const { recoveryCustomerPrintDocument, exchangeCustomerPrintDocument } = require('./recovery-printing');
const { FeishuSync } = require('./sync');
const { InventorySnapshotScheduler } = require('./inventory-snapshot-scheduler');
const { sha, derive } = require('./server/hash');
const { createUser, ensureTeamAccounts, demoSeed } = require('./server/accounts');
const { send } = require('./server/http');
const { readBody: read } = require('./server/middleware/body');
const { createSessions } = require('./server/middleware/session');
const { createRouter } = require('./server/router');
const { runRoute } = require('./server/dispatcher');
const routes = require('./server/routes');
const router = createRouter(routes);
function csvText(value) {
const text = String(value),
safe = /^[\s\u0000-\u001f]*[=+\-@]|^[\u0000-\u001f]/.test(text) ? "'" + text : text;
return '"' + safe.replace(/"/g, '""') + '"';
}
function createApp(options = {}) {
const mode = options.mode || process.env.APP_MODE || 'trial';
const production = mode === 'production';
const host = options.host || process.env.HOST || '127.0.0.1';
const port = Number(options.port ?? process.env.PORT ?? 3100);
if (!['trial', 'demo', 'production'].includes(mode)) throw new Error('APP_MODE须为trial、demo或production');
if (!production && !['127.0.0.1', '::1', 'localhost'].includes(host))
throw new Error('试用/演示只能绑定本机,云端请配置production模式与HTTPS');
if (
production &&
(!process.env.PUBLIC_URL?.startsWith('https://') || !process.env.DATA_DIR || !path.isAbsolute(process.env.DATA_DIR))
)
throw new Error('云端须配置HTTPS PUBLIC_URL和绝对路径持久化DATA_DIR');
const dataDir = options.dataDir || (production ? process.env.DATA_DIR : null) || path.join(__dirname, 'data', mode);
const ledger = options.ledger || new Ledger(path.join(dataDir, 'ledger.sqlite'));
ledger.enableTeamMode();
if (mode === 'demo') demoSeed(ledger);
const configPath = process.env.FEISHU_CONFIG || path.join(__dirname, 'feishu.local.json');
const config =
options.feishuConfig ||
(mode !== 'demo' && fs.existsSync(configPath) ? JSON.parse(fs.readFileSync(configPath, 'utf8')) : null);
if (production && !ledger.one('SELECT id FROM users LIMIT 1') && process.env.SHOP_NAME) {
require('./new-shop').initialize(
ledger,
{
storeName: process.env.SHOP_NAME,
ownerLabel: process.env.OWNER_DISPLAY_NAME || '店主',
ownerLoginName: process.env.OWNER_LOGIN_NAME || 'owner',
ownerPassword: process.env.OWNER_INITIAL_PASSWORD,
},
createUser,
);
}
if (production && !ledger.one('SELECT id FROM users LIMIT 1')) {
if (!process.env.OWNER_INITIAL_PASSWORD || !process.env.ASSISTANT_INITIAL_PASSWORD)
throw new Error('首次云端启动须在服务器环境设置两个初始密码,禁止公开初始化入口');
for (const pw of [process.env.OWNER_INITIAL_PASSWORD, process.env.ASSISTANT_INITIAL_PASSWORD])
if (pw.length < 12) throw new Error('云端初始密码至少12位');
createUser(ledger, '麦麦', 'owner', process.env.OWNER_INITIAL_PASSWORD);
createUser(ledger, '助理', 'assistant', process.env.ASSISTANT_INITIAL_PASSWORD);
}
ensureTeamAccounts(ledger);
const sync = new FeishuSync(ledger, config, options.fetcher);
const automaticSnapshots = new InventorySnapshotScheduler(ledger, {
clock: options.clock,
logger: options.inventorySnapshotLogger,
...options.inventorySnapshotTimers,
});
const { user, session } = createSessions(ledger, { production });
const backupState = { last: null, error: null };
let backupBusy = false;
async function doBackup() {
if (backupBusy) fail('备份进行中,请稍后');
backupBusy = true;
try {
const name = 'ledger-' + new Date().toISOString().replace(/[:.]/g, '-') + '.sqlite';
const dest = path.join(dataDir, 'backups', name);
await ledger.backupTo(dest);
backupState.last = { name, time: new Date().toISOString() };
backupState.error = null;
return { name, path: dest };
} catch (e) {
backupState.error = '备份失败,请检查磁盘空间与目录权限';
throw e;
} finally {
backupBusy = false;
}
}
const app = { mode, production, dataDir, ledger, sync, automaticSnapshots, doBackup, backupState, user, session };
const server = http.createServer(async (req, res) => {
res.setHeader('Cache-Control', 'no-store');
res.setHeader('X-Content-Type-Options', 'nosniff');
res.setHeader('X-Frame-Options', 'DENY');
res.setHeader('Referrer-Policy', 'no-referrer');
res.setHeader(
'Content-Security-Policy',
"default-src 'self'; style-src 'self' 'unsafe-inline'; script-src 'self'; img-src 'self' data:; connect-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'self'",
);
try {
const expected = production ? new URL(process.env.PUBLIC_URL).host : req.headers.host;
if (production && req.headers.host !== expected) fail('访问地址不匹配', 403);
if (!production && !/^(localhost|127\.0\.0\.1|\[::1\])(?::\d+)?$/.test(req.headers.host || ''))
fail('仅允许本机地址访问', 403);
const url = new URL(req.url, 'http://' + req.headers.host);
const route = url.pathname;
const isPost = req.method === 'POST';
if (!['GET', 'POST'].includes(req.method)) fail('不支持的请求方式', 405);
if (isPost) {
const expectedOrigin = production ? new URL(process.env.PUBLIC_URL).origin : 'http://' + req.headers.host;
if (
req.headers.origin !== expectedOrigin ||
req.headers['x-requested-with'] !== 'maimai-ledger' ||
!req.headers['content-type']?.startsWith('application/json')
)
fail('请从系统页面提交操作', 403);
}
if (route === '/api/session' && !isPost)
return send(res, 200, {
user: user(req),
setup: !ledger.one('SELECT id FROM users LIMIT 1'),
mode,
today: today(),
brand: {
storeName: ledger.one('SELECT id FROM users LIMIT 1') ? ShopSettings.read(ledger).storeName : '店铺台账',
},
loginOptions: ShopSettings.loginOptions(ledger)
.filter(row => ledger.one('SELECT user_id FROM team_user_members WHERE member=?', row.member))
.map(({ member, label }) => ({ member, label })),
});
if (route === '/api/setup' && isPost) {
if (production || mode === 'demo' || ledger.one('SELECT id FROM users LIMIT 1')) fail('初始化入口已关闭', 403);
const b = await read(req);
if (b.storeName !== undefined) {
const actor = require('./new-shop').initialize(ledger, b, createUser);
return send(res, 200, session(res, actor));
}
if (String(b.ownerPassword || '').length < 12 || String(b.assistantPassword || '').length < 12)
fail('两组密码都至少12个字符');
ledger.db.exec('BEGIN IMMEDIATE');
try {
createUser(ledger, '麦麦', 'owner', b.ownerPassword);
createUser(ledger, '助理', 'assistant', b.assistantPassword);
if (b.assistant2Password !== undefined) {
if (String(b.assistant2Password).length < 12) fail('小昊密码至少12个字符');
createUser(ledger, '助理2', 'assistant', b.assistant2Password, 'assistant2');
}
ensureTeamAccounts(ledger);
ledger.db.exec('COMMIT');
} catch (e) {
ledger.db.exec('ROLLBACK');
throw e;
}
return send(res, 200, session(res, ledger.one("SELECT id,name,role FROM users WHERE role='owner'")));
}
if (route === '/api/login' && isPost) {
const b = await read(req);
const u =
b.member !== undefined
? typeof b.member === 'string'
? ledger.one(
'SELECT u.* FROM users u JOIN team_user_members t ON t.user_id=u.id JOIN team_members m ON m.member=t.member WHERE t.member=? AND m.enabled=1',
b.member,
)
: null
: ShopSettings.resolveLogin(ledger, b.name);
const pw = String(b.password || '');
const hash = derive(pw.slice(0, 500), u?.salt || 'dummy-salt');
if (
!u ||
ledger.one('SELECT password_set FROM team_user_members WHERE user_id=?', u.id)?.password_set === 0 ||
!crypto.timingSafeEqual(Buffer.from(hash, 'hex'), Buffer.from(u.hash, 'hex'))
)
fail('账号或密码不正确', 401);
return send(res, 200, session(res, u));
}
if (route === '/api/demo-login' && isPost && mode === 'demo') {
const b = await read(req),
member =
b.member ?? (b.role === 'assistant2' ? 'assistant2' : b.role === 'assistant' ? 'assistant' : 'owner');
if (!TeamMembers.isActive(ledger, member)) fail('演示成员无效');
return send(
res,
200,
session(
res,
ledger.one(
'SELECT u.id,u.name,u.role FROM users u JOIN team_user_members t ON t.user_id=u.id WHERE t.member=?',
member,
),
),
);
}
const actor = user(req);
const actorLedger = ledger.asActor(actor);
if (route.startsWith('/api/') || route.startsWith('/print/')) {
if (!actor) fail('请先登录', 401);
// 仅校验本次页面的原账号与cookie一致,实际授权仍由登录和成员权限决定。
if (req.headers['x-ledger-user'] !== undefined && req.headers['x-ledger-user'] !== actor.id) {
const error = new Error('登录账号已在其他页面切换,请刷新后继续;原操作已暂停。');
error.status = 409;
error.code = 'ACCOUNT_CHANGED';
throw error;
}
const hit = router.match(req.method, route);
if (hit)
return await runRoute(hit.route, {
req,
res,
url,
params: hit.params,
query: Object.fromEntries(url.searchParams),
actor,
ledger: actorLedger,
rawLedger: ledger,
app,
});
if (route === '/api/logout' && isPost) {
const token = req.headers.cookie
?.split(';')
.map(x => x.trim())
.find(x => x.startsWith('mm_session='))
?.slice(11);
if (token) actorLedger.run('DELETE FROM sessions WHERE hash=?', sha(token));
res.setHeader('Set-Cookie', 'mm_session=; HttpOnly; SameSite=Strict; Path=/; Max-Age=0');
return send(res, 200, { ok: true });
}
if (route === '/api/state' && !isPost) {
const orders = actorLedger
.visibleRows('order', actorLedger.rows('SELECT id FROM orders ORDER BY created DESC'))
.map(r => actorLedger.detail(r.id));
return send(res, 200, {
today: today(),
mode,
user: actor,
members: TeamMembers.members(actorLedger),
shopSettings: ShopSettings.publicSettings(actorLedger, actor),
pockets: actorLedger.activePocketKeys(),
pocketCatalog: actorLedger.pocketCatalog(),
accounts: actorLedger.paymentAccounts({ activeOnly: true }),
inventory: actorLedger.inventory(),
orders: orders.map(({ audit, payments, expenses, settlements, ...o }) => o),
priceLockCounts: actorLedger.priceLocks({ status: 'pending' }).counts,
materialPoolSummary: actorLedger.materialPools().summary,
materialPoolSettlement: actorLedger.materialPoolSettlement(),
materialPoolAllocation: actorLedger.materialPoolAllocationStatus(),
sync: actor.role === 'owner' ? sync.status() : { enabled: sync.enabled },
printing: ShopSettings.printingSettings(actorLedger),
backup: actor.role === 'owner' ? { last: backupState.last, error: backupState.error } : null,
movements: actorLedger.inventoryMovements({}, actor).movements,
});
}
if (route === '/api/report' && !isPost) {
const report = actorLedger.reportFor(Object.fromEntries(url.searchParams), actor);
if (actor.role !== 'owner') report.peopleCount = null;
return send(res, 200, report);
}
if (route === '/api/export/inventory' && !isPost) {
owner(actor);
res.setHeader('Content-Disposition', 'attachment; filename="inventory.csv"');
return send(
res,
200,
'\ufeff货盘,账面克重,已占用克重,可用克重,计数单位,账面对数,已占用对数,可用对数\r\n' +
actorLedger
.inventory()
.map(r =>
[
csvText(actorLedger.pocketLabel(r.pocket)),
(r.mg / 1000).toFixed(3),
(r.reserved / 1000).toFixed(3),
(r.available / 1000).toFixed(3),
...(r.countUnit === 'pair'
? ['对', r.count ?? '未登记', r.reservedCount ?? '未登记', r.availableCount ?? '未登记']
: ['', '', '', '']),
].join(','),
)
.join('\r\n'),
'text/csv; charset=utf-8',
);
}
if (route === '/api/backup' && isPost) {
owner(actor);
await read(req);
const b = await doBackup();
actorLedger.audit('system', '完整备份', actor, { name: b.name });
return send(res, 200, { name: b.name });
}
if (route.startsWith('/api/backup/') && !isPost) {
owner(actor);
const filename = route.slice(12);
if (!/^ledger-[\dTZ-]+\.sqlite$/.test(filename)) fail('备份名称无效');
const file = path.join(dataDir, 'backups', filename);
if (!fs.existsSync(file)) fail('备份不存在', 404);
res.setHeader('Content-Disposition', `attachment; filename="${filename}"`);
res.writeHead(200, { 'Content-Type': 'application/octet-stream' });
return fs.createReadStream(file).pipe(res);
}
if (route === '/api/sync' && isPost) {
owner(actor);
await read(req);
await sync.tick();
return send(res, 200, sync.status());
}
if (!isPost) fail('地址不存在', 404);
const b = await read(req);
const key = req.headers['idempotency-key'];
// 读取请求体期间账号可能已被停用或重置密码,写入前再次核验会话。
const checkedActor = user(req);
if (!checkedActor || checkedActor.id !== actor.id) fail('登录已失效,请重新登录', 401);
const result = actorLedger.transact(
key,
actor,
{ route, body: b },
() => {
if (route === '/api/password') {
const u = actorLedger.one('SELECT * FROM users WHERE id=?', actor.id);
if (derive(String(b.current || ''), u.salt) !== u.hash) fail('原密码不正确');
if (String(b.password || '').length < 12) fail('新密码至少12个字符');
const salt = crypto.randomBytes(24).toString('hex');
actorLedger.run('UPDATE users SET salt=?,hash=? WHERE id=?', salt, derive(b.password, salt), actor.id);
actorLedger.run('UPDATE team_user_members SET password_set=1 WHERE user_id=?', actor.id);
actorLedger.run('DELETE FROM sessions WHERE user_id=?', actor.id);
return { ok: true };
}
fail('地址不存在', 404);
},
{
syncTeamFunds: !['/api/password'].includes(route),
},
);
return send(res, 200, result);
}
const assets = {
'/': 'index.html',
'/private-operations-ui.js': 'private-operations-ui.js',
'/app.js': 'app.js',
'/order-copy.js': 'order-copy.js',
'/order-templates.js': 'order-templates.js',
'/order-templates-ui.js': 'order-templates-ui.js',
'/order-edit-ui.js': 'order-edit-ui.js',
'/order-cancellations-ui.js': 'order-cancellations-ui.js',
'/order-changes-ui.js': 'order-changes-ui.js',
'/order-after-sales-ui.js': 'order-after-sales-ui.js',
'/order-ownership-ui.js': 'order-ownership-ui.js',
'/daily-funds-ui.js': 'daily-funds-ui.js',
'/team-funds-ui.js': 'team-funds-ui.js',
'/cost-funding-ui.js': 'cost-funding-ui.js',
'/price-locks-ui.js': 'price-locks-ui.js',
'/price-lock-changes-ui.js': 'price-lock-changes-ui.js',
'/material-pools-ui.js': 'material-pools-ui.js',
'/recoveries-ui.js': 'recoveries-ui.js',
'/recovery-changes-ui.js': 'recovery-changes-ui.js',
'/inventory-changes-ui.js': 'inventory-changes-ui.js',
'/pockets-ui.js': 'pockets-ui.js',
'/shop-settings-ui.js': 'shop-settings-ui.js',
'/employees-ui.js': 'employees-ui.js',
'/credit-card-fees.js': 'credit-card-fees.js',
'/calculations.js': 'calculations.js',
'/order-formula.js': 'order-formula.js',
'/fee-estimates.js': 'fee-estimates.js',
'/order-cost-presets-ui.js': 'order-cost-presets-ui.js',
'/app.css': 'app.css',
'/print.js': 'print.js',
};
const file = assets[route];
if (!file || isPost) fail('地址不存在', 404);
send(
res,
200,
fs.readFileSync(path.join(__dirname, 'public', file)),
file.endsWith('.js')
? 'application/javascript; charset=utf-8'
: file.endsWith('.css')
? 'text/css; charset=utf-8'
: 'text/html; charset=utf-8',
);
} catch (e) {
if (!res.headersSent)
send(res, e.status || 400, {
error:
e.status || e.message?.startsWith('打印')
? e.message
: e.code?.startsWith('SQLITE')
? '保存失败,请保留操作内容并联系维护者'
: e.message || '操作失败',
...(e.code === 'ACCOUNT_CHANGED' ? { code: e.code } : {}),
...(e.code === 'EMPLOYEE_HAS_BUSINESS' ? { code: e.code, businessUsage: e.businessUsage } : {}),
...(e.code === 'RECOVERY_MATERIAL_IN_USE' ? { code: e.code, blockedUsages: e.blockedUsages } : {}),
});
else res.end();
}
});
const timers = [];
function startTimers() {
if (timers.length) return false;
timers.push(setInterval(() => sync.tick(), 60000));
timers.push(setInterval(() => doBackup().catch(() => {}), 6 * 60 * 60 * 1000));
automaticSnapshots.start();
doBackup().catch(() => {});
for (const t of timers) t.unref();
return true;
}
function stop() {
for (const t of timers) clearInterval(t);
timers.length = 0;
automaticSnapshots.stop();
server.close();
}
return { server, ledger, sync, automaticSnapshots, startTimers, stop, host, port, dataDir, mode, doBackup };
}
// 在 Ledger 构造器执行任何增量建表前备份旧库;只在显式正式启动路径调用。
async function prepareTeamStartupDatabase(dataDir) {
const filename = path.join(dataDir, 'ledger.sqlite');
if (!fs.existsSync(filename)) return { required: false, backupName: null };
const source = new DatabaseSync(filename, { readOnly: true });
let required, backupName;
try {
const hasMeta = source.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='meta'").get();
const teamReady = hasMeta && source.prepare("SELECT value FROM meta WHERE key='team-mode-v1'").get();
const materialRule =
hasMeta && source.prepare("SELECT value FROM meta WHERE key='team-material-funding-rule'").get();
let materialReady = false;
try {
materialReady = JSON.parse(materialRule?.value || 'null')?.version >= 2;
} catch {}
required = !(teamReady && materialReady);
if (!required) return { required: false, backupName: null };
backupName =
(teamReady ? 'ledger-before-material-usage-v2-' : 'ledger-before-team-v1-') +
new Date().toISOString().replace(/[:.]/g, '-') +
'-' +
crypto.randomUUID().slice(0, 8) +
'.sqlite';
const directory = path.join(dataDir, 'backups');
fs.mkdirSync(directory, { recursive: true, mode: 0o700 });
const destination = path.join(directory, backupName);
await backup(source, destination);
fs.chmodSync(destination, 0o600);
const check = new DatabaseSync(destination, { readOnly: true });
try {
if (check.prepare('PRAGMA integrity_check').get().integrity_check !== 'ok')
throw new Error('三人台账升级前备份完整性检查失败');
} finally {
check.close();
}
return { required: true, backupName };
} finally {
source.close();
}
}
function acquireLock(dataDir) { function acquireLock(dataDir) {
fs.mkdirSync(dataDir, { recursive: true, mode: 0o700 }); fs.mkdirSync(dataDir, { recursive: true, mode: 0o700 });
const lock = path.join(dataDir, 'server.lock'); const lock = path.join(dataDir, 'server.lock');
@@ -483,40 +29,6 @@ function acquireLock(dataDir) {
} catch {} } catch {}
}; };
} }
// 正式启动先备份再显式迁移,完成全部不变量核对后才能监听;createApp 保持同步的测试/嵌入入口。
async function prepareStartupMigrations(app) {
const status = app.ledger.materialPoolAllocationStatus();
if (!status.migrationRequired) return { changed: false, ...status };
let backupName = null;
if (status.usageCount) {
backupName =
'ledger-before-material-fifo-v' +
status.targetVersion +
'-' +
new Date().toISOString().replace(/[:.]/g, '-') +
'-' +
crypto.randomUUID().slice(0, 8) +
'.sqlite';
const destination = path.join(app.dataDir, 'backups', backupName);
await app.ledger.backupTo(destination);
if (!fs.statSync(destination).isFile() || !fs.statSync(destination).size)
throw new Error('日购料升级前备份未完整写入');
const check = new DatabaseSync(destination);
try {
check.exec('PRAGMA query_only=ON');
if (check.prepare('PRAGMA integrity_check').get().integrity_check !== 'ok')
throw new Error('日购料升级前备份完整性检查失败');
} finally {
check.close();
}
}
const actor = {
id: 'system-material-pool-fifo-v' + status.targetVersion,
name: '系统升级(日购料垫付FIFO v' + status.targetVersion + ')',
role: 'system',
};
return app.ledger.migrateMaterialPoolAllocation(actor, { backupName });
}
if (require.main === module) { if (require.main === module) {
let unlock, app; let unlock, app;
(async () => { (async () => {
+104
View File
@@ -0,0 +1,104 @@
'use strict';
// 应用装配:配置校验、台账与账号初始化、飞书同步、自动盘点快照、备份,以及 HTTP 服务(路由表分发)。
const http = require('node:http');
const fs = require('node:fs');
const path = require('node:path');
const { Ledger, fail } = require('../ledger');
const { FeishuSync } = require('../sync');
const { InventorySnapshotScheduler } = require('../inventory-snapshot-scheduler');
const { createUser, ensureTeamAccounts, demoSeed } = require('./accounts');
const { createSessions } = require('./middleware/session');
const { createHandler } = require('./dispatcher');
const routes = require('./routes');
const ROOT = path.join(__dirname, '..');
function createApp(options = {}) {
const mode = options.mode || process.env.APP_MODE || 'trial';
const production = mode === 'production';
const host = options.host || process.env.HOST || '127.0.0.1';
const port = Number(options.port ?? process.env.PORT ?? 3100);
if (!['trial', 'demo', 'production'].includes(mode)) throw new Error('APP_MODE须为trial、demo或production');
if (!production && !['127.0.0.1', '::1', 'localhost'].includes(host))
throw new Error('试用/演示只能绑定本机,云端请配置production模式与HTTPS');
if (
production &&
(!process.env.PUBLIC_URL?.startsWith('https://') || !process.env.DATA_DIR || !path.isAbsolute(process.env.DATA_DIR))
)
throw new Error('云端须配置HTTPS PUBLIC_URL和绝对路径持久化DATA_DIR');
const dataDir = options.dataDir || (production ? process.env.DATA_DIR : null) || path.join(ROOT, 'data', mode);
const ledger = options.ledger || new Ledger(path.join(dataDir, 'ledger.sqlite'));
ledger.enableTeamMode();
if (mode === 'demo') demoSeed(ledger);
const configPath = process.env.FEISHU_CONFIG || path.join(ROOT, 'feishu.local.json');
const config =
options.feishuConfig ||
(mode !== 'demo' && fs.existsSync(configPath) ? JSON.parse(fs.readFileSync(configPath, 'utf8')) : null);
if (production && !ledger.one('SELECT id FROM users LIMIT 1') && process.env.SHOP_NAME) {
require('../new-shop').initialize(
ledger,
{
storeName: process.env.SHOP_NAME,
ownerLabel: process.env.OWNER_DISPLAY_NAME || '店主',
ownerLoginName: process.env.OWNER_LOGIN_NAME || 'owner',
ownerPassword: process.env.OWNER_INITIAL_PASSWORD,
},
createUser,
);
}
if (production && !ledger.one('SELECT id FROM users LIMIT 1')) {
if (!process.env.OWNER_INITIAL_PASSWORD || !process.env.ASSISTANT_INITIAL_PASSWORD)
throw new Error('首次云端启动须在服务器环境设置两个初始密码,禁止公开初始化入口');
for (const pw of [process.env.OWNER_INITIAL_PASSWORD, process.env.ASSISTANT_INITIAL_PASSWORD])
if (pw.length < 12) throw new Error('云端初始密码至少12位');
createUser(ledger, '麦麦', 'owner', process.env.OWNER_INITIAL_PASSWORD);
createUser(ledger, '助理', 'assistant', process.env.ASSISTANT_INITIAL_PASSWORD);
}
ensureTeamAccounts(ledger);
const sync = new FeishuSync(ledger, config, options.fetcher);
const automaticSnapshots = new InventorySnapshotScheduler(ledger, {
clock: options.clock,
logger: options.inventorySnapshotLogger,
...options.inventorySnapshotTimers,
});
const { user, session } = createSessions(ledger, { production });
const backupState = { last: null, error: null };
let backupBusy = false;
async function doBackup() {
if (backupBusy) fail('备份进行中,请稍后');
backupBusy = true;
try {
const name = 'ledger-' + new Date().toISOString().replace(/[:.]/g, '-') + '.sqlite';
const dest = path.join(dataDir, 'backups', name);
await ledger.backupTo(dest);
backupState.last = { name, time: new Date().toISOString() };
backupState.error = null;
return { name, path: dest };
} catch (e) {
backupState.error = '备份失败,请检查磁盘空间与目录权限';
throw e;
} finally {
backupBusy = false;
}
}
const app = { mode, production, dataDir, ledger, sync, automaticSnapshots, doBackup, backupState, user, session };
const server = http.createServer(createHandler(app, routes));
const timers = [];
function startTimers() {
if (timers.length) return false;
timers.push(setInterval(() => sync.tick(), 60000));
timers.push(setInterval(() => doBackup().catch(() => {}), 6 * 60 * 60 * 1000));
automaticSnapshots.start();
doBackup().catch(() => {});
for (const t of timers) t.unref();
return true;
}
function stop() {
for (const t of timers) clearInterval(t);
timers.length = 0;
automaticSnapshots.stop();
server.close();
}
return { server, ledger, sync, automaticSnapshots, startTimers, stop, host, port, dataDir, mode, doBackup };
}
module.exports = { createApp };
+43 -1
View File
@@ -13,8 +13,14 @@
// 未匹配的 /api/、/print/ 请求:GET 直接 404;POST 照常读请求体、复核会话、进入 transact 后再 404, // 未匹配的 /api/、/print/ 请求:GET 直接 404;POST 照常读请求体、复核会话、进入 transact 后再 404,
// 因此请求体过大/非 JSON、会话失效、操作号无效等错误仍先于 404 返回。 // 因此请求体过大/非 JSON、会话失效、操作号无效等错误仍先于 404 返回。
const { fail, owner } = require('../ledger'); const { fail, owner } = require('../ledger');
const { createRouter } = require('./router');
const { send, notFound } = require('./http'); const { send, notFound } = require('./http');
const { readBody } = require('./middleware/body'); const { readBody } = require('./middleware/body');
const { securityHeaders } = require('./middleware/security-headers');
const { checkRequest } = require('./middleware/request-guard');
const { requireActor } = require('./middleware/session');
const { serveStatic } = require('./middleware/static');
const { sendError } = require('./middleware/errors');
const UNMATCHED = { const UNMATCHED = {
GET: { method: 'GET', handler: notFound }, GET: { method: 'GET', handler: notFound },
@@ -48,4 +54,40 @@ async function runRoute(route, ctx) {
send(res, 200, route.project ? route.project(ctx, result) : result); send(res, 200, route.project ? route.project(ctx, result) : result);
} }
module.exports = { runRoute, UNMATCHED }; // 处理顺序:安全响应头 → Host/405/来源校验 → 登录前路由 → 解析当前账号 → /api/、/print/ 的 401/409
// → 路由(含未匹配)→ 静态文件 → 统一错误响应。
function createHandler(app, routes) {
const router = createRouter(routes);
const enabled = route => !route.when || route.when(app);
return async (req, res) => {
securityHeaders(res);
try {
const { url, route: pathname, isPost } = checkRequest(req, app.production);
const hit = router.match(req.method, pathname, enabled);
const ctx = {
req,
res,
url,
params: hit?.params ?? {},
query: Object.fromEntries(url.searchParams),
body: undefined,
actor: null,
ledger: null,
rawLedger: app.ledger,
app,
};
if (hit?.route.auth === 'public') return await runRoute(hit.route, ctx);
ctx.actor = app.user(req);
ctx.ledger = app.ledger.asActor(ctx.actor);
if (pathname.startsWith('/api/') || pathname.startsWith('/print/')) {
requireActor(req, ctx.actor);
return await runRoute(hit?.route ?? UNMATCHED[req.method], ctx);
}
serveStatic(res, pathname, isPost);
} catch (e) {
sendError(res, e);
}
};
}
module.exports = { createHandler, runRoute, UNMATCHED };
+166
View File
@@ -0,0 +1,166 @@
'use strict';
// 登录前入口(会话、初始化、登录、演示登录),退出、页面初始状态、修改本人密码。
const crypto = require('node:crypto');
const TeamMembers = require('../../team-members');
const ShopSettings = require('../../shop-settings');
const { today, fail } = require('../../ledger');
const { sha, derive } = require('../hash');
const { createUser, ensureTeamAccounts } = require('../accounts');
const { readBody } = require('../middleware/body');
const { sessionToken } = require('../middleware/session');
module.exports = [
{
method: 'GET',
path: '/api/session',
auth: 'public',
handler: ({ req, app, rawLedger: ledger }) => ({
user: app.user(req),
setup: !ledger.one('SELECT id FROM users LIMIT 1'),
mode: app.mode,
today: today(),
brand: {
storeName: ledger.one('SELECT id FROM users LIMIT 1') ? ShopSettings.read(ledger).storeName : '店铺台账',
},
loginOptions: ShopSettings.loginOptions(ledger)
.filter(row => ledger.one('SELECT user_id FROM team_user_members WHERE member=?', row.member))
.map(({ member, label }) => ({ member, label })),
}),
},
{
method: 'POST',
path: '/api/setup',
auth: 'public',
direct: true,
handler: async ({ req, res, app, rawLedger: ledger }) => {
if (app.production || app.mode === 'demo' || ledger.one('SELECT id FROM users LIMIT 1'))
fail('初始化入口已关闭', 403);
const b = await readBody(req);
if (b.storeName !== undefined) {
const actor = require('../../new-shop').initialize(ledger, b, createUser);
return app.session(res, actor);
}
if (String(b.ownerPassword || '').length < 12 || String(b.assistantPassword || '').length < 12)
fail('两组密码都至少12个字符');
ledger.db.exec('BEGIN IMMEDIATE');
try {
createUser(ledger, '麦麦', 'owner', b.ownerPassword);
createUser(ledger, '助理', 'assistant', b.assistantPassword);
if (b.assistant2Password !== undefined) {
if (String(b.assistant2Password).length < 12) fail('小昊密码至少12个字符');
createUser(ledger, '助理2', 'assistant', b.assistant2Password, 'assistant2');
}
ensureTeamAccounts(ledger);
ledger.db.exec('COMMIT');
} catch (e) {
ledger.db.exec('ROLLBACK');
throw e;
}
return app.session(res, ledger.one("SELECT id,name,role FROM users WHERE role='owner'"));
},
},
{
method: 'POST',
path: '/api/login',
auth: 'public',
direct: true,
handler: async ({ req, res, app, rawLedger: ledger }) => {
const b = await readBody(req);
const u =
b.member !== undefined
? typeof b.member === 'string'
? ledger.one(
'SELECT u.* FROM users u JOIN team_user_members t ON t.user_id=u.id JOIN team_members m ON m.member=t.member WHERE t.member=? AND m.enabled=1',
b.member,
)
: null
: ShopSettings.resolveLogin(ledger, b.name);
const pw = String(b.password || '');
const hash = derive(pw.slice(0, 500), u?.salt || 'dummy-salt');
if (
!u ||
ledger.one('SELECT password_set FROM team_user_members WHERE user_id=?', u.id)?.password_set === 0 ||
!crypto.timingSafeEqual(Buffer.from(hash, 'hex'), Buffer.from(u.hash, 'hex'))
)
fail('账号或密码不正确', 401);
return app.session(res, u);
},
},
{
// 仅演示模式存在;其他模式下视同未声明,按登录后的未知地址处理。
method: 'POST',
path: '/api/demo-login',
auth: 'public',
when: app => app.mode === 'demo',
direct: true,
handler: async ({ req, res, app, rawLedger: ledger }) => {
const b = await readBody(req),
member = b.member ?? (b.role === 'assistant2' ? 'assistant2' : b.role === 'assistant' ? 'assistant' : 'owner');
if (!TeamMembers.isActive(ledger, member)) fail('演示成员无效');
return app.session(
res,
ledger.one(
'SELECT u.id,u.name,u.role FROM users u JOIN team_user_members t ON t.user_id=u.id WHERE t.member=?',
member,
),
);
},
},
{
// 不读请求体。
method: 'POST',
path: '/api/logout',
direct: true,
handler: ({ req, res, ledger }) => {
const token = sessionToken(req);
if (token) ledger.run('DELETE FROM sessions WHERE hash=?', sha(token));
res.setHeader('Set-Cookie', 'mm_session=; HttpOnly; SameSite=Strict; Path=/; Max-Age=0');
return { ok: true };
},
},
{
method: 'GET',
path: '/api/state',
handler: ({ ledger, actor, app }) => {
const orders = ledger
.visibleRows('order', ledger.rows('SELECT id FROM orders ORDER BY created DESC'))
.map(r => ledger.detail(r.id));
return {
today: today(),
mode: app.mode,
user: actor,
members: TeamMembers.members(ledger),
shopSettings: ShopSettings.publicSettings(ledger, actor),
pockets: ledger.activePocketKeys(),
pocketCatalog: ledger.pocketCatalog(),
accounts: ledger.paymentAccounts({ activeOnly: true }),
inventory: ledger.inventory(),
orders: orders.map(({ audit, payments, expenses, settlements, ...o }) => o),
priceLockCounts: ledger.priceLocks({ status: 'pending' }).counts,
materialPoolSummary: ledger.materialPools().summary,
materialPoolSettlement: ledger.materialPoolSettlement(),
materialPoolAllocation: ledger.materialPoolAllocationStatus(),
sync: actor.role === 'owner' ? app.sync.status() : { enabled: app.sync.enabled },
printing: ShopSettings.printingSettings(ledger),
backup: actor.role === 'owner' ? { last: app.backupState.last, error: app.backupState.error } : null,
movements: ledger.inventoryMovements({}, actor).movements,
};
},
},
{
method: 'POST',
path: '/api/password',
write: true,
syncTeamFunds: false,
handler: ({ ledger, body: b, actor }) => {
const u = ledger.one('SELECT * FROM users WHERE id=?', actor.id);
if (derive(String(b.current || ''), u.salt) !== u.hash) fail('原密码不正确');
if (String(b.password || '').length < 12) fail('新密码至少12个字符');
const salt = crypto.randomBytes(24).toString('hex');
ledger.run('UPDATE users SET salt=?,hash=? WHERE id=?', salt, derive(b.password, salt), actor.id);
ledger.run('UPDATE team_user_members SET password_set=1 WHERE user_id=?', actor.id);
ledger.run('DELETE FROM sessions WHERE user_id=?', actor.id);
return { ok: true };
},
},
];
+2
View File
@@ -1,6 +1,7 @@
'use strict'; 'use strict';
// 全部路由按声明顺序匹配;同一请求方式下路径互有重叠的路由都在同一文件内按先具体后通配排列。 // 全部路由按声明顺序匹配;同一请求方式下路径互有重叠的路由都在同一文件内按先具体后通配排列。
module.exports = [ module.exports = [
...require('./auth.routes'),
...require('./shop.routes'), ...require('./shop.routes'),
...require('./orders.routes'), ...require('./orders.routes'),
...require('./order-changes.routes'), ...require('./order-changes.routes'),
@@ -9,5 +10,6 @@ module.exports = [
...require('./inventory.routes'), ...require('./inventory.routes'),
...require('./recoveries.routes'), ...require('./recoveries.routes'),
...require('./funds.routes'), ...require('./funds.routes'),
...require('./reports.routes'),
...require('./print.routes'), ...require('./print.routes'),
]; ];
@@ -0,0 +1,92 @@
'use strict';
// 报表、库存导出、完整备份与下载、飞书同步。
const fs = require('node:fs');
const path = require('node:path');
const { fail } = require('../../ledger');
const { send } = require('../http');
const { readBody } = require('../middleware/body');
function csvText(value) {
const text = String(value),
safe = /^[\s\u0000-\u001f]*[=+\-@]|^[\u0000-\u001f]/.test(text) ? "'" + text : text;
return '"' + safe.replace(/"/g, '""') + '"';
}
module.exports = [
{
method: 'GET',
path: '/api/report',
handler: ({ ledger, query, actor }) => {
const report = ledger.reportFor(query, actor);
if (actor.role !== 'owner') report.peopleCount = null;
return report;
},
},
{
method: 'GET',
path: '/api/export/inventory',
role: 'owner',
raw: true,
handler: ({ res, ledger }) => {
res.setHeader('Content-Disposition', 'attachment; filename="inventory.csv"');
send(
res,
200,
'\ufeff货盘,账面克重,已占用克重,可用克重,计数单位,账面对数,已占用对数,可用对数\r\n' +
ledger
.inventory()
.map(r =>
[
csvText(ledger.pocketLabel(r.pocket)),
(r.mg / 1000).toFixed(3),
(r.reserved / 1000).toFixed(3),
(r.available / 1000).toFixed(3),
...(r.countUnit === 'pair'
? ['对', r.count ?? '未登记', r.reservedCount ?? '未登记', r.availableCount ?? '未登记']
: ['', '', '', '']),
].join(','),
)
.join('\r\n'),
'text/csv; charset=utf-8',
);
},
},
{
// 读取并丢弃请求体;不复核会话、不走操作号事务。
method: 'POST',
path: '/api/backup',
role: 'owner',
direct: true,
handler: async ({ req, ledger, actor, app }) => {
await readBody(req);
const b = await app.doBackup();
ledger.audit('system', '完整备份', actor, { name: b.name });
return { name: b.name };
},
},
{
method: 'GET',
path: '/api/backup/*filename',
role: 'owner',
raw: true,
handler: ({ res, params: { filename }, app }) => {
if (!/^ledger-[\dTZ-]+\.sqlite$/.test(filename)) fail('备份名称无效');
const file = path.join(app.dataDir, 'backups', filename);
if (!fs.existsSync(file)) fail('备份不存在', 404);
res.setHeader('Content-Disposition', `attachment; filename="${filename}"`);
res.writeHead(200, { 'Content-Type': 'application/octet-stream' });
fs.createReadStream(file).pipe(res);
},
},
{
method: 'POST',
path: '/api/sync',
role: 'owner',
direct: true,
handler: async ({ req, app }) => {
await readBody(req);
await app.sync.tick();
return app.sync.status();
},
},
];
+82
View File
@@ -0,0 +1,82 @@
'use strict';
// 正式启动前的升级备份与显式迁移。
const fs = require('node:fs');
const path = require('node:path');
const crypto = require('node:crypto');
const { DatabaseSync, backup } = require('node:sqlite');
// 在 Ledger 构造器执行任何增量建表前备份旧库;只在显式正式启动路径调用。
async function prepareTeamStartupDatabase(dataDir) {
const filename = path.join(dataDir, 'ledger.sqlite');
if (!fs.existsSync(filename)) return { required: false, backupName: null };
const source = new DatabaseSync(filename, { readOnly: true });
let required, backupName;
try {
const hasMeta = source.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='meta'").get();
const teamReady = hasMeta && source.prepare("SELECT value FROM meta WHERE key='team-mode-v1'").get();
const materialRule =
hasMeta && source.prepare("SELECT value FROM meta WHERE key='team-material-funding-rule'").get();
let materialReady = false;
try {
materialReady = JSON.parse(materialRule?.value || 'null')?.version >= 2;
} catch {}
required = !(teamReady && materialReady);
if (!required) return { required: false, backupName: null };
backupName =
(teamReady ? 'ledger-before-material-usage-v2-' : 'ledger-before-team-v1-') +
new Date().toISOString().replace(/[:.]/g, '-') +
'-' +
crypto.randomUUID().slice(0, 8) +
'.sqlite';
const directory = path.join(dataDir, 'backups');
fs.mkdirSync(directory, { recursive: true, mode: 0o700 });
const destination = path.join(directory, backupName);
await backup(source, destination);
fs.chmodSync(destination, 0o600);
const check = new DatabaseSync(destination, { readOnly: true });
try {
if (check.prepare('PRAGMA integrity_check').get().integrity_check !== 'ok')
throw new Error('三人台账升级前备份完整性检查失败');
} finally {
check.close();
}
return { required: true, backupName };
} finally {
source.close();
}
}
// 正式启动先备份再显式迁移,完成全部不变量核对后才能监听;createApp 保持同步的测试/嵌入入口。
async function prepareStartupMigrations(app) {
const status = app.ledger.materialPoolAllocationStatus();
if (!status.migrationRequired) return { changed: false, ...status };
let backupName = null;
if (status.usageCount) {
backupName =
'ledger-before-material-fifo-v' +
status.targetVersion +
'-' +
new Date().toISOString().replace(/[:.]/g, '-') +
'-' +
crypto.randomUUID().slice(0, 8) +
'.sqlite';
const destination = path.join(app.dataDir, 'backups', backupName);
await app.ledger.backupTo(destination);
if (!fs.statSync(destination).isFile() || !fs.statSync(destination).size)
throw new Error('日购料升级前备份未完整写入');
const check = new DatabaseSync(destination);
try {
check.exec('PRAGMA query_only=ON');
if (check.prepare('PRAGMA integrity_check').get().integrity_check !== 'ok')
throw new Error('日购料升级前备份完整性检查失败');
} finally {
check.close();
}
}
const actor = {
id: 'system-material-pool-fifo-v' + status.targetVersion,
name: '系统升级(日购料垫付FIFO v' + status.targetVersion + ')',
role: 'system',
};
return app.ledger.migrateMaterialPoolAllocation(actor, { backupName });
}
module.exports = { prepareTeamStartupDatabase, prepareStartupMigrations };
+139
View File
@@ -0,0 +1,139 @@
'use strict';
const test = require('node:test');
const assert = require('node:assert/strict');
const { createRouter } = require('../server/router');
const routes = require('../server/routes');
const router = createRouter(routes);
const U = '0123abcd-0000-4000-8000-0123456789ab';
const match = (method, path, accept) => router.match(method, path, accept);
const routeOf = (method, path) => match(method, path)?.route;
test('路由匹配器:重叠路径按声明顺序与参数约束区分', () => {
// 订单:售后与通用动作
assert.equal(routeOf('GET', `/api/orders/${U}/after-sale`).path, '/api/orders/:id(hexid)/after-sale');
assert.equal(routeOf('POST', `/api/orders/${U}/after-sale`), undefined, 'POST after-sale 无此路由,走未匹配 404');
const preview = routeOf('POST', `/api/orders/${U}/after-sale-preview`);
assert.equal(preview.path, '/api/orders/:id(hexid)/after-sale-preview');
assert.ok(!preview.write, '售后试算不进入事务');
assert.equal(routeOf('POST', `/api/orders/${U}/edit`).path, '/api/orders/:id(hexid)/edit');
assert.equal(routeOf('POST', `/api/orders/${U}/change`).path, '/api/orders/:id(hexid)/change');
assert.deepEqual(match('POST', `/api/orders/${U}/confirm`).params, { id: U, action: 'confirm' });
assert.equal(routeOf('POST', '/api/orders/issue').path, '/api/orders/issue');
assert.equal(routeOf('POST', `/api/orders/${U}`), undefined);
assert.equal(routeOf('GET', `/api/orders/${U}/unknown`), undefined);
// 打印页:回收专用页优先,其余(含非 UUID 的 recoveries/…、空编号)归通用订单打印
assert.equal(routeOf('GET', `/print/recoveries/${U}`).path, '/print/recoveries/:id(uuid)');
assert.deepEqual(match('GET', '/print/recoveries/abc').params, { id: 'recoveries/abc' });
assert.deepEqual(match('GET', '/print/').params, { id: '' });
assert.equal(routeOf('GET', '/print'), undefined);
// 购料:详情/编辑/删除允许宽松编号,申请修改要求 36 位
assert.equal(routeOf('GET', '/api/material-purchases/abc').path, '/api/material-purchases/:id(hexid)');
assert.equal(routeOf('POST', '/api/material-purchases/abc/edit').path, '/api/material-purchases/:id(hexid)/edit');
assert.equal(routeOf('POST', '/api/material-purchases/abc/change'), undefined);
assert.equal(routeOf('POST', `/api/material-purchases/${U}/change`).path, '/api/material-purchases/:id(uuid)/change');
assert.equal(routeOf('GET', `/api/material-purchases/${U}/change`), undefined);
// 日购料池:固定子路径与日期参数
assert.equal(routeOf('GET', '/api/material-pools/rolling-preview').path, '/api/material-pools/rolling-preview');
assert.equal(routeOf('GET', '/api/material-pools/2026-01-02').path, '/api/material-pools/:date(day)');
assert.equal(routeOf('GET', '/api/material-pools/2026-1-02'), undefined);
// 库存流水导出与流水详情
assert.equal(routeOf('GET', '/api/inventory/movements/export.xlsx').path, '/api/inventory/movements/export.xlsx');
assert.equal(routeOf('GET', '/api/inventory/movements/exportxxlsx'), undefined, '点号按字面匹配');
assert.equal(routeOf('GET', `/api/inventory/movements/${U}`).path, '/api/inventory/movements/:id(uuid)');
// 锁价
assert.equal(routeOf('GET', '/api/price-locks/abc/edit-context').path, '/api/price-locks/:id(hexid)/edit-context');
assert.equal(routeOf('POST', '/api/price-locks/abc/edit-context'), undefined);
// 售后与售后修改
assert.equal(routeOf('GET', '/api/after-sales/changes').path, '/api/after-sales/changes');
assert.equal(routeOf('GET', `/api/after-sales/${U}`).path, '/api/after-sales/:id(uuid)');
// 约束整体锚定
assert.equal(routeOf('GET', `/api/order-templates/${U}x`), undefined);
assert.equal(routeOf('GET', `/api/order-templates/${U.toUpperCase()}`), undefined);
// 货盘键与备份文件名原样传入(不解码)
assert.deepEqual(match('POST', '/api/pockets/%E7%8E%B0%E8%B4%A7/update').params, { key: '%E7%8E%B0%E8%B4%A7' });
assert.deepEqual(match('GET', '/api/backup/a/b').params, { filename: 'a/b' });
assert.equal(routeOf('GET', '/api/backup'), undefined);
assert.equal(routeOf('POST', '/api/backup/x'), undefined);
// 打印状态:GET 与 POST 共用路径,POST 自行读请求体
assert.ok(routeOf('POST', `/api/print-status/order/${U}`).direct);
assert.equal(routeOf('GET', `/api/print-status/other/${U}`), undefined);
// 演示登录只在演示模式启用
const demo = r => !r.when || r.when({ mode: 'demo' }),
trial = r => !r.when || r.when({ mode: 'trial' });
assert.equal(match('POST', '/api/demo-login', demo).route.auth, 'public');
assert.equal(match('POST', '/api/demo-login', trial), null);
// 请求方式必须一致
assert.equal(routeOf('POST', '/api/session'), undefined);
assert.equal(routeOf('GET', '/api/login'), undefined);
});
// 由 git show 2b9cb82:新账系统/server.js 中全部 owner(actor) 调用整理:[方法, 示例地址]。
const OWNER_ONLY = [
['POST', '/api/shop-settings'],
['POST', '/api/printing'],
['GET', '/api/employees'],
['POST', '/api/employees'],
...['update', 'deactivate', 'reactivate', 'delete'].flatMap(action => [
['GET', `/api/employees/staff_x/${action}`],
['POST', `/api/employees/staff_x/${action}`],
]),
['POST', '/api/pockets'],
['POST', '/api/pockets/pocket_x/update'],
['GET', '/api/team-funds'],
['GET', '/api/private-operations'],
['POST', '/api/private-operations'],
['GET', '/api/people-count'],
['POST', '/api/people-count'],
['GET', '/api/people-count-history'],
['POST', '/api/people-count-history'],
['GET', '/api/team-profits'],
['GET', '/api/team-funds/transfers'],
['POST', '/api/team-funds/transfers'],
['GET', '/api/team-funds/transfer'],
['POST', '/api/team-funds/transfer'],
['GET', '/api/material-pools/rolling-preview'],
['POST', '/api/team-members/assistant/password'],
['GET', '/api/export/inventory'],
['POST', '/api/backup'],
['GET', '/api/backup/ledger-2026-01-01T00-00-00-000Z.sqlite'],
['POST', '/api/sync'],
];
test('旧代码中的店主专用路由在路由表中均标记 role: owner', () => {
for (const [method, path] of OWNER_ONLY) {
const route = routeOf(method, path);
assert.ok(route, `${method} ${path} 缺少路由`);
assert.equal(route.role, 'owner', `${method} ${path} 应为店主专用`);
// 旧代码只有成员密码在事务内校验店主,其余都在读请求体之前。
assert.equal(
route.ownerCheck === 'transact',
path === '/api/team-members/assistant/password',
`${method} ${path} 店主校验时机`,
);
}
const owners = routes.filter(r => r.role === 'owner').length;
assert.equal(owners, OWNER_ONLY.length - 6, '路由表中的店主路由数与清单一致(员工动作 8 个示例合为 2 条路由)');
});
test('路由表没有重复的 方法 + 路径', () => {
const seen = new Set();
for (const { method, path } of routes) {
const key = method + ' ' + path;
assert.ok(!seen.has(key), '重复路由:' + key);
seen.add(key);
}
});
test('路由声明字段合法', () => {
for (const route of routes) {
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, 'owner'].includes(route.role), name);
if (route.write) assert.equal(route.method, 'POST', name);
if (route.direct) assert.ok(!route.write, name);
if (route.auth === 'public') assert.ok(!route.role && !route.write, name);
}
});