2026-10-17 19:50:24 +08:00
|
|
|
|
'use strict';
|
|
|
|
|
|
const http = require('node:http');
|
|
|
|
|
|
const fs = require('node:fs');
|
|
|
|
|
|
const path = require('node:path');
|
|
|
|
|
|
const crypto = require('node:crypto');
|
2026-10-25 14:19:24 +08:00
|
|
|
|
const { DatabaseSync, backup } = require('node:sqlite');
|
|
|
|
|
|
const TeamMembers = require('./team-members');
|
2026-11-16 23:03:36 +08:00
|
|
|
|
const ShopSettings = require('./shop-settings');
|
2026-12-03 17:46:23 +08:00
|
|
|
|
const PrintStatus = require('./print-status');
|
2026-11-10 02:54:58 +08:00
|
|
|
|
const OrderChanges = require('./order-changes');
|
2026-11-30 15:40:40 +08:00
|
|
|
|
const OrderNoteTags = require('./order-note-tags');
|
2026-10-31 14:59:30 +08:00
|
|
|
|
const { inventoryMovementsFile } = require('./inventory-movements-export');
|
2026-11-08 03:30:58 +08:00
|
|
|
|
const { Ledger, ACCOUNTS, today, fail, text, owner } = require('./ledger');
|
2026-11-14 01:16:35 +08:00
|
|
|
|
const { receipt } = require('./printing');
|
2026-10-26 14:44:07 +08:00
|
|
|
|
const { recoveryCustomerPrintDocument, exchangeCustomerPrintDocument } = require('./recovery-printing');
|
2026-10-17 19:50:24 +08:00
|
|
|
|
const { FeishuSync } = require('./sync');
|
2026-10-26 22:46:55 +08:00
|
|
|
|
const { InventorySnapshotScheduler } = require('./inventory-snapshot-scheduler');
|
2026-12-04 12:26:22 -08:00
|
|
|
|
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);
|
2026-11-08 03:30:58 +08:00
|
|
|
|
function csvText(value) {
|
|
|
|
|
|
const text = String(value),
|
|
|
|
|
|
safe = /^[\s\u0000-\u001f]*[=+\-@]|^[\u0000-\u001f]/.test(text) ? "'" + text : text;
|
|
|
|
|
|
return '"' + safe.replace(/"/g, '""') + '"';
|
2026-10-25 14:19:24 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
2026-10-17 19:50:24 +08:00
|
|
|
|
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))
|
2026-12-04 08:58:53 -08:00
|
|
|
|
)
|
2026-10-17 19:50:24 +08:00
|
|
|
|
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'));
|
2026-10-25 14:19:24 +08:00
|
|
|
|
ledger.enableTeamMode();
|
2026-10-17 19:50:24 +08:00
|
|
|
|
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);
|
2026-12-04 00:53:53 +08:00
|
|
|
|
if (production && !ledger.one('SELECT id FROM users LIMIT 1') && process.env.SHOP_NAME) {
|
|
|
|
|
|
require('./new-shop').initialize(
|
|
|
|
|
|
ledger,
|
2026-12-04 08:58:53 -08:00
|
|
|
|
{
|
2026-12-04 00:53:53 +08:00
|
|
|
|
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,
|
|
|
|
|
|
);
|
|
|
|
|
|
}
|
2026-10-17 19:50:24 +08:00
|
|
|
|
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);
|
|
|
|
|
|
}
|
2026-10-25 14:19:24 +08:00
|
|
|
|
ensureTeamAccounts(ledger);
|
2026-10-24 16:09:45 +08:00
|
|
|
|
const sync = new FeishuSync(ledger, config, options.fetcher);
|
2026-10-26 22:46:55 +08:00
|
|
|
|
const automaticSnapshots = new InventorySnapshotScheduler(ledger, {
|
|
|
|
|
|
clock: options.clock,
|
|
|
|
|
|
logger: options.inventorySnapshotLogger,
|
|
|
|
|
|
...options.inventorySnapshotTimers,
|
|
|
|
|
|
});
|
2026-12-04 12:26:22 -08:00
|
|
|
|
const { user, session } = createSessions(ledger, { production });
|
|
|
|
|
|
const backupState = { last: null, error: null };
|
|
|
|
|
|
let backupBusy = false;
|
2026-10-17 19:50:24 +08:00
|
|
|
|
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);
|
2026-12-04 12:26:22 -08:00
|
|
|
|
backupState.last = { name, time: new Date().toISOString() };
|
|
|
|
|
|
backupState.error = null;
|
2026-10-17 19:50:24 +08:00
|
|
|
|
return { name, path: dest };
|
|
|
|
|
|
} catch (e) {
|
2026-12-04 12:26:22 -08:00
|
|
|
|
backupState.error = '备份失败,请检查磁盘空间与目录权限';
|
2026-10-17 19:50:24 +08:00
|
|
|
|
throw e;
|
|
|
|
|
|
} finally {
|
|
|
|
|
|
backupBusy = false;
|
2026-12-04 08:58:53 -08:00
|
|
|
|
}
|
|
|
|
|
|
}
|
2026-12-04 12:26:22 -08:00
|
|
|
|
const app = { mode, production, dataDir, ledger, sync, automaticSnapshots, doBackup, backupState, user, session };
|
2026-10-17 19:50:24 +08:00
|
|
|
|
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')
|
2026-12-04 08:58:53 -08:00
|
|
|
|
)
|
2026-10-17 19:50:24 +08:00
|
|
|
|
fail('请从系统页面提交操作', 403);
|
|
|
|
|
|
}
|
2026-12-04 02:45:54 +08:00
|
|
|
|
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 })),
|
|
|
|
|
|
});
|
2026-10-17 19:50:24 +08:00
|
|
|
|
if (route === '/api/setup' && isPost) {
|
|
|
|
|
|
if (production || mode === 'demo' || ledger.one('SELECT id FROM users LIMIT 1')) fail('初始化入口已关闭', 403);
|
|
|
|
|
|
const b = await read(req);
|
2026-10-25 14:19:24 +08:00
|
|
|
|
if (b.storeName !== undefined) {
|
2026-11-14 01:16:35 +08:00
|
|
|
|
const actor = require('./new-shop').initialize(ledger, b, createUser);
|
2026-10-25 14:19:24 +08:00
|
|
|
|
return send(res, 200, session(res, actor));
|
2026-12-04 08:58:53 -08:00
|
|
|
|
}
|
2026-12-04 02:45:54 +08:00
|
|
|
|
if (String(b.ownerPassword || '').length < 12 || String(b.assistantPassword || '').length < 12)
|
2026-10-17 19:50:24 +08:00
|
|
|
|
fail('两组密码都至少12个字符');
|
2026-11-03 01:15:41 +08:00
|
|
|
|
ledger.db.exec('BEGIN IMMEDIATE');
|
2026-12-04 08:58:53 -08:00
|
|
|
|
try {
|
2026-11-03 01:15:41 +08:00
|
|
|
|
createUser(ledger, '麦麦', 'owner', b.ownerPassword);
|
|
|
|
|
|
createUser(ledger, '助理', 'assistant', b.assistantPassword);
|
|
|
|
|
|
if (b.assistant2Password !== undefined) {
|
2026-10-25 14:19:24 +08:00
|
|
|
|
if (String(b.assistant2Password).length < 12) fail('小昊密码至少12个字符');
|
2026-11-03 01:15:41 +08:00
|
|
|
|
createUser(ledger, '助理2', 'assistant', b.assistant2Password, 'assistant2');
|
2026-12-04 08:58:53 -08:00
|
|
|
|
}
|
2026-10-25 14:19:24 +08:00
|
|
|
|
ensureTeamAccounts(ledger);
|
2026-11-03 01:15:41 +08:00
|
|
|
|
ledger.db.exec('COMMIT');
|
2026-12-04 08:58:53 -08:00
|
|
|
|
} catch (e) {
|
2026-11-03 01:15:41 +08:00
|
|
|
|
ledger.db.exec('ROLLBACK');
|
2026-12-04 08:58:53 -08:00
|
|
|
|
throw e;
|
|
|
|
|
|
}
|
2026-12-04 02:45:54 +08:00
|
|
|
|
return send(res, 200, session(res, ledger.one("SELECT id,name,role FROM users WHERE role='owner'")));
|
2026-12-04 08:58:53 -08:00
|
|
|
|
}
|
2026-10-17 19:50:24 +08:00
|
|
|
|
if (route === '/api/login' && isPost) {
|
|
|
|
|
|
const b = await read(req);
|
2026-12-04 08:58:53 -08:00
|
|
|
|
const u =
|
2026-12-04 02:45:54 +08:00
|
|
|
|
b.member !== undefined
|
|
|
|
|
|
? typeof b.member === 'string'
|
2026-10-25 14:19:24 +08:00
|
|
|
|
? ledger.one(
|
2026-12-04 02:45:54 +08:00
|
|
|
|
'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',
|
2026-10-17 19:50:24 +08:00
|
|
|
|
b.member,
|
2026-12-04 08:58:53 -08:00
|
|
|
|
)
|
|
|
|
|
|
: null
|
2026-12-04 00:53:53 +08:00
|
|
|
|
: ShopSettings.resolveLogin(ledger, b.name);
|
|
|
|
|
|
const pw = String(b.password || '');
|
|
|
|
|
|
const hash = derive(pw.slice(0, 500), u?.salt || 'dummy-salt');
|
2026-11-03 01:15:41 +08:00
|
|
|
|
if (
|
2026-12-04 08:58:53 -08:00
|
|
|
|
!u ||
|
2026-11-03 01:15:41 +08:00
|
|
|
|
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'))
|
2026-12-04 08:58:53 -08:00
|
|
|
|
)
|
2026-11-03 01:15:41 +08:00
|
|
|
|
fail('账号或密码不正确', 401);
|
2026-10-17 19:50:24 +08:00
|
|
|
|
return send(res, 200, session(res, u));
|
|
|
|
|
|
}
|
|
|
|
|
|
if (route === '/api/demo-login' && isPost && mode === 'demo') {
|
2026-10-24 16:09:45 +08:00
|
|
|
|
const b = await read(req),
|
2026-12-04 02:45:54 +08:00
|
|
|
|
member =
|
|
|
|
|
|
b.member ?? (b.role === 'assistant2' ? 'assistant2' : b.role === 'assistant' ? 'assistant' : 'owner');
|
|
|
|
|
|
if (!TeamMembers.isActive(ledger, member)) fail('演示成员无效');
|
|
|
|
|
|
return send(
|
2026-12-04 08:58:53 -08:00
|
|
|
|
res,
|
2026-12-04 02:45:54 +08:00
|
|
|
|
200,
|
|
|
|
|
|
session(
|
2026-12-04 08:58:53 -08:00
|
|
|
|
res,
|
2026-12-04 02:45:54 +08:00
|
|
|
|
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,
|
2026-10-25 14:19:24 +08:00
|
|
|
|
),
|
2026-12-04 08:58:53 -08:00
|
|
|
|
),
|
2026-10-25 14:19:24 +08:00
|
|
|
|
);
|
2026-10-17 19:50:24 +08:00
|
|
|
|
}
|
2026-10-25 14:19:24 +08:00
|
|
|
|
const actor = user(req);
|
|
|
|
|
|
const actorLedger = ledger.asActor(actor);
|
2026-10-17 19:50:24 +08:00
|
|
|
|
if (route.startsWith('/api/') || route.startsWith('/print/')) {
|
|
|
|
|
|
if (!actor) fail('请先登录', 401);
|
2026-10-29 00:27:36 +08:00
|
|
|
|
// 仅校验本次页面的原账号与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;
|
|
|
|
|
|
}
|
2026-12-04 12:26:22 -08:00
|
|
|
|
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,
|
|
|
|
|
|
});
|
2026-10-25 14:19:24 +08:00
|
|
|
|
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');
|
2026-11-14 01:16:35 +08:00
|
|
|
|
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),
|
2026-12-04 12:26:22 -08:00
|
|
|
|
backup: actor.role === 'owner' ? { last: backupState.last, error: backupState.error } : null,
|
2026-11-14 01:16:35 +08:00
|
|
|
|
movements: actorLedger.inventoryMovements({}, actor).movements,
|
2026-12-04 08:58:53 -08:00
|
|
|
|
});
|
|
|
|
|
|
}
|
2026-10-17 19:50:24 +08:00
|
|
|
|
if (route === '/api/report' && !isPost) {
|
2026-12-04 02:03:31 +08:00
|
|
|
|
const report = actorLedger.reportFor(Object.fromEntries(url.searchParams), actor);
|
|
|
|
|
|
if (actor.role !== 'owner') report.peopleCount = null;
|
|
|
|
|
|
return send(res, 200, report);
|
2026-10-17 19:50:24 +08:00
|
|
|
|
}
|
2026-11-08 15:47:07 +08:00
|
|
|
|
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 =>
|
2026-12-04 08:58:53 -08:00
|
|
|
|
[
|
2026-11-08 15:47:07 +08:00
|
|
|
|
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(','),
|
2026-12-04 08:58:53 -08:00
|
|
|
|
)
|
2026-11-08 15:47:07 +08:00
|
|
|
|
.join('\r\n'),
|
|
|
|
|
|
'text/csv; charset=utf-8',
|
|
|
|
|
|
);
|
|
|
|
|
|
}
|
2026-10-25 14:19:24 +08:00
|
|
|
|
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 });
|
|
|
|
|
|
}
|
2026-10-17 19:50:24 +08:00
|
|
|
|
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());
|
2026-12-04 08:58:53 -08:00
|
|
|
|
}
|
2026-10-17 19:50:24 +08:00
|
|
|
|
if (!isPost) fail('地址不存在', 404);
|
|
|
|
|
|
const b = await read(req);
|
|
|
|
|
|
const key = req.headers['idempotency-key'];
|
2026-11-14 01:16:35 +08:00
|
|
|
|
// 读取请求体期间账号可能已被停用或重置密码,写入前再次核验会话。
|
|
|
|
|
|
const checkedActor = user(req);
|
|
|
|
|
|
if (!checkedActor || checkedActor.id !== actor.id) fail('登录已失效,请重新登录', 401);
|
2026-10-25 14:19:24 +08:00
|
|
|
|
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 };
|
|
|
|
|
|
}
|
2026-10-17 19:50:24 +08:00
|
|
|
|
fail('地址不存在', 404);
|
2026-12-04 02:03:31 +08:00
|
|
|
|
},
|
2026-12-04 08:58:53 -08:00
|
|
|
|
{
|
2026-12-04 12:28:18 -08:00
|
|
|
|
syncTeamFunds: !['/api/password'].includes(route),
|
2026-12-04 08:58:53 -08:00
|
|
|
|
},
|
2026-12-04 02:03:31 +08:00
|
|
|
|
);
|
2026-12-04 12:28:18 -08:00
|
|
|
|
return send(res, 200, result);
|
2026-10-17 19:50:24 +08:00
|
|
|
|
}
|
2026-12-04 02:03:31 +08:00
|
|
|
|
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);
|
2026-10-17 19:50:24 +08:00
|
|
|
|
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',
|
|
|
|
|
|
);
|
2026-11-14 01:16:35 +08:00
|
|
|
|
} 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();
|
2026-12-04 08:58:53 -08:00
|
|
|
|
}
|
2026-10-17 19:50:24 +08:00
|
|
|
|
});
|
|
|
|
|
|
const timers = [];
|
2026-10-26 22:46:55 +08:00
|
|
|
|
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();
|
2026-12-04 08:58:53 -08:00
|
|
|
|
}
|
2026-10-26 22:46:55 +08:00
|
|
|
|
return { server, ledger, sync, automaticSnapshots, startTimers, stop, host, port, dataDir, mode, doBackup };
|
2026-10-17 19:50:24 +08:00
|
|
|
|
}
|
2026-10-25 14:19:24 +08:00
|
|
|
|
// 在 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 });
|
2026-12-04 09:02:52 -08:00
|
|
|
|
let required, backupName;
|
2026-10-25 14:19:24 +08:00
|
|
|
|
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();
|
2026-12-04 08:58:53 -08:00
|
|
|
|
}
|
2026-10-25 14:19:24 +08:00
|
|
|
|
return { required: true, backupName };
|
|
|
|
|
|
} finally {
|
|
|
|
|
|
source.close();
|
2026-12-04 08:58:53 -08:00
|
|
|
|
}
|
2026-10-25 14:19:24 +08:00
|
|
|
|
}
|
2026-10-17 19:50:24 +08:00
|
|
|
|
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;
|
2026-12-04 08:58:53 -08:00
|
|
|
|
}
|
2026-10-17 19:50:24 +08:00
|
|
|
|
if (alive) throw new Error('这份数据库已有系统进程运行,请打开现有页面,不要启动第二个服务。');
|
|
|
|
|
|
fs.unlinkSync(lock);
|
2026-12-04 08:58:53 -08:00
|
|
|
|
}
|
2026-10-17 19:50:24 +08:00
|
|
|
|
fs.writeFileSync(lock, String(process.pid), { flag: 'wx', mode: 0o600 });
|
|
|
|
|
|
return () => {
|
|
|
|
|
|
try {
|
|
|
|
|
|
if (fs.readFileSync(lock, 'utf8') === String(process.pid)) fs.unlinkSync(lock);
|
|
|
|
|
|
} catch {}
|
|
|
|
|
|
};
|
|
|
|
|
|
}
|
2026-10-23 00:14:29 +08:00
|
|
|
|
// 正式启动先备份再显式迁移,完成全部不变量核对后才能监听;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();
|
2026-12-04 08:58:53 -08:00
|
|
|
|
}
|
2026-10-23 00:14:29 +08:00
|
|
|
|
}
|
|
|
|
|
|
const actor = {
|
|
|
|
|
|
id: 'system-material-pool-fifo-v' + status.targetVersion,
|
|
|
|
|
|
name: '系统升级(日购料垫付FIFO v' + status.targetVersion + ')',
|
|
|
|
|
|
role: 'system',
|
|
|
|
|
|
};
|
|
|
|
|
|
return app.ledger.migrateMaterialPoolAllocation(actor, { backupName });
|
|
|
|
|
|
}
|
2026-10-17 19:50:24 +08:00
|
|
|
|
if (require.main === module) {
|
2026-10-23 00:14:29 +08:00
|
|
|
|
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');
|
2026-10-25 14:19:24 +08:00
|
|
|
|
unlock = acquireLock(dir);
|
|
|
|
|
|
process.on('exit', () => unlock?.());
|
|
|
|
|
|
await prepareTeamStartupDatabase(dir);
|
|
|
|
|
|
app = createApp();
|
2026-10-23 00:14:29 +08:00
|
|
|
|
await prepareStartupMigrations(app);
|
|
|
|
|
|
app.server.on('error', e => {
|
|
|
|
|
|
console.error(e.code === 'EADDRINUSE' ? '这个端口已在使用,请打开现有页面,或修改PORT再启动。' : e.message);
|
|
|
|
|
|
process.exitCode = 1;
|
|
|
|
|
|
app.ledger.close();
|
|
|
|
|
|
unlock?.();
|
2026-11-14 01:16:35 +08:00
|
|
|
|
});
|
|
|
|
|
|
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 停止。`,
|
|
|
|
|
|
);
|
2026-10-23 00:14:29 +08:00
|
|
|
|
});
|
|
|
|
|
|
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;
|
2026-12-04 08:58:53 -08:00
|
|
|
|
}
|
2026-10-23 00:14:29 +08:00
|
|
|
|
})();
|
2026-10-17 19:50:24 +08:00
|
|
|
|
}
|
2026-10-25 14:19:24 +08:00
|
|
|
|
module.exports = { createApp, createUser, demoSeed, acquireLock, prepareStartupMigrations, prepareTeamStartupDatabase };
|