561 lines
25 KiB
JavaScript
561 lines
25 KiB
JavaScript
'use strict';
|
||
const http = require('node:http');
|
||
const fs = require('node:fs');
|
||
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 PrintStatus = require('./print-status');
|
||
const OrderChanges = require('./order-changes');
|
||
const OrderNoteTags = require('./order-note-tags');
|
||
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) {
|
||
fs.mkdirSync(dataDir, { recursive: true, mode: 0o700 });
|
||
const lock = path.join(dataDir, 'server.lock');
|
||
if (fs.existsSync(lock)) {
|
||
const pid = Number(fs.readFileSync(lock, 'utf8'));
|
||
if (!Number.isSafeInteger(pid) || pid <= 0) throw new Error('运行锁内容异常,请维护者核对server.lock');
|
||
let alive = true;
|
||
try {
|
||
process.kill(pid, 0);
|
||
} catch (e) {
|
||
if (e.code === 'ESRCH') alive = false;
|
||
else throw e;
|
||
}
|
||
if (alive) throw new Error('这份数据库已有系统进程运行,请打开现有页面,不要启动第二个服务。');
|
||
fs.unlinkSync(lock);
|
||
}
|
||
fs.writeFileSync(lock, String(process.pid), { flag: 'wx', mode: 0o600 });
|
||
return () => {
|
||
try {
|
||
if (fs.readFileSync(lock, 'utf8') === String(process.pid)) fs.unlinkSync(lock);
|
||
} 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) {
|
||
let unlock, app;
|
||
(async () => {
|
||
try {
|
||
const mode = process.env.APP_MODE || 'trial',
|
||
dir = mode === 'production' ? process.env.DATA_DIR : path.join(__dirname, 'data', mode);
|
||
if (!dir) throw new Error('请配置持久化DATA_DIR');
|
||
unlock = acquireLock(dir);
|
||
process.on('exit', () => unlock?.());
|
||
await prepareTeamStartupDatabase(dir);
|
||
app = createApp();
|
||
await prepareStartupMigrations(app);
|
||
app.server.on('error', e => {
|
||
console.error(e.code === 'EADDRINUSE' ? '这个端口已在使用,请打开现有页面,或修改PORT再启动。' : e.message);
|
||
process.exitCode = 1;
|
||
app.ledger.close();
|
||
unlock?.();
|
||
});
|
||
app.server.listen(app.port, app.host, () => {
|
||
app.startTimers();
|
||
console.log(
|
||
`${ShopSettings.read(app.ledger).storeName} ${app.mode === 'production' ? '云端正式系统' : app.mode === 'demo' ? '演示练习(虚构数据)' : '本机试用(尚未云端上线)'}\n打开 http://${app.host}:${app.port}\n数据库目录:${app.dataDir}\n保持本窗口打开。按 Ctrl+C 停止。`,
|
||
);
|
||
});
|
||
process.on('SIGINT', () => {
|
||
app.stop();
|
||
process.exit(0);
|
||
});
|
||
process.on('SIGTERM', () => {
|
||
app.stop();
|
||
process.exit(0);
|
||
});
|
||
} catch (e) {
|
||
app?.ledger.close();
|
||
unlock?.();
|
||
console.error('启动失败:' + e.message);
|
||
process.exitCode = 1;
|
||
}
|
||
})();
|
||
}
|
||
module.exports = { createApp, createUser, demoSeed, acquireLock, prepareStartupMigrations, prepareTeamStartupDatabase };
|