目录重组:后端按core/domains分领域存放(仅移动与更新引用)

- 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>
This commit is contained in:
黄健铭andClaude Opus 5.5 committed 2026-12-04 13:01:19 -08:00
1 parent 95c481c74a
commit 9ec37196d4
172 files changed
+458 -384

No files matched your search

@@ -0,0 +1,113 @@
'use strict';
const { today, AUTOMATIC_SNAPSHOT_LAST_SUCCESS, automaticSnapshotKey } = require('./ledger');
const TIME_ZONE = 'Asia/Shanghai',
DAILY_TIME = '23:50',
RETRY_MS = 60000;
const recordDTO = value =>
value && typeof value.date === 'string' && typeof value.scheduledFor === 'string' && typeof value.savedAt === 'string'
? { date: value.date, scheduledFor: value.scheduledFor, savedAt: value.savedAt }
: null;
class InventorySnapshotScheduler {
constructor(
ledger,
{ clock = () => new Date(), logger = console.error, setTimer = setTimeout, clearTimer = clearTimeout } = {},
) {
this.ledger = ledger;
this.clock = clock;
this.logger = logger;
this.setTimer = setTimer;
this.clearTimer = clearTimer;
this.running = false;
this.busy = false;
this.timer = null;
this.lastError = null;
this.retry = null;
}
moment() {
const actual = new Date(this.clock());
if (!Number.isFinite(actual.getTime())) throw new Error('自动库存快照时钟无效');
const date = today(actual),
scheduledFor = date + 'T' + DAILY_TIME + ':00+08:00';
return { actual, date, scheduledFor, dueAt: Date.parse(scheduledFor) };
}
start() {
if (this.running) return false;
this.running = true;
this.tick();
this.arm();
return true;
}
stop() {
this.running = false;
if (this.timer !== null) this.clearTimer(this.timer);
this.timer = null;
}
arm() {
if (!this.running || this.timer !== null) return;
const { actual, dueAt, date } = this.moment(),
retryAt = this.retry?.date === date ? this.retry.at : null;
const target =
actual.getTime() < dueAt ? dueAt : retryAt && retryAt > actual.getTime() ? retryAt : actual.getTime() + RETRY_MS;
this.timer = this.setTimer(
() => {
this.timer = null;
this.tick();
this.arm();
},
Math.min(RETRY_MS, Math.max(1, target - actual.getTime())),
);
this.timer?.unref?.();
}
tick() {
if (!this.running || this.busy) return { saved: false, reason: 'stopped-or-busy' };
const { actual, date, dueAt } = this.moment(),
instant = actual.getTime();
if (instant < dueAt) return { saved: false, reason: 'not-due' };
if (this.retry?.date === date && instant < this.retry.at) return { saved: false, reason: 'retry-wait' };
this.busy = true;
try {
const result = this.ledger.saveAutomaticInventorySnapshot(date, this.clock);
this.lastError = null;
this.retry = null;
return result;
} catch (error) {
const failedAt = new Date(this.clock());
this.lastError = {
date,
attemptedAt: failedAt.toISOString(),
message: '自动库存快照保存失败,请检查磁盘空间或目录权限;系统会在当日每分钟重试。',
};
this.retry = { date, at: failedAt.getTime() + RETRY_MS };
try {
this.logger(`自动库存快照保存失败(${date},${error.code || '保存未完成'}),当日每分钟重试。`);
} catch {}
return { saved: false, reason: 'failed' };
} finally {
this.busy = false;
}
}
status() {
const { actual, date, dueAt } = this.moment(),
completed = recordDTO(this.ledger.meta(automaticSnapshotKey(date))),
lastSuccess = recordDTO(this.ledger.meta(AUTOMATIC_SNAPSHOT_LAST_SUCCESS));
const lastError = !completed && this.lastError?.date === date ? { ...this.lastError } : null;
let nextAttemptAt = null;
if (this.running && !completed) {
const target = actual.getTime() < dueAt ? dueAt : this.retry?.date === date ? this.retry.at : actual.getTime();
// 跨过午夜就等待新一天,不能把第二天的重试伪装成前一天的定时快照。
if (today(new Date(target)) === date) nextAttemptAt = new Date(target).toISOString();
}
return {
enabled: this.running,
time: DAILY_TIME,
timeZone: TIME_ZONE,
date,
status: !this.running ? 'stopped' : completed ? 'saved' : lastError ? 'failed' : 'waiting',
lastSuccess,
lastError,
nextAttemptAt,
};
}
}
module.exports = { InventorySnapshotScheduler, TIME_ZONE, DAILY_TIME, RETRY_MS };
File diff suppressed because it is too large. Load diff
+46
View File
@@ -0,0 +1,46 @@
'use strict';
// 成员名单属于业务数据,不能由旧表的三人枚举锁死。仅去除指定枚举,逐值保留原记录。
function removeMemberCheck(ledger, table, column) {
const row = ledger.one("SELECT sql FROM sqlite_master WHERE type='table' AND name=?", table);
if (!row) return false;
const pattern = new RegExp(
'\\s+CHECK\\s*\\(\\s*' +
column +
"\\s+IN\\s*\\(\\s*'owner'\\s*,\\s*'assistant'(?:\\s*,\\s*'assistant2')?\\s*\\)\\s*\\)",
'ig',
);
const clean = row.sql.replace(pattern, '');
if (clean === row.sql) return false;
if (ledger.db.isTransaction) throw new Error('成员表结构升级须在启动阶段完成');
const foreignKeys = ledger.one('PRAGMA foreign_keys').foreign_keys,
temp = table + '_members_upgrade';
const support = ledger.rows(
"SELECT sql FROM sqlite_master WHERE tbl_name=? AND type IN ('index','trigger') AND sql IS NOT NULL ORDER BY type,name",
table,
);
if (foreignKeys) ledger.db.exec('PRAGMA foreign_keys=OFF');
try {
ledger.db.exec('BEGIN IMMEDIATE');
const create = clean.replace(
new RegExp('CREATE TABLE\\s+(?:"' + table + '"|' + table + ')', 'i'),
'CREATE TABLE ' + temp,
);
ledger.db.exec(create);
const columns = ledger
.rows('PRAGMA table_info(' + table + ')')
.map(row => '"' + row.name + '"')
.join(',');
ledger.db.exec('INSERT INTO ' + temp + '(rowid,' + columns + ') SELECT rowid,' + columns + ' FROM ' + table);
ledger.db.exec('DROP TABLE ' + table + ';ALTER TABLE ' + temp + ' RENAME TO ' + table);
for (const item of support) ledger.db.exec(item.sql);
if (ledger.rows('PRAGMA foreign_key_check').length) throw new Error('成员表升级关联核对失败,已回滚');
ledger.db.exec('COMMIT');
} catch (error) {
if (ledger.db.isTransaction) ledger.db.exec('ROLLBACK');
throw error;
} finally {
if (foreignKeys) ledger.db.exec('PRAGMA foreign_keys=ON');
}
return true;
}
module.exports = { removeMemberCheck };
+42
View File
@@ -0,0 +1,42 @@
'use strict';
// 仅供没有账号和业务的新账本初始化;已有店铺通过配置和员工管理维护。
const Settings = require('../domains/team/shop-settings');
function initialize(ledger, input, createUser) {
if (
ledger.one('SELECT id FROM users LIMIT 1') ||
ledger.one('SELECT id FROM orders LIMIT 1') ||
ledger.one('SELECT id FROM movements LIMIT 1')
)
throw new Error('已有账本不能重新初始化店铺');
const storeName = Settings.string(input.storeName, '店铺名称', 80),
label = Settings.string(input.ownerLabel, '店主显示名', 30),
loginName = Settings.string(input.ownerLoginName, '店主登录名', 60, { login: true });
if (typeof input.ownerPassword !== 'string' || input.ownerPassword.length < 12 || input.ownerPassword.length > 500)
throw new Error('店主密码须为12~500个字符');
ledger.db.exec('SAVEPOINT new_shop');
try {
// 空账本不强制创建两个助理,更不把其他店的姓名带入新店。
ledger.run("DELETE FROM team_members WHERE member<>'owner'");
createUser(ledger, loginName, 'owner', input.ownerPassword, 'owner');
const actor = ledger.one("SELECT id,name,role FROM users WHERE role='owner'");
ledger.setMeta('team-accounts-initialized-v1', { version: 1 });
const config = Settings.read(ledger);
Settings.update(
ledger,
{
revision: config.revision,
storeName,
costPresets: Object.fromEntries(Object.keys(config.costPresets).map(key => [key, null])),
members: [{ member: 'owner', label, loginName }],
},
actor,
);
ledger.db.exec('RELEASE new_shop');
return actor;
} catch (error) {
ledger.db.exec('ROLLBACK TO new_shop');
ledger.db.exec('RELEASE new_shop');
throw error;
}
}
module.exports = { initialize };
+177
View File
@@ -0,0 +1,177 @@
'use strict';
// 飞书是单向查看副本。默认未启用;只连接显式配置的新账专用表。
const { now } = require('./ledger');
const TABLE_NAME = '新账_系统镜像';
const FIELDS = [
['系统键', 1],
['类型', 1],
['单号', 1],
['状态', 1],
['日期', 1],
['销售金额', 2],
['订单利润', 2],
['已收净额', 2],
['待结算', 2],
['数据版本', 2],
['明细', 1],
];
class FeishuSync {
constructor(ledger, config, fetcher = fetch) {
this.ledger = ledger;
this.config = config;
this.fetcher = fetcher;
this.busy = false;
this.checked = false;
this.token = null;
this.expires = 0;
}
get enabled() {
return !!(
this.config?.enabled &&
this.config.appId &&
this.config.appSecret &&
this.config.baseToken &&
this.config.tableId
);
}
async request(method, route, body) {
const r = await this.fetcher('https://open.feishu.cn/open-apis/' + route, {
method,
headers: { 'Content-Type': 'application/json', ...(this.token ? { Authorization: 'Bearer ' + this.token } : {}) },
...(body ? { body: JSON.stringify(body) } : {}),
signal: AbortSignal.timeout(20000),
});
const data = await r.json();
if (!r.ok || data.code !== 0)
throw new Error(
`飞书请求失败(${data.code ?? r.status}):${String(data.msg || '请检查网络和应用权限').slice(0, 180)}`,
);
return data;
}
async auth() {
if (this.token && Date.now() < this.expires) return;
const d = await this.request('POST', 'auth/v3/tenant_access_token/internal', {
app_id: this.config.appId,
app_secret: this.config.appSecret,
});
this.token = d.tenant_access_token;
this.expires = Date.now() + Math.max(60, (d.expire || 7200) - 120) * 1000;
}
get route() {
return `bitable/v1/apps/${encodeURIComponent(this.config.baseToken)}/tables/${encodeURIComponent(this.config.tableId)}`;
}
async validate() {
if (this.checked) return;
await this.auth();
// 防止把旧账表当作同步目标。表名和字段都核实后才允许写。
let found = false,
token = '';
do {
const d = await this.request(
'GET',
`bitable/v1/apps/${encodeURIComponent(this.config.baseToken)}/tables?page_size=100${token ? '&page_token=' + encodeURIComponent(token) : ''}`,
);
found ||= d.data.items.some(t => t.table_id === this.config.tableId && t.name === TABLE_NAME);
token = d.data.has_more ? d.data.page_token : '';
if (d.data.has_more && !token) throw new Error('飞书表分页缺失');
} while (token);
if (!found) throw new Error(`只允许同步到专用表「${TABLE_NAME}」,请先建立新表,不使用旧销售表`);
const d = await this.request('GET', this.route + '/fields?page_size=100');
if (d.data.has_more) throw new Error('同步表字段超过预期,请检查专用表');
for (const [name, type] of FIELDS)
if (!d.data.items.some(f => f.field_name === name && f.type === type))
throw new Error(`同步表缺少正确类型字段:${name}`);
this.checked = true;
}
async find(entity) {
const d = await this.request('POST', this.route + '/records/search?page_size=100', {
filter: { conjunction: 'and', conditions: [{ field_name: '系统键', operator: 'is', value: [entity] }] },
});
if (d.data.has_more || d.data.items.length > 1) throw new Error('同步键存在重复记录,已停止覆盖,请维护者核对');
return d.data.items[0] || null;
}
fields(entity, revision) {
if (entity === 'inventory')
return {
系统键: entity,
类型: '库存快照',
单号: '',
状态: '从主账流水重算',
日期: now().slice(0, 10),
销售金额: 0,
订单利润: 0,
已收净额: 0,
待结算: 0,
数据版本: revision,
明细: JSON.stringify(this.ledger.inventory()),
};
const o = this.ledger.detail(entity.slice(6));
const { audit, sync, ...details } = o;
return {
系统键: entity,
类型: o.recovery_id ? '置换订单' : '订单',
单号: o.number,
状态: o.status,
日期: o.date,
销售金额: o.cancellationApproved ? 0 : o.total / 100,
订单利润: o.profit / 100,
已收净额: o.netReceived / 100,
待结算: o.settlementDue / 100,
数据版本: revision,
明细: JSON.stringify(details),
};
}
async tick() {
if (!this.enabled || this.busy) return;
this.busy = true;
try {
await this.validate();
for (const job of this.ledger.rows(
'SELECT * FROM sync WHERE revision<>done_revision ORDER BY updated LIMIT 10',
)) {
try {
await this.auth();
const fields = this.fields(job.entity, job.revision);
if (JSON.stringify(fields).length > 90000)
throw new Error('订单明细超过同步大小,请在主系统查看,需维护者拆分镜像');
// 每次重试先查询稳定键。写请求超时后不盲目再创建;一个服务只跑一个同步工人。
const existing = await this.find(job.entity);
let recordId = existing?.record_id;
if (recordId) await this.request('PUT', this.route + '/records/' + encodeURIComponent(recordId), { fields });
else recordId = (await this.request('POST', this.route + '/records', { fields })).data.record.record_id;
const check = (await this.request('GET', this.route + '/records/' + encodeURIComponent(recordId))).data
.record;
if (check.fields['数据版本'] !== job.revision || check.fields['明细'] !== fields['明细'])
throw new Error('写后回读不一致,保留待同步状态');
this.ledger.run(
'UPDATE sync SET done_revision=?,record_id=?,error=NULL,attempts=0 WHERE entity=?',
job.revision,
recordId,
job.entity,
);
} catch (e) {
this.ledger.run(
'UPDATE sync SET error=?,attempts=attempts+1 WHERE entity=?',
String(e.message).slice(0, 300),
job.entity,
);
}
}
this.lastError = null;
} catch (e) {
this.lastError = String(e.message).slice(0, 300);
} finally {
this.busy = false;
}
}
status() {
return {
enabled: this.enabled,
busy: this.busy,
error: this.lastError || null,
pending: this.ledger.one('SELECT COUNT(*) AS n FROM sync WHERE revision<>done_revision').n,
failed: this.ledger.one('SELECT COUNT(*) AS n FROM sync WHERE error IS NOT NULL').n,
};
}
}
module.exports = { FeishuSync, FIELDS, TABLE_NAME };
+125
View File
@@ -0,0 +1,125 @@
'use strict';
// 仅生成一个文本/数值工作表;用Node内置ZIP压缩,不执行公式或嵌入外部链接。
const { deflateRawSync } = require('node:zlib');
const crcTable = Uint32Array.from({ length: 256 }, (_, value) => {
for (let bit = 0; bit < 8; bit++) value = value & 1 ? 0xedb88320 ^ (value >>> 1) : value >>> 1;
return value >>> 0;
});
function crc32(buffer) {
let crc = 0xffffffff;
for (const byte of buffer) crc = crcTable[(crc ^ byte) & 255] ^ (crc >>> 8);
return (crc ^ 0xffffffff) >>> 0;
}
function xml(value) {
return [...String(value ?? '')]
.filter(char => {
const n = char.codePointAt(0);
return (
n === 9 ||
n === 10 ||
n === 13 ||
(n >= 32 && n <= 0xd7ff) ||
(n >= 0xe000 && n <= 0xfffd) ||
(n >= 0x10000 && n <= 0x10ffff)
);
})
.join('')
.slice(0, 32767)
.replace(/[&<>"']/g, char => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&apos;' })[char]);
}
function zip(files) {
const locals = [],
directory = [];
let offset = 0;
for (const [filename, value] of Object.entries(files)) {
const name = Buffer.from(filename),
data = Buffer.from(value),
compressed = deflateRawSync(data),
crc = crc32(data),
local = Buffer.alloc(30),
central = Buffer.alloc(46);
local.writeUInt32LE(0x04034b50, 0);
local.writeUInt16LE(20, 4);
local.writeUInt16LE(0x800, 6);
local.writeUInt16LE(8, 8);
local.writeUInt16LE(33, 12);
local.writeUInt32LE(crc, 14);
local.writeUInt32LE(compressed.length, 18);
local.writeUInt32LE(data.length, 22);
local.writeUInt16LE(name.length, 26);
central.writeUInt32LE(0x02014b50, 0);
central.writeUInt16LE(20, 4);
central.writeUInt16LE(20, 6);
central.writeUInt16LE(0x800, 8);
central.writeUInt16LE(8, 10);
central.writeUInt16LE(33, 14);
central.writeUInt32LE(crc, 16);
central.writeUInt32LE(compressed.length, 20);
central.writeUInt32LE(data.length, 24);
central.writeUInt16LE(name.length, 28);
central.writeUInt32LE(offset, 42);
locals.push(local, name, compressed);
directory.push(central, name);
offset += local.length + name.length + compressed.length;
}
const index = Buffer.concat(directory),
end = Buffer.alloc(22),
count = Object.keys(files).length;
end.writeUInt32LE(0x06054b50, 0);
end.writeUInt16LE(count, 8);
end.writeUInt16LE(count, 10);
end.writeUInt32LE(index.length, 12);
end.writeUInt32LE(offset, 16);
return Buffer.concat([...locals, index, end]);
}
function workbook(
rows,
{
sheetName = '库存流水',
widths = [8, 14, 16, 18, 20, 48, 18, 24, 30],
numericColumns = [0, 3],
optionalNumericColumns = [],
} = {},
) {
if (rows.length > 1048576) throw new Error('超过Excel单表行数上限,请缩小筛选范围');
const column = index => {
let name = '';
for (index++; index; index = Math.floor((index - 1) / 26))
name = String.fromCharCode(65 + ((index - 1) % 26)) + name;
return name;
};
const cells = rows
.map(
(row, index) =>
`<row r="${index + 1}">${row
.map((value, col) => {
const ref = column(col) + (index + 1);
if (
index &&
(numericColumns.includes(col) || (optionalNumericColumns.includes(col) && typeof value === 'number'))
) {
if (typeof value !== 'number' || !Number.isFinite(value)) throw new Error('导出数值无效');
return `<c r="${ref}" s="${col === 3 ? 2 : 0}" t="n"><v>${value}</v></c>`;
}
return `<c r="${ref}"${index ? '' : ' s="1"'} t="inlineStr"><is><t xml:space="preserve">${xml(value)}</t></is></c>`;
})
.join('')}</row>`,
)
.join('');
const lastColumn = column(rows.reduce((max, row) => Math.max(max, row.length), 1) - 1),
range = `A1:${lastColumn}${rows.length}`;
const sheet = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?><worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><dimension ref="${range}"/><sheetViews><sheetView workbookViewId="0"><pane ySplit="1" topLeftCell="A2" activePane="bottomLeft" state="frozen"/></sheetView></sheetViews><cols>${widths.map((width, index) => `<col min="${index + 1}" max="${index + 1}" width="${width}" customWidth="1"/>`).join('')}</cols><sheetData>${cells}</sheetData><autoFilter ref="${range}"/></worksheet>`;
return zip({
'[Content_Types].xml':
'<?xml version="1.0" encoding="UTF-8"?><Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="xml" ContentType="application/xml"/><Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/><Override PartName="/xl/worksheets/sheet1.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/><Override PartName="/xl/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml"/></Types>',
'_rels/.rels':
'<?xml version="1.0" encoding="UTF-8"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="xl/workbook.xml"/></Relationships>',
'xl/workbook.xml': `<?xml version="1.0" encoding="UTF-8"?><workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><sheets><sheet name="${xml(sheetName)}" sheetId="1" r:id="rId1"/></sheets></workbook>`,
'xl/_rels/workbook.xml.rels':
'<?xml version="1.0" encoding="UTF-8"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet1.xml"/><Relationship Id="rId2" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/></Relationships>',
'xl/styles.xml':
'<?xml version="1.0" encoding="UTF-8"?><styleSheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><numFmts count="1"><numFmt numFmtId="164" formatCode="+0.000;-0.000;0.000"/></numFmts><fonts count="2"><font><sz val="11"/><name val="等线"/></font><font><b/><sz val="11"/><name val="等线"/></font></fonts><fills count="2"><fill><patternFill patternType="none"/></fill><fill><patternFill patternType="gray125"/></fill></fills><borders count="1"><border/></borders><cellStyleXfs count="1"><xf numFmtId="0" fontId="0" fillId="0" borderId="0"/></cellStyleXfs><cellXfs count="3"><xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0"/><xf numFmtId="0" fontId="1" fillId="0" borderId="0" xfId="0" applyFont="1"/><xf numFmtId="164" fontId="0" fillId="0" borderId="0" xfId="0" applyNumberFormat="1"/></cellXfs><cellStyles count="1"><cellStyle name="Normal" xfId="0" builtinId="0"/></cellStyles></styleSheet>',
'xl/worksheets/sheet1.xml': sheet,
});
}
module.exports = { workbook };