路由表化:迁移登录/会话、报表/备份/同步路由,删除旧路由链,server.js 收为入口
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
d5c015f826
commit
2305900178
8 files changed
+632
-493
No files matched your search
@@ -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 };
|
||||
Reference in new issue
Block a user