import { DATASETS } from './load.js'; import { NEW_REGIONS } from './regions.js'; /** * Rebuilds the full /api/data answer from the load-history database - the * exact inverse of what db.js writes. The contract is byte-exact JSON * equality with the in-memory answer of loadAll(): same keys, same key * order, same numbers (guarded by snapshot.test.js). * * It leans on one invariant of the fact mappers in db.js: every mapper * emits a FIXED number of fact rows per source row, in a fixed metric * order, nulls included. So reading facts back in insertion order and * cutting them into fixed-size chunks restores the original rows exactly. * If that invariant ever breaks, the shape check below throws and the * caller falls back to the in-memory answer instead of showing garbage. */ // Inverse of FACT_MAPPERS in db.js: chunk size, expected labels, row builder. const CHUNKED = { people: { size: 1, build: (c) => ({ month: c[0].period, metric: c[0].metric, company: c[0].org, value: c[0].value }), }, cashWeekly: { size: 5, labels: ['Остаток на начало', 'Приход', 'Расход', 'Сальдо', 'Остаток на конец'], label: (fact) => fact.metric, build: (c) => ({ date: c[0].period, company: c[0].org, openBalance: c[0].value, inflow: c[1].value, outflow: c[2].value, saldo: c[3].value, closeBalance: c[4].value, comment: c[3].note ?? '', }), }, cashBanks: { size: 1, labels: ['Остатки ДС'], label: (fact) => fact.metric, build: (c) => ({ date: c[0].period, bank: c[0].org, balance: c[0].value }), }, depositBalances: { size: 1, labels: ['Остатки на РС'], label: (fact) => fact.metric, build: (c) => ({ month: c[0].period, division: c[0].org, balance: c[0].value }), }, depositInterest: { size: 2, labels: ['Процентные доходы', 'Процентная доходность'], label: (fact) => fact.metric, build: (c) => ({ quarter: c[0].period, division: c[0].org, amount: c[0].value, yield: c[1].value }), }, finance: { size: 3, labels: ['факт', 'бюджет', 'прогноз'], label: (fact) => fact.scenario, build: (c) => ({ month: c[0].period, company: c[0].org, indicator: c[0].metric, fact: c[0].value, budget: c[1].value, forecast: c[2].value, }), }, }; // Набор «итог холдинга» из списка читаемых файлов убран 26.08.2026, но в базе он // остался у прежних загрузок - без этой строки их снимок не собрать. CHUNKED.depositHolding = CHUNKED.depositInterest; function restoreChunked(shape, facts) { if (facts.length % shape.size !== 0) { throw new Error(`факты не делятся на строки по ${shape.size}`); } const rows = []; for (let start = 0; start < facts.length; start += shape.size) { const chunk = facts.slice(start, start + shape.size); if (shape.labels) { for (let i = 0; i < shape.size; i += 1) { if (shape.label(chunk[i]) !== shape.labels[i]) { throw new Error(`строка фактов не совпала с ожидаемой формой (${shape.label(chunk[i])})`); } } } rows.push(shape.build(chunk)); } return rows; } // Key order below mirrors the loaders in load.js - byte-exact JSON depends on it. function restoreTaxes(rows) { return rows.map((row) => ({ quarter: row.quarter, org: row.org, inn: row.inn, activity: row.activity, geography: row.geography, region: row.region, regionalBudget: row.regional_budget, vat: row.vat, profitFederal: row.profit_federal, profitRegional: row.profit_regional, insurance: row.insurance, property: row.property, land: row.land, transport: row.transport, excise: row.excise, recycling: row.recycling, })); } function restoreCompanies(rows) { return rows.map((row) => ({ name: row.name, shortName: row.short_name, inn: row.inn, activity: row.activity, geography: row.geography, region: row.region, regionShort: row.region_short, division: row.division, site: row.site, type: row.type, synonyms: row.synonyms ? row.synonyms.split('|') : [], })); } function restoreBudgetLevels(rows) { return rows.map((row) => ({ level: row.level, taxes: row.taxes.split('|') })); } function restoreRows(history, loadId, dataset) { if (dataset === 'taxes') return restoreTaxes(history.taxesFor(loadId)); if (dataset === 'companies') return restoreCompanies(history.companiesFor(loadId)); if (dataset === 'budgetLevels') return restoreBudgetLevels(history.budgetLevelsFor(loadId)); const shape = CHUNKED[dataset]; if (!shape) throw new Error(`набор «${dataset}» не описан в сборке снимка`); return restoreChunked(shape, history.factsFor(loadId, dataset)); } /** * Assembles the answer of load loadId from the DB, or returns null when the * DB is away, the load does not exist or the stored shape is unexpected - * the caller then serves from memory (soft degradation, never an exception). */ export function buildSnapshot(history, loadId) { try { const load = history.loadById(loadId); if (!load) return null; const files = history.filesForLoad(loadId); if (files.length === 0) return null; const titles = new Map(DATASETS.map((dataset) => [dataset.key, dataset.title])); const metaFiles = []; const data = {}; const rejects = []; for (const file of files) { const entry = { key: file.dataset, file: file.file, title: titles.get(file.dataset) ?? '', exists: Boolean(file.found), rows: file.rows_accepted, rawRows: file.rows_read, rejected: file.rows_rejected, size: file.size, updatedAt: file.file_mtime, }; if (file.stale) { entry.stale = true; entry.dataFrom = file.data_from; if (file.pending !== null) entry.pending = file.pending; } metaFiles.push(entry); const rows = restoreRows(history, loadId, file.dataset); // Чтение из базы гасит ошибку и возвращает пустой список (db.js, функция all). // Молча собранный из таких пустот снимок выглядит успешным: панель показала бы // пустые экраны, объявив их ответом из базы, и отбросила бы разобранные цифры. if (rows.length === 0 && file.rows_accepted > 0) { throw new Error(`набор «${file.dataset}»: принято ${file.rows_accepted} строк, восстановлено 0`); } data[file.dataset] = rows; // quarantine rows live with the facts of their (possibly earlier) load for (const item of history.rejectsFor(file.facts_load_id, file.file)) { rejects.push({ file: item.file, reason: item.reason, raw: JSON.parse(item.raw) }); } } const meta = { dataDir: load.data_dir, sourceLabel: load.source_label, loadedAt: load.loaded_at, // week of the delivery; key position matters - the answer is compared byte-exact reportPeriod: load.report_start ? { start: load.report_start, end: load.report_end, week: load.report_week } : null, // same formula as loadAll: the freshest file-change time among the files dataUpdatedAt: metaFiles .filter((item) => item.updatedAt) .map((item) => item.updatedAt) .sort() .slice(-1)[0] ?? null, durationMs: load.duration_ms, files: metaFiles, errors: history.errorsForLoad(loadId), warnings: history.warningsForLoad(loadId), rejects, newRegions: NEW_REGIONS, }; const snapshot = { meta, companyRegions: Object.fromEntries( history.companyRegionsFor(loadId).map((row) => [row.name, row.region]), ), }; for (const file of files) snapshot[file.dataset] = data[file.dataset]; return snapshot; } catch (error) { // a broken snapshot must never break serving - memory is the fallback console.error(`[db] снимок загрузки №${loadId} не собрался: ${error.message}`); return null; } }