import fs from 'node:fs'; import os from 'node:os'; import path from 'node:path'; import crypto from 'node:crypto'; import { DatabaseSync } from 'node:sqlite'; /** * Load history in SQLite - the ONLY module that talks to the database. * node:sqlite is marked experimental, so an API change must touch one file. * * The database is derived data: the CSV files in DATA_DIR stay the single * source of truth, and the DB can always be deleted and rebuilt by rereading * them. Hence the resilience contract: any DB failure is logged and swallowed, * recordLoad() never throws and never touches the in-memory data - the panel * must keep working with the DB missing, corrupted or locked. * * Facts are stored in long form (one row = one observation: period, org, * metric, value), so a new metric in a customer file means new rows, not a * schema migration. Exceptions where wide form is objectively better: * taxes (a column set fixed by tax law plus per-row reference attributes) * and the companies / budget-levels reference tables. * * To keep the DB small, facts are rewritten only when a file's content * actually changed (content hash differs); otherwise load_files.facts_load_id * points at the load whose fact rows are still current for this dataset. */ const MIGRATIONS = [ { version: 1, sql: ` CREATE TABLE loads ( id INTEGER PRIMARY KEY AUTOINCREMENT, loaded_at TEXT NOT NULL, reason TEXT NOT NULL, data_dir TEXT NOT NULL, source_label TEXT, duration_ms INTEGER NOT NULL, files_found INTEGER NOT NULL, files_total INTEGER NOT NULL, rows_total INTEGER NOT NULL, warnings INTEGER NOT NULL, errors INTEGER NOT NULL, rejects INTEGER NOT NULL ); CREATE TABLE load_files ( id INTEGER PRIMARY KEY AUTOINCREMENT, load_id INTEGER NOT NULL REFERENCES loads(id), dataset TEXT NOT NULL, file TEXT NOT NULL, found INTEGER NOT NULL, stale INTEGER NOT NULL, rows_read INTEGER NOT NULL, rows_accepted INTEGER NOT NULL, rows_rejected INTEGER NOT NULL, size INTEGER, file_mtime TEXT, content_hash TEXT, facts_load_id INTEGER ); CREATE INDEX idx_load_files_load ON load_files(load_id); CREATE TABLE load_warnings ( id INTEGER PRIMARY KEY AUTOINCREMENT, load_id INTEGER NOT NULL REFERENCES loads(id), file TEXT NOT NULL, code TEXT NOT NULL, message TEXT NOT NULL ); CREATE TABLE load_errors ( id INTEGER PRIMARY KEY AUTOINCREMENT, load_id INTEGER NOT NULL REFERENCES loads(id), file TEXT NOT NULL, message TEXT NOT NULL ); CREATE TABLE load_rejects ( id INTEGER PRIMARY KEY AUTOINCREMENT, load_id INTEGER NOT NULL REFERENCES loads(id), file TEXT NOT NULL, reason TEXT NOT NULL, raw TEXT NOT NULL ); CREATE TABLE facts ( id INTEGER PRIMARY KEY AUTOINCREMENT, load_id INTEGER NOT NULL REFERENCES loads(id), dataset TEXT NOT NULL, period TEXT NOT NULL, org TEXT NOT NULL, metric TEXT NOT NULL, scenario TEXT, value REAL, note TEXT ); CREATE INDEX idx_facts_dataset_load ON facts(dataset, load_id); CREATE TABLE companies ( id INTEGER PRIMARY KEY AUTOINCREMENT, load_id INTEGER NOT NULL REFERENCES loads(id), name TEXT NOT NULL, short_name TEXT, inn TEXT, activity TEXT, geography TEXT, region TEXT, region_short TEXT, division TEXT, site TEXT, type TEXT, synonyms TEXT ); CREATE INDEX idx_companies_load ON companies(load_id); CREATE TABLE taxes ( id INTEGER PRIMARY KEY AUTOINCREMENT, load_id INTEGER NOT NULL REFERENCES loads(id), quarter TEXT NOT NULL, org TEXT NOT NULL, inn TEXT, activity TEXT, geography TEXT, region TEXT, regional_budget TEXT, vat REAL, profit_federal REAL, profit_regional REAL, insurance REAL, property REAL, land REAL, transport REAL ); CREATE INDEX idx_taxes_load ON taxes(load_id); CREATE TABLE budget_levels ( id INTEGER PRIMARY KEY AUTOINCREMENT, load_id INTEGER NOT NULL REFERENCES loads(id), level TEXT NOT NULL, taxes TEXT NOT NULL ); `, }, { // Stage 3 (answer assembled from the DB) needs everything the in-memory // answer carries: keep-previous bookkeeping of stale files and the // site-to-region map, deduplicated the same way facts are. version: 2, sql: ` ALTER TABLE load_files ADD COLUMN data_from TEXT; ALTER TABLE load_files ADD COLUMN pending TEXT; ALTER TABLE loads ADD COLUMN regions_hash TEXT; ALTER TABLE loads ADD COLUMN regions_load_id INTEGER; CREATE TABLE company_regions ( id INTEGER PRIMARY KEY AUTOINCREMENT, load_id INTEGER NOT NULL REFERENCES loads(id), name TEXT NOT NULL, region TEXT NOT NULL ); CREATE INDEX idx_company_regions_load ON company_regions(load_id); `, }, ]; /** Outside the repo on purpose: the file holds real holding finances. */ export function defaultDbPath() { return path.join(os.homedir(), '.shareholder-panel', 'history.db'); } function migrate(db) { const current = db.prepare('PRAGMA user_version').get().user_version; for (const step of MIGRATIONS) { if (step.version <= current) continue; db.exec('BEGIN'); try { db.exec(step.sql); // PRAGMA does not take bind parameters; version comes from code, not input db.exec(`PRAGMA user_version = ${step.version}`); db.exec('COMMIT'); } catch (error) { db.exec('ROLLBACK'); throw error; } } } const CASH_WEEKLY_METRICS = [ ['openBalance', 'Остаток на начало'], ['inflow', 'Приход'], ['outflow', 'Расход'], ['saldo', 'Сальдо'], ['closeBalance', 'Остаток на конец'], ]; const FINANCE_SCENARIOS = [['fact', 'факт'], ['budget', 'бюджет'], ['forecast', 'прогноз']]; // Every in-memory field becomes a fact row, nulls included: this keeps the // DB-versus-memory comparison exact (row counts match) and keeps "нет данных" // distinguishable from zero. Row shape: [period, org, metric, scenario, value, note]. const FACT_MAPPERS = { people: (row) => [[row.month, row.company, row.metric, null, row.value, null]], cashWeekly: (row) => CASH_WEEKLY_METRICS.map(([field, metric]) => [ row.date, row.company, metric, null, row[field], // the comment explains the week's movements, so it rides on the saldo row metric === 'Сальдо' && row.comment ? row.comment : null, ]), cashBanks: (row) => [[row.date, row.bank, 'Остатки ДС', null, row.balance, null]], depositBalances: (row) => [[row.month, row.division ?? '', 'Остатки на РС', null, row.balance, null]], depositInterest: (row) => [ [row.quarter, row.division ?? '', 'Процентные доходы', null, row.amount, null], [row.quarter, row.division ?? '', 'Процентная доходность', null, row.yield, null], ], finance: (row) => FINANCE_SCENARIOS.map(([field, scenario]) => [ row.month, row.company, row.indicator, scenario, row[field], null, ]), }; FACT_MAPPERS.depositHolding = FACT_MAPPERS.depositInterest; function insertRows(db, loadId, dataset, rows) { if (dataset === 'companies') { const insert = db.prepare('INSERT INTO companies (load_id, name, short_name, inn, activity,' + ' geography, region, region_short, division, site, type, synonyms)' + ' VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'); for (const row of rows) { insert.run(loadId, row.name, row.shortName ?? null, row.inn ?? null, row.activity ?? null, row.geography ?? null, row.region ?? null, row.regionShort ?? null, row.division ?? null, row.site ?? null, row.type ?? null, (row.synonyms ?? []).join('|') || null); } return; } if (dataset === 'taxes') { const insert = db.prepare('INSERT INTO taxes (load_id, quarter, org, inn, activity, geography,' + ' region, regional_budget, vat, profit_federal, profit_regional, insurance, property,' + ' land, transport) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'); for (const row of rows) { insert.run(loadId, row.quarter, row.org, row.inn ?? null, row.activity ?? null, row.geography ?? null, row.region ?? null, row.regionalBudget ?? null, row.vat, row.profitFederal, row.profitRegional, row.insurance, row.property, row.land, row.transport); } return; } if (dataset === 'budgetLevels') { const insert = db.prepare('INSERT INTO budget_levels (load_id, level, taxes) VALUES (?, ?, ?)'); for (const row of rows) insert.run(loadId, row.level, row.taxes.join('|')); return; } const mapper = FACT_MAPPERS[dataset]; if (!mapper) { // a future dataset unknown to the schema: better a journal line than silence console.warn(`[db] набор «${dataset}» не описан в схеме базы - его строки не записаны`); return; } const insert = db.prepare('INSERT INTO facts (load_id, dataset, period, org, metric, scenario,' + ' value, note) VALUES (?, ?, ?, ?, ?, ?, ?, ?)'); for (const row of rows) { for (const [period, org, metric, scenario, value, note] of mapper(row)) { insert.run(loadId, dataset, period ?? '', org ?? '', metric ?? '', scenario ?? null, value ?? null, note ?? null); } } } function contentHash(rows, fileRejects) { return crypto.createHash('sha256') .update(JSON.stringify(rows)) .update('|') .update(JSON.stringify(fileRejects)) .digest('hex'); } /** Lineage of the previous load: dataset -> where its current facts live. */ function readLineage(db) { const lineage = new Map(); const rows = db.prepare('SELECT dataset, content_hash, facts_load_id FROM load_files' + ' WHERE load_id = (SELECT MAX(id) FROM loads)').all(); for (const row of rows) lineage.set(row.dataset, row); return lineage; } /** Same idea for the site-to-region map, which lives on the loads row. */ function readRegionsLineage(db) { const row = db.prepare('SELECT regions_hash, regions_load_id FROM loads' + ' ORDER BY id DESC LIMIT 1').get(); return row?.regions_hash ? { hash: row.regions_hash, loadId: row.regions_load_id } : null; } function writeLoad(db, lineage, regionsPrev, result, reason) { const meta = result.meta; const rejectsByFile = new Map(); for (const item of meta.rejects ?? []) { if (!rejectsByFile.has(item.file)) rejectsByFile.set(item.file, []); rejectsByFile.get(item.file).push(item); } const files = meta.files ?? []; const nextLineage = new Map(); db.exec('BEGIN'); try { const loadId = Number(db.prepare('INSERT INTO loads (loaded_at, reason, data_dir, source_label,' + ' duration_ms, files_found, files_total, rows_total, warnings, errors, rejects)' + ' VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)').run( meta.loadedAt ?? new Date().toISOString(), reason, meta.dataDir ?? '', meta.sourceLabel ?? null, meta.durationMs ?? 0, files.filter((file) => file.exists).length, files.length, files.reduce((total, file) => total + (file.rows ?? 0), 0), (meta.warnings ?? []).length, (meta.errors ?? []).length, files.reduce((total, file) => total + (file.rejected ?? 0), 0), ).lastInsertRowid); const insertFile = db.prepare('INSERT INTO load_files (load_id, dataset, file, found, stale,' + ' rows_read, rows_accepted, rows_rejected, size, file_mtime, content_hash, facts_load_id,' + ' data_from, pending) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'); const insertReject = db.prepare('INSERT INTO load_rejects (load_id, file, reason, raw)' + ' VALUES (?, ?, ?, ?)'); for (const file of files) { const rows = result[file.key] ?? []; const fileRejects = rejectsByFile.get(file.file) ?? []; const hash = contentHash(rows, fileRejects); const previous = lineage.get(file.key); let factsLoadId = loadId; if (previous && previous.content_hash === hash && previous.facts_load_id) { // nothing changed since the load the previous lineage points to: // reference those rows instead of duplicating thousands of them factsLoadId = previous.facts_load_id; } else { insertRows(db, loadId, file.key, rows); for (const item of fileRejects) { insertReject.run(loadId, item.file, item.reason, JSON.stringify(item.raw)); } } insertFile.run(loadId, file.key, file.file, file.exists ? 1 : 0, file.stale ? 1 : 0, file.rawRows ?? 0, file.rows ?? 0, file.rejected ?? 0, file.size ?? null, file.updatedAt ?? null, hash, factsLoadId, file.dataFrom ?? null, file.pending ?? null); nextLineage.set(file.key, { dataset: file.key, content_hash: hash, facts_load_id: factsLoadId }); } // Site-to-region map: written only when it changed, like the facts; // loads.regions_load_id says which load holds the current rows. const regionsEntries = Object.entries(result.companyRegions ?? {}); const regionsHash = contentHash(regionsEntries, []); let regionsLoadId = loadId; if (regionsPrev && regionsPrev.hash === regionsHash && regionsPrev.loadId) { regionsLoadId = regionsPrev.loadId; } else { const insertRegion = db.prepare('INSERT INTO company_regions (load_id, name, region) VALUES (?, ?, ?)'); for (const [name, region] of regionsEntries) insertRegion.run(loadId, name, region); } db.prepare('UPDATE loads SET regions_hash = ?, regions_load_id = ? WHERE id = ?') .run(regionsHash, regionsLoadId, loadId); const insertWarning = db.prepare('INSERT INTO load_warnings (load_id, file, code, message)' + ' VALUES (?, ?, ?, ?)'); for (const item of meta.warnings ?? []) { insertWarning.run(loadId, item.file ?? '', item.code ?? '', item.message ?? ''); } const insertError = db.prepare('INSERT INTO load_errors (load_id, file, message) VALUES (?, ?, ?)'); for (const item of meta.errors ?? []) insertError.run(loadId, item.file ?? '', item.message ?? ''); db.exec('COMMIT'); return { loadId, nextLineage, nextRegions: { hash: regionsHash, loadId: regionsLoadId } }; } catch (error) { try { db.exec('ROLLBACK'); } catch { /* already rolled back */ } throw error; } } /** * Opens the load history. Never throws: on any failure returns a handle with * available=false whose recordLoad() resolves to null and readers return []. * Reconnects lazily, so a transient lock or a DB created later heals itself. */ export function openHistory(dbPath, { readOnly = false } = {}) { const file = dbPath || defaultDbPath(); const state = { db: null, lineage: null, regions: null, queue: Promise.resolve() }; function ensure() { if (state.db) return state.db; try { if (readOnly) { state.db = new DatabaseSync(file, { readOnly: true }); } else { fs.mkdirSync(path.dirname(file), { recursive: true }); state.db = new DatabaseSync(file); // WAL lets the report script read while the panel writes state.db.exec('PRAGMA journal_mode = WAL'); // ...but the write-ahead log is only folded back into the DB at 1000 // pages and is never truncated afterwards, so it parks at ~4 MB forever. // The limit alone does not help (measured): the fold must be asked for // explicitly after each write - see checkpoint() below. state.db.exec('PRAGMA journal_size_limit = 1048576'); migrate(state.db); } // a corrupt file fails on the first statement, not on open - probe now state.db.prepare('SELECT COUNT(*) AS n FROM sqlite_master').get(); state.lineage = null; state.regions = null; } catch (error) { console.warn(`[db] база истории недоступна (${file}): ${error.message} - панель работает без неё`); try { state.db?.close(); } catch { /* nothing to close */ } state.db = null; } return state.db; } function drop() { try { state.db?.close(); } catch { /* nothing to close */ } state.db = null; state.lineage = null; state.regions = null; } /** Read helper: empty result instead of an exception when the DB is away. */ function all(sql, ...params) { try { const db = ensure(); return db ? db.prepare(sql).all(...params) : []; } catch (error) { console.warn(`[db] чтение из базы не удалось: ${error.message}`); drop(); return []; } } function factsSource(loadId, dataset) { const rows = all('SELECT facts_load_id FROM load_files WHERE load_id = ? AND dataset = ?', loadId, dataset); return rows[0]?.facts_load_id ?? null; } /** Rows of a wide table (taxes, companies, budget_levels) as shown at loadId. */ function wideFor(loadId, dataset, table) { const source = factsSource(loadId, dataset); if (source === null) return []; return all(`SELECT * FROM ${table} WHERE load_id = ? ORDER BY id`, source); } ensure(); if (state.db && !readOnly) console.log(`[db] история загрузок: ${file}`); return { path: file, get available() { return state.db !== null; }, /** * Records one loadAll() result. Serialized through a queue so overlapping * calls cannot interleave transactions; resolves to the load id or null. */ recordLoad(result, reason = '') { if (readOnly) return Promise.resolve(null); const run = state.queue.then(async () => { // yield once so pending request handlers run before the synchronous write await new Promise((resolve) => { setImmediate(resolve); }); const db = ensure(); if (!db) return null; if (state.lineage === null) { state.lineage = readLineage(db); state.regions = readRegionsLineage(db); } const { loadId, nextLineage, nextRegions } = writeLoad(db, state.lineage, state.regions, result, reason); state.lineage = nextLineage; state.regions = nextRegions; // Fold the write-ahead log back into the DB and truncate it. Measured on // 200 loads: without this the log parks at ~3.5 MB, with it at zero, and // the cost is 0.04 ms per load. Matters twice - the file stops holding // space for nothing, and a backup of history.db alone stops being a // half-copy. A busy reader just makes it a no-op, which is fine. try { db.exec('PRAGMA wal_checkpoint(TRUNCATE)'); } catch { /* reader holds it: next time */ } return loadId; }).catch((error) => { // a failed write must never take the panel down; drop the connection // so the next call reopens it and a transient failure heals itself console.error(`[db] запись загрузки в базу не удалась: ${error.message}`); drop(); return null; }); state.queue = run.then(() => undefined); return run; }, lastLoads(limit = 20) { return all('SELECT * FROM loads ORDER BY id DESC LIMIT ?', limit); }, loadById(loadId) { return all('SELECT * FROM loads WHERE id = ?', loadId)[0] ?? null; }, filesForLoad(loadId) { return all('SELECT * FROM load_files WHERE load_id = ? ORDER BY id', loadId); }, warningsForLoad(loadId) { return all('SELECT file, code, message FROM load_warnings WHERE load_id = ? ORDER BY id', loadId); }, errorsForLoad(loadId) { return all('SELECT file, message FROM load_errors WHERE load_id = ? ORDER BY id', loadId); }, /** One quarantine page; total is counted with the same filters. */ rejectsPage({ loadId = null, file = null, limit = 50, offset = 0 } = {}) { const where = []; const params = []; if (loadId !== null) { where.push('r.load_id = ?'); params.push(loadId); } if (file !== null) { where.push('r.file = ?'); params.push(file); } const clause = where.length > 0 ? ` WHERE ${where.join(' AND ')}` : ''; const total = all(`SELECT COUNT(*) AS n FROM load_rejects r${clause}`, ...params)[0]?.n ?? 0; const items = all('SELECT r.id, r.load_id, l.loaded_at, r.file, r.reason, r.raw' + ` FROM load_rejects r JOIN loads l ON l.id = r.load_id${clause}` + ' ORDER BY r.id DESC LIMIT ? OFFSET ?', ...params, limit, offset); return { total, items }; }, /** * Accepted-row history per dataset, one point per content change (loads * that only reread an unchanged file add no points). A drop between two * consecutive points is therefore a real change of the file, not noise - * the earliest signal of silent data loss. */ volumeSeries(maxPoints = 40) { const rows = all('SELECT f.dataset, f.file, f.load_id, f.rows_accepted, l.loaded_at' + ' FROM load_files f JOIN loads l ON l.id = f.load_id' + ' WHERE f.facts_load_id = f.load_id ORDER BY f.load_id'); const byDataset = new Map(); for (const row of rows) { if (!byDataset.has(row.dataset)) { byDataset.set(row.dataset, { dataset: row.dataset, file: row.file, points: [] }); } const entry = byDataset.get(row.dataset); entry.file = row.file; entry.points.push({ loadId: row.load_id, loadedAt: row.loaded_at, rows: row.rows_accepted }); } for (const entry of byDataset.values()) { if (entry.points.length > maxPoints) entry.points = entry.points.slice(-maxPoints); } return [...byDataset.values()]; }, recentRejects(limit = 20) { return all('SELECT r.id, r.load_id, l.loaded_at, r.file, r.reason, r.raw' + ' FROM load_rejects r JOIN loads l ON l.id = r.load_id ORDER BY r.id DESC LIMIT ?', limit); }, recentWarnings(limit = 20) { return all('SELECT w.id, w.load_id, l.loaded_at, w.file, w.code, w.message' + ' FROM load_warnings w JOIN loads l ON l.id = w.load_id ORDER BY w.id DESC LIMIT ?', limit); }, recentErrors(limit = 20) { return all('SELECT e.id, e.load_id, l.loaded_at, e.file, e.message' + ' FROM load_errors e JOIN loads l ON l.id = e.load_id ORDER BY e.id DESC LIMIT ?', limit); }, /** Long-form facts of a dataset exactly as shown at loadId (history lookup). */ factsFor(loadId, dataset) { const source = factsSource(loadId, dataset); if (source === null) return []; return all('SELECT period, org, metric, scenario, value, note FROM facts' + ' WHERE dataset = ? AND load_id = ? ORDER BY id', dataset, source); }, taxesFor(loadId) { return wideFor(loadId, 'taxes', 'taxes'); }, companiesFor(loadId) { return wideFor(loadId, 'companies', 'companies'); }, budgetLevelsFor(loadId) { return wideFor(loadId, 'budgetLevels', 'budget_levels'); }, /** Quarantine of one file exactly as written with its facts (no paging). */ rejectsFor(loadId, file) { return all('SELECT file, reason, raw FROM load_rejects WHERE load_id = ? AND file = ?' + ' ORDER BY id', loadId, file); }, /** Site-to-region map as shown at loadId, in original insertion order. */ companyRegionsFor(loadId) { const row = all('SELECT regions_load_id FROM loads WHERE id = ?', loadId)[0]; if (!row || row.regions_load_id === null) return []; return all('SELECT name, region FROM company_regions WHERE load_id = ? ORDER BY id', row.regions_load_id); }, close() { drop(); }, }; }