2026-12-04 08:37:28 -08:00
|
|
|
|
#!/usr/bin/env node
|
|
|
|
|
|
'use strict';
|
|
|
|
|
|
// 旧库兼容检查:把用户本机旧账本快照复制到临时目录,按正式启动顺序
|
|
|
|
|
|
// (prepareTeamStartupDatabase → createApp → prepareStartupMigrations → listen)启动,
|
|
|
|
|
|
// 以三个成员身份读取主要接口,记录完整性、结构、行数、原始列内容哈希和规范化响应哈希。
|
|
|
|
|
|
// 基线只含计数与哈希,不含任何客户名称或金额。
|
|
|
|
|
|
// 用法:node e2e/legacy-db.js [--check] [--fixture <path>]
|
|
|
|
|
|
const fs = require('node:fs'),
|
|
|
|
|
|
os = require('node:os'),
|
|
|
|
|
|
path = require('node:path'),
|
|
|
|
|
|
crypto = require('node:crypto');
|
|
|
|
|
|
const { DatabaseSync } = require('node:sqlite');
|
|
|
|
|
|
const { startServer } = require('./lib/server');
|
|
|
|
|
|
const { Session } = require('./lib/client');
|
|
|
|
|
|
const { Normalizer } = require('./lib/normalize');
|
|
|
|
|
|
const { compare, report } = require('./lib/diff');
|
2026-12-05 19:39:07 -08:00
|
|
|
|
const ApprovedAuditIndex = require('./lib/approved-audit-index');
|
2026-12-04 08:37:28 -08:00
|
|
|
|
const args = process.argv.slice(2),
|
|
|
|
|
|
check = args.includes('--check');
|
|
|
|
|
|
const FIXTURE = args.includes('--fixture')
|
|
|
|
|
|
? args[args.indexOf('--fixture') + 1]
|
|
|
|
|
|
: '/tmp/refactor-fixtures/demo-ledger.sqlite';
|
|
|
|
|
|
const BASELINE = path.join(__dirname, 'baseline', 'legacy.json');
|
|
|
|
|
|
const CLOCK = '2026-12-05T02:00:00.000Z',
|
|
|
|
|
|
TODAY = '2026-12-05';
|
|
|
|
|
|
const sha = value => crypto.createHash('sha256').update(value).digest('hex');
|
|
|
|
|
|
function cell(v) {
|
|
|
|
|
|
return v instanceof Uint8Array
|
|
|
|
|
|
? { blob: Buffer.from(v).toString('hex') }
|
|
|
|
|
|
: typeof v === 'bigint'
|
|
|
|
|
|
? { bigint: v.toString() }
|
|
|
|
|
|
: v;
|
2026-12-04 08:58:53 -08:00
|
|
|
|
}
|
2026-12-04 08:37:28 -08:00
|
|
|
|
function inspect(file, originalColumns = null) {
|
|
|
|
|
|
const db = new DatabaseSync(file, { readOnly: true });
|
|
|
|
|
|
try {
|
|
|
|
|
|
const integrity = db
|
|
|
|
|
|
.prepare('PRAGMA integrity_check')
|
|
|
|
|
|
.all()
|
|
|
|
|
|
.map(r => r.integrity_check);
|
|
|
|
|
|
const tables = db.prepare("SELECT name,sql FROM sqlite_master WHERE type='table' ORDER BY name").all();
|
|
|
|
|
|
const schema = {},
|
|
|
|
|
|
counts = {},
|
|
|
|
|
|
hashes = {};
|
|
|
|
|
|
for (const { name, sql } of tables) {
|
|
|
|
|
|
const q = `"${name.replace(/"/g, '""')}"`;
|
|
|
|
|
|
const columns = db
|
|
|
|
|
|
.prepare(`PRAGMA table_info(${q})`)
|
|
|
|
|
|
.all()
|
|
|
|
|
|
.map(c => ({ name: c.name, type: c.type, notnull: c.notnull, pk: c.pk, dflt: c.dflt_value }));
|
|
|
|
|
|
const indexes = db
|
|
|
|
|
|
.prepare(`PRAGMA index_list(${q})`)
|
|
|
|
|
|
.all()
|
|
|
|
|
|
.filter(i => !i.name.startsWith('sqlite_autoindex_'))
|
|
|
|
|
|
.map(i => ({
|
|
|
|
|
|
name: i.name,
|
|
|
|
|
|
unique: i.unique,
|
|
|
|
|
|
columns: db
|
|
|
|
|
|
.prepare(`PRAGMA index_info("${i.name.replace(/"/g, '""')}")`)
|
|
|
|
|
|
.all()
|
|
|
|
|
|
.map(c => c.name),
|
|
|
|
|
|
}))
|
|
|
|
|
|
.sort((a, b) => (a.name < b.name ? -1 : 1));
|
|
|
|
|
|
schema[name] = { columns, indexes, withoutRowid: /WITHOUT\s+ROWID/i.test(sql || '') };
|
|
|
|
|
|
counts[name] = db.prepare(`SELECT COUNT(*) AS n FROM ${q}`).get().n;
|
|
|
|
|
|
// 只对“原始列”求内容哈希:升级新增的列不影响对照,原有列的任何改动都会被发现。
|
|
|
|
|
|
const cols = (originalColumns?.[name] ?? columns.map(c => c.name)).filter(c => columns.some(x => x.name === c));
|
|
|
|
|
|
if (originalColumns && !originalColumns[name]) continue;
|
|
|
|
|
|
const order = schema[name].withoutRowid ? cols.map((_, i) => i + 1).join(',') : 'rowid';
|
|
|
|
|
|
const rows = cols.length
|
|
|
|
|
|
? db
|
|
|
|
|
|
.prepare(`SELECT ${cols.map(c => `"${c.replace(/"/g, '""')}"`).join(',')} FROM ${q} ORDER BY ${order}`)
|
|
|
|
|
|
.all()
|
|
|
|
|
|
.map(r => cols.map(c => cell(r[c])))
|
|
|
|
|
|
: [];
|
|
|
|
|
|
hashes[name] = sha(JSON.stringify({ cols, rows }));
|
|
|
|
|
|
}
|
|
|
|
|
|
return { integrity, schema, counts, hashes };
|
|
|
|
|
|
} finally {
|
|
|
|
|
|
db.close();
|
2026-12-04 08:58:53 -08:00
|
|
|
|
}
|
2026-12-04 08:37:28 -08:00
|
|
|
|
}
|
|
|
|
|
|
const READS = [
|
|
|
|
|
|
'/api/session',
|
|
|
|
|
|
'/api/state',
|
|
|
|
|
|
`/api/order-book?from=2000-01-01&date=${TODAY}`,
|
|
|
|
|
|
`/api/report?from=2000-01-01&date=${TODAY}&basis=orderDate`,
|
|
|
|
|
|
`/api/report?date=${TODAY}`,
|
|
|
|
|
|
'/api/inventory',
|
|
|
|
|
|
'/api/inventory/movements',
|
|
|
|
|
|
'/api/inventory/snapshots',
|
|
|
|
|
|
'/api/material-pools',
|
|
|
|
|
|
'/api/price-locks?status=all',
|
|
|
|
|
|
'/api/recoveries',
|
|
|
|
|
|
'/api/customer-materials',
|
|
|
|
|
|
`/api/team-funds?date=${TODAY}`,
|
|
|
|
|
|
'/api/team-profits',
|
|
|
|
|
|
`/api/daily-funds?date=${TODAY}`,
|
|
|
|
|
|
'/api/shop-settings',
|
|
|
|
|
|
'/api/pockets',
|
|
|
|
|
|
'/api/order-templates',
|
|
|
|
|
|
'/api/reimbursements',
|
|
|
|
|
|
'/api/order-changes?status=all',
|
|
|
|
|
|
'/api/order-cancellations?status=all',
|
|
|
|
|
|
'/api/inventory/changes?status=all',
|
|
|
|
|
|
'/api/employees',
|
|
|
|
|
|
'/api/people-count-history',
|
|
|
|
|
|
];
|
|
|
|
|
|
async function run() {
|
|
|
|
|
|
if (!fs.existsSync(FIXTURE)) throw new Error('找不到旧库快照:' + FIXTURE);
|
|
|
|
|
|
const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'ledger-legacy-'));
|
|
|
|
|
|
try {
|
|
|
|
|
|
const file = path.join(dataDir, 'ledger.sqlite');
|
|
|
|
|
|
fs.copyFileSync(FIXTURE, file);
|
|
|
|
|
|
fs.chmodSync(file, 0o600);
|
|
|
|
|
|
const before = inspect(file);
|
|
|
|
|
|
const originalColumns = Object.fromEntries(
|
|
|
|
|
|
Object.entries(before.schema).map(([t, s]) => [t, s.columns.map(c => c.name)]),
|
|
|
|
|
|
);
|
|
|
|
|
|
const server = startServer({
|
|
|
|
|
|
mode: 'demo',
|
|
|
|
|
|
dataDir,
|
|
|
|
|
|
startup: 'production',
|
|
|
|
|
|
clockStart: CLOCK,
|
|
|
|
|
|
seed: 'legacy-seed',
|
|
|
|
|
|
});
|
|
|
|
|
|
const responses = {};
|
|
|
|
|
|
let startup;
|
|
|
|
|
|
try {
|
|
|
|
|
|
const info = await server.ready();
|
|
|
|
|
|
startup = info.startup;
|
|
|
|
|
|
const s = new Session({ base: info.base, server });
|
|
|
|
|
|
await s.day(TODAY);
|
|
|
|
|
|
const n = new Normalizer();
|
|
|
|
|
|
n.literal(info.base, 'http://<host>');
|
|
|
|
|
|
n.literal(info.base.slice(7), '<host>');
|
|
|
|
|
|
for (const [role, body] of [
|
|
|
|
|
|
['owner', { role: 'owner' }],
|
|
|
|
|
|
['assistant', { role: 'assistant' }],
|
|
|
|
|
|
['assistant2', { member: 'assistant2' }],
|
|
|
|
|
|
]) {
|
|
|
|
|
|
const login = await s.request(role, 'POST', '/api/demo-login', { body, expect: 'any' });
|
|
|
|
|
|
responses[role] = { login: login.status };
|
|
|
|
|
|
for (const route of READS) {
|
|
|
|
|
|
const r = await s.request(role, 'GET', route, { expect: 'any' });
|
|
|
|
|
|
const normalized = n.value(r.body);
|
|
|
|
|
|
responses[role][route] = {
|
|
|
|
|
|
status: r.status,
|
|
|
|
|
|
hash: sha(JSON.stringify(normalized)),
|
|
|
|
|
|
keys:
|
|
|
|
|
|
normalized && typeof normalized === 'object' && !Array.isArray(normalized)
|
|
|
|
|
|
? Object.keys(normalized).length
|
|
|
|
|
|
: null,
|
|
|
|
|
|
};
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
} finally {
|
|
|
|
|
|
await server.stop();
|
2026-12-04 08:58:53 -08:00
|
|
|
|
}
|
2026-12-04 08:37:28 -08:00
|
|
|
|
const after = inspect(file, originalColumns);
|
|
|
|
|
|
const afterAll = inspect(file);
|
|
|
|
|
|
const backups = fs.existsSync(path.join(dataDir, 'backups'))
|
|
|
|
|
|
? fs.readdirSync(path.join(dataDir, 'backups')).length
|
|
|
|
|
|
: 0;
|
|
|
|
|
|
return {
|
|
|
|
|
|
fixture: { sha256: sha(fs.readFileSync(FIXTURE)), bytes: fs.statSync(FIXTURE).size },
|
|
|
|
|
|
startup: {
|
|
|
|
|
|
teamBackupRequired: startup?.team?.required ?? null,
|
|
|
|
|
|
migrationChanged: startup?.migration?.changed ?? null,
|
|
|
|
|
|
backupFiles: backups,
|
|
|
|
|
|
},
|
|
|
|
|
|
before: { integrity: before.integrity, schema: before.schema, counts: before.counts, hashes: before.hashes },
|
|
|
|
|
|
after: {
|
|
|
|
|
|
integrity: after.integrity,
|
|
|
|
|
|
schema: afterAll.schema,
|
|
|
|
|
|
counts: afterAll.counts,
|
|
|
|
|
|
originalColumnHashes: after.hashes,
|
|
|
|
|
|
},
|
|
|
|
|
|
unchangedOriginalTables: Object.keys(before.hashes).filter(t => before.hashes[t] === after.hashes[t]).length,
|
|
|
|
|
|
changedOriginalTables: Object.keys(before.hashes).filter(t => before.hashes[t] !== after.hashes[t]),
|
|
|
|
|
|
responses,
|
2026-12-05 19:39:07 -08:00
|
|
|
|
...(check ? { auditIndex: ApprovedAuditIndex.inspect(file) } : {}),
|
2026-12-04 08:37:28 -08:00
|
|
|
|
};
|
|
|
|
|
|
} finally {
|
|
|
|
|
|
fs.rmSync(dataDir, { recursive: true, force: true });
|
2026-12-04 08:58:53 -08:00
|
|
|
|
}
|
2026-12-04 08:37:28 -08:00
|
|
|
|
}
|
|
|
|
|
|
(async () => {
|
|
|
|
|
|
const started = Date.now();
|
|
|
|
|
|
const result = await run();
|
|
|
|
|
|
const seconds = ((Date.now() - started) / 1000).toFixed(1);
|
|
|
|
|
|
const integrityOk = result.before.integrity.join() === 'ok' && result.after.integrity.join() === 'ok';
|
|
|
|
|
|
if (check) {
|
2026-12-05 19:39:07 -08:00
|
|
|
|
const frozen = JSON.parse(fs.readFileSync(BASELINE, 'utf8'));
|
|
|
|
|
|
const expected = {
|
|
|
|
|
|
...frozen,
|
|
|
|
|
|
before: { ...frozen.before, schema: ApprovedAuditIndex.expectedLegacySchema(frozen.before.schema) },
|
|
|
|
|
|
after: {
|
|
|
|
|
|
...frozen.after,
|
|
|
|
|
|
schema: ApprovedAuditIndex.expectedLegacySchema(frozen.after.schema, { afterStartup: true }),
|
|
|
|
|
|
},
|
|
|
|
|
|
auditIndex: ApprovedAuditIndex.definition,
|
|
|
|
|
|
};
|
2026-12-04 08:37:28 -08:00
|
|
|
|
const d = compare(expected, JSON.parse(JSON.stringify(result)));
|
|
|
|
|
|
const text = report('旧库兼容', d);
|
|
|
|
|
|
if (text) console.log(text);
|
|
|
|
|
|
const failed = d.diffs.length > 0 || !integrityOk;
|
|
|
|
|
|
if (!integrityOk) console.log('完整性检查失败:', result.before.integrity, result.after.integrity);
|
|
|
|
|
|
console.log(
|
|
|
|
|
|
`legacy ${failed ? 'FAIL' : 'PASS'}:${Object.keys(result.after.counts).length} 张表,${result.unchangedOriginalTables} 张原表内容未变,用时 ${seconds}s`,
|
|
|
|
|
|
);
|
|
|
|
|
|
process.exit(failed ? 1 : 0);
|
2026-12-04 08:58:53 -08:00
|
|
|
|
}
|
2026-12-04 08:37:28 -08:00
|
|
|
|
if (!integrityOk) {
|
|
|
|
|
|
console.error('完整性检查失败,拒绝写入基线');
|
|
|
|
|
|
process.exit(1);
|
|
|
|
|
|
}
|
|
|
|
|
|
fs.mkdirSync(path.dirname(BASELINE), { recursive: true });
|
|
|
|
|
|
fs.writeFileSync(BASELINE, JSON.stringify(result, null, 1) + '\n');
|
|
|
|
|
|
console.log(
|
|
|
|
|
|
`基线已写入 e2e/baseline/legacy.json(${Object.keys(result.after.counts).length} 张表,原表内容变化:${result.changedOriginalTables.join('、') || '无'},用时 ${seconds}s)`,
|
|
|
|
|
|
);
|
|
|
|
|
|
})().catch(error => {
|
|
|
|
|
|
console.error(error.stack || error);
|
|
|
|
|
|
process.exit(2);
|
|
|
|
|
|
});
|