import test from 'node:test'; import assert from 'node:assert/strict'; import fs from 'node:fs'; import os from 'node:os'; import path from 'node:path'; import { fileURLToPath } from 'node:url'; import { DatabaseSync } from 'node:sqlite'; import { loadAll } from './load.js'; import { openHistory } from './db.js'; // The DB is derived data: CSV files stay the source of truth, so the key test // here is the characterization one - DB content must give the same totals as // the in-memory structures built from the demo dataset. const demoDir = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'data'); function tempDir(prefix) { return fs.mkdtempSync(path.join(os.tmpdir(), prefix)); } function tempDbFile() { return path.join(tempDir('panel-db-'), 'history.db'); } async function loadFixture(files) { const dir = tempDir('panel-db-fix-'); for (const [name, content] of Object.entries(files)) { const target = path.join(dir, name); fs.mkdirSync(path.dirname(target), { recursive: true }); fs.writeFileSync(target, content, 'utf8'); } return loadAll(dir); } const sum = (rows, field) => rows.reduce((total, row) => total + (row[field] ?? 0), 0); const round = (value) => Math.round(value * 1000) / 1000; test('база создаётся со схемой и номером версии', () => { const file = tempDbFile(); const history = openHistory(file); assert.equal(history.available, true); history.close(); const raw = new DatabaseSync(file, { readOnly: true }); const tables = raw.prepare("SELECT name FROM sqlite_master WHERE type = 'table'").all() .map((row) => row.name); for (const name of ['loads', 'load_files', 'load_warnings', 'load_errors', 'load_rejects', 'facts', 'companies', 'taxes', 'budget_levels']) { assert.ok(tables.includes(name), `нет таблицы ${name}`); } assert.ok(raw.prepare('PRAGMA user_version').get().user_version >= 1, 'версия схемы записана в базу'); raw.close(); }); test('журнал загрузки: счётчики по файлам, предупреждения и карантин с сырьём', async () => { const data = await loadFixture({ 'people.csv': 'месяц;показатель;МС Автомотив НН;Альта Поволжье\n' + 'мусор;Абсентеизм;0,02;0,03\n' + '01.06.2026;Численность категория ОПР;94;16\n', 'taxes.csv': '№ п/п;Организация;ИНН;Квартал;НДС\n1;ООО РОГА;123;кв-л 2026;100\n', }); const history = openHistory(tempDbFile()); const loadId = await history.recordLoad(data, 'тест'); assert.ok(loadId >= 1, 'запись возвращает номер загрузки'); const loads = history.lastLoads(5); assert.equal(loads.length, 1); assert.equal(loads[0].reason, 'тест'); assert.equal(loads[0].rows_total, 2); assert.equal(loads[0].rejects, 2); assert.ok(loads[0].warnings >= 2, 'предупреждения о пропущенных строках посчитаны'); const files = history.filesForLoad(loadId); const people = files.find((item) => item.dataset === 'people'); assert.equal(people.rows_read, 2, 'прочитано сырых строк'); assert.equal(people.rows_accepted, 2, 'принято наблюдений'); assert.equal(people.rows_rejected, 1, 'отброшена одна строка'); const taxes = files.find((item) => item.dataset === 'taxes'); assert.equal(taxes.rows_read, 1); assert.equal(taxes.rows_accepted, 0); assert.equal(taxes.rows_rejected, 1); const rejects = history.recentRejects(10); const bad = rejects.find((item) => item.file === 'people.csv'); assert.match(bad.reason, /месяц/); assert.match(bad.raw, /мусор/, 'сырая строка сохранена в карантине'); assert.match(rejects.find((item) => item.file === 'taxes.csv').raw, /кв-л 2026/); const warnings = history.recentWarnings(20); assert.ok(warnings.some((item) => item.code === 'unparsed-rows')); history.close(); }); test('факты хранят историю: каждая загрузка отвечает «что показывалось тогда»', async () => { const dir = tempDir('panel-db-hist-'); const financeFile = path.join(dir, 'finance.csv'); const header = 'Месяц;Предприятие;Показатель;Факт;Бюджет;Прогноз\n'; fs.writeFileSync(financeFile, header + '01.06.2026;ООО РОГА;1. Выручка;100;;\n', 'utf8'); const history = openHistory(tempDbFile()); const first = await loadAll(dir); const firstId = await history.recordLoad(first, 'старт'); fs.writeFileSync(financeFile, header + '01.06.2026;ООО РОГА;1. Выручка;250;;\n', 'utf8'); const second = await loadAll(dir); const secondId = await history.recordLoad(second, 'автообновление'); const factOf = (rows) => rows.find((row) => row.scenario === 'факт'); assert.equal(factOf(history.factsFor(firstId, 'finance')).value, 100, 'первая загрузка помнит прежнюю цифру'); assert.equal(factOf(history.factsFor(secondId, 'finance')).value, 250, 'вторая загрузка помнит новую цифру'); // "нет данных" остаётся пустотой, а не нулём - и в длинной форме тоже const budget = history.factsFor(secondId, 'finance').find((row) => row.scenario === 'бюджет'); assert.equal(budget.value, null); history.close(); }); test('повторная загрузка без изменений не раздувает базу', async () => { const dir = tempDir('panel-db-same-'); fs.writeFileSync(path.join(dir, 'finance.csv'), 'Месяц;Предприятие;Показатель;Факт\n01.06.2026;ООО РОГА;1. Выручка;100\n', 'utf8'); const file = tempDbFile(); const history = openHistory(file); const first = await loadAll(dir); const firstId = await history.recordLoad(first, 'старт'); const second = await loadAll(dir, first); const secondId = await history.recordLoad(second, 'автообновление'); assert.ok(secondId > firstId, 'сама загрузка в журнал попадает'); const financeFile = history.filesForLoad(secondId).find((item) => item.dataset === 'finance'); assert.equal(financeFile.facts_load_id, firstId, 'факты не переписаны, ссылка ведёт на прежнюю загрузку'); assert.equal(history.factsFor(secondId, 'finance').length, 3, 'история при этом читается полностью'); history.close(); // server restart: lineage must be restored from the DB, not from memory const reopened = openHistory(file); const third = await loadAll(dir); const thirdId = await reopened.recordLoad(third, 'после перезапуска'); assert.equal( reopened.filesForLoad(thirdId).find((item) => item.dataset === 'finance').facts_load_id, firstId, 'после перезапуска сервера факты тоже не переписываются', ); reopened.close(); const raw = new DatabaseSync(file, { readOnly: true }); assert.equal( raw.prepare("SELECT COUNT(*) AS n FROM facts WHERE dataset = 'finance'").get().n, 3, 'строки фактов записаны один раз, а не трижды', ); raw.close(); }); test('база против памяти: демонстрационный набор даёт те же итоги', async () => { const data = await loadAll(demoDir); assert.equal(data.meta.errors.length, 0); assert.deepEqual(data.meta.rejects ?? [], [], 'в демонстрационном наборе карантин пуст'); const history = openHistory(tempDbFile()); const loadId = await history.recordLoad(data, 'сверка'); assert.ok(loadId, 'запись демонстрационного набора должна состояться'); const people = history.factsFor(loadId, 'people'); assert.equal(people.length, data.people.length); assert.equal(round(sum(people, 'value')), round(sum(data.people, 'value'))); const cash = history.factsFor(loadId, 'cashWeekly'); assert.equal(cash.length, data.cashWeekly.length * 5, 'пять показателей на строку недельного отчёта'); const cashSum = (metric) => round(sum(cash.filter((row) => row.metric === metric), 'value')); assert.equal(cashSum('Приход'), round(sum(data.cashWeekly, 'inflow'))); assert.equal(cashSum('Расход'), round(sum(data.cashWeekly, 'outflow'))); assert.equal(cashSum('Остаток на конец'), round(sum(data.cashWeekly, 'closeBalance'))); const banks = history.factsFor(loadId, 'cashBanks'); assert.equal(banks.length, data.cashBanks.length); assert.equal(round(sum(banks, 'value')), round(sum(data.cashBanks, 'balance'))); // depositBalances исключён из обязательных 11.08.2026 (adr/003) - сверять нечего; // разбор набора оставлен ради просмотра старых загрузок из истории. const interest = history.factsFor(loadId, 'depositInterest'); assert.equal(interest.length, data.depositInterest.length * 2, 'доход и доходность на каждую строку'); assert.equal( round(sum(interest.filter((row) => row.metric === 'Процентные доходы'), 'value')), round(sum(data.depositInterest, 'amount')), ); const finance = history.factsFor(loadId, 'finance'); assert.equal(finance.length, data.finance.length * 3, 'факт, бюджет и прогноз на каждую строку'); const financeSum = (scenario) => round(sum(finance.filter((row) => row.scenario === scenario), 'value')); assert.equal(financeSum('факт'), round(sum(data.finance, 'fact'))); assert.equal(financeSum('бюджет'), round(sum(data.finance, 'budget'))); assert.equal(financeSum('прогноз'), round(sum(data.finance, 'forecast'))); const taxes = history.taxesFor(loadId); assert.equal(taxes.length, data.taxes.length); assert.equal(round(sum(taxes, 'vat')), round(sum(data.taxes, 'vat'))); assert.equal(round(sum(taxes, 'insurance')), round(sum(data.taxes, 'insurance'))); assert.equal(round(sum(taxes, 'property')), round(sum(data.taxes, 'property'))); const companies = history.companiesFor(loadId); assert.equal(companies.length, data.companies.length); assert.deepEqual( companies.map((row) => row.name).sort(), data.companies.map((row) => row.name).sort(), ); history.close(); }); test('прочерк в налогах остаётся пустотой и в базе', async () => { const data = await loadFixture({ 'taxes.csv': '№ п/п;Организация;ИНН;География;Квартал;НДС;Страховые взносы\n' + '1;ООО ПЕТЕРФОРМ;7801234567;РФ, г.Санкт-Петербург;1Q2026; - ;5000\n', }); const history = openHistory(tempDbFile()); const loadId = await history.recordLoad(data, 'тест'); const [row] = history.taxesFor(loadId); assert.equal(row.vat, null, 'прочерк не должен стать нулём в базе'); assert.equal(row.insurance, 5000); history.close(); }); test('недоступная база не мешает панели: данные целы, ошибок наружу нет', async () => { // a path that cannot be created: /dev/null is a file, not a directory const history = openHistory('/dev/null/panel/history.db'); assert.equal(history.available, false); const data = await loadFixture({ 'people.csv': 'месяц;показатель;МС Автомотив НН\n01.06.2026;Численность категория ОПР;94\n', }); const snapshot = JSON.parse(JSON.stringify(data.people)); const recorded = await history.recordLoad(data, 'тест'); assert.equal(recorded, null, 'запись честно сообщает, что не состоялась'); assert.deepEqual(data.people, snapshot, 'данные в памяти не тронуты'); assert.deepEqual(history.lastLoads(5), [], 'чтение из недоступной базы отвечает пустотой'); history.close(); }); test('испорченный файл базы не роняет панель и не затирается', async () => { const file = tempDbFile(); fs.writeFileSync(file, 'это не база данных, а случайный текст', 'utf8'); const history = openHistory(file); const data = await loadFixture({ 'people.csv': 'месяц;показатель;МС Автомотив НН\n01.06.2026;Численность категория ОПР;94\n', }); assert.equal(await history.recordLoad(data, 'тест'), null); history.close(); assert.equal(fs.readFileSync(file, 'utf8'), 'это не база данных, а случайный текст', 'панель не «чинит» базу удалением - файл остался как был'); }); test('отчётный режим только читает и не создаёт файла базы', async () => { const file = tempDbFile(); const data = await loadFixture({ 'people.csv': 'месяц;показатель;МС Автомотив НН\n01.06.2026;Численность категория ОПР;94\n', }); const writer = openHistory(file); await writer.recordLoad(data, 'тест'); writer.close(); const reader = openHistory(file, { readOnly: true }); assert.equal(reader.available, true); assert.equal(reader.lastLoads(5).length, 1); assert.equal(await reader.recordLoad(data, 'тест'), null, 'в отчётном режиме запись выключена'); reader.close(); const missing = path.join(tempDir('panel-db-ro-'), 'нет-такой.db'); const empty = openHistory(missing, { readOnly: true }); assert.equal(empty.available, false); assert.equal(fs.existsSync(missing), false, 'отчётный режим не должен создавать базу'); empty.close(); });