- 50个后端模块用git mv移入core/与domains/<领域>/,入口server.js、launch.js、restore.js及server/原位不动 - 所有require路径由脚本按新旧位置统一换算(后端、server/、测试) - 新增test/app-paths.test.js,锁定默认数据目录、public目录与飞书配置文件的绝对位置 - 维护与部署.md补充目录说明并更新模块路径 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
105 lines
4.8 KiB
JavaScript
105 lines
4.8 KiB
JavaScript
'use strict';
|
|
// 应用装配:配置校验、台账与账号初始化、飞书同步、自动盘点快照、备份,以及 HTTP 服务(路由表分发)。
|
|
const http = require('node:http');
|
|
const fs = require('node:fs');
|
|
const path = require('node:path');
|
|
const { Ledger, fail } = require('../core/ledger');
|
|
const { FeishuSync } = require('../core/sync');
|
|
const { InventorySnapshotScheduler } = require('../core/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('../core/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 };
|