Files
anorandClaude Opus 5 14d98c9f74 feat: панель переведена на утверждённый формат выгрузок заказчика
Файлы ищутся в подкаталогах с русскими именами; прежний плоский набор
по-прежнему читается, эталон итогов демо-набора зелёный.

Закрыты три места, где данные исчезали молча: месяц вида «июн.26»
(финрезультат терял все строки), колонка «Остатки ДС» (пропадали остатки
по банкам), прочерк в налогах вместо тихого нуля.

ФОТ выгружается тысячами рублей, а панель считает миллионами — без
пересчёта цифра на экране была бы завышена в тысячу раз. Единица
определяется по правдоподобию: больше 5 млн руб. на человека в месяц
означает, что единица не та.

«КЛГ» в названиях площадок — это Калуга, а не Калининград: 281 человек
стоял на карте не в том конце страны. Калужской области в словаре не было
вовсе. Списки коротких названий в сервере и на карте теперь сторожит тест —
он сразу нашёл ещё четыре расхождения.

Разбивка по дивизионам убрана по решению заказчика, см. docs/adr/001.

Тестов 80.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-06 23:29:54 +10:00

241 lines
9.9 KiB
JavaScript
Raw Permalink Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import fs from 'node:fs';
import iconv from 'iconv-lite';
/**
* Чтение CSV с автоопределением кодировки (UTF-8 / UTF-8 BOM / windows-1251)
* и разделителя (; , tab |). Поддерживаются кавычки и переводы строк внутри полей.
*/
function decode(buffer) {
if (buffer.length >= 3 && buffer[0] === 0xef && buffer[1] === 0xbb && buffer[2] === 0xbf) {
return buffer.slice(3).toString('utf8');
}
// Excel сохраняет "Текст Юникод" в UTF-16 с обязательной меткой порядка байтов;
// без этой ветки заголовки превращаются в мусор и файл молча читается пустым
if (buffer.length >= 2 && buffer[0] === 0xff && buffer[1] === 0xfe) {
return iconv.decode(buffer, 'utf16-le').replace(/^/, '');
}
if (buffer.length >= 2 && buffer[0] === 0xfe && buffer[1] === 0xff) {
return iconv.decode(buffer, 'utf16-be').replace(/^/, '');
}
const text = buffer.toString('utf8');
// U+FFFD появляется, когда байты не являются валидным UTF-8 - значит это windows-1251
if (text.includes('�')) return iconv.decode(buffer, 'win1251');
return text;
}
function detectDelimiter(text) {
const head = text.split(/\r?\n/).slice(0, 5).join('\n');
const candidates = [';', '\t', ',', '|'];
let best = ';';
let bestCount = -1;
for (const candidate of candidates) {
const count = head.split(candidate).length - 1;
if (count > bestCount) {
best = candidate;
bestCount = count;
}
}
return bestCount > 0 ? best : ';';
}
function splitRows(text, delimiter) {
const rows = [];
let row = [];
let field = '';
let quoted = false;
for (let i = 0; i < text.length; i += 1) {
const char = text[i];
if (quoted) {
if (char === '"') {
if (text[i + 1] === '"') {
field += '"';
i += 1;
} else {
quoted = false;
}
} else {
field += char;
}
continue;
}
if (char === '"') {
quoted = true;
} else if (char === delimiter) {
row.push(field);
field = '';
} else if (char === '\n') {
row.push(field);
rows.push(row);
row = [];
field = '';
} else if (char !== '\r') {
field += char;
}
}
if (field.length > 0 || row.length > 0) {
row.push(field);
rows.push(row);
}
return rows.filter((item) => item.some((cell) => cell.trim() !== ''));
}
/** Разбирает уже прочитанное содержимое файла: { headers, rows } с массивом объектов. */
export function parseCsv(buffer) {
const text = decode(buffer);
const delimiter = detectDelimiter(text);
const raw = splitRows(text, delimiter);
if (raw.length === 0) return { headers: [], rows: [], matrix: [] };
const headers = raw[0].map((cell) => cell.replace(/\s+/g, ' ').trim());
const rows = raw.slice(1).map((cells) => {
const record = {};
headers.forEach((header, index) => {
record[header] = (cells[index] ?? '').trim();
});
return record;
});
return { headers, rows, matrix: raw };
}
/**
* Синхронное чтение файла - осталось для тестов и разовых сценариев.
* Сервер читает данные асинхронно (см. safeRead в load.js): сетевая папка может
* подвиснуть на десятки секунд, и синхронное чтение заморозило бы панель для всех.
*/
export function readCsv(filePath) {
return parseCsv(fs.readFileSync(filePath));
}
/** "1 234,56", "1234.56", "12%", "" -> число или null */
export function toNumber(value) {
if (value === null || value === undefined) return null;
if (typeof value === 'number') return Number.isFinite(value) ? value : null;
let text = String(value).trim();
if (text === '' || text === '-' || text === 'н/д' || text === 'n/a') return null;
// бухгалтерская запись отрицательных чисел: (1 234) = -1234
let negative = false;
const brackets = text.match(/^\((.+)\)$/);
if (brackets) {
negative = true;
text = brackets[1].trim();
}
const percent = text.includes('%');
text = text
.replace(/ /g, '')
.replace(/\s/g, '')
.replace(/%/g, '')
.replace(/["']/g, '');
// числа вида 1.234,56 (европейский формат) и 1,234.56 (английский)
if (text.includes(',') && text.includes('.')) {
if (text.lastIndexOf(',') > text.lastIndexOf('.')) text = text.replace(/\./g, '').replace(',', '.');
else text = text.replace(/,/g, '');
} else {
text = text.replace(',', '.');
}
const parsed = Number(text);
if (!Number.isFinite(parsed)) return null;
const value_ = percent ? parsed / 100 : parsed;
return negative ? -value_ : value_;
}
const MONTH_NAMES = [
'январь', 'февраль', 'март', 'апрель', 'май', 'июнь',
'июль', 'август', 'сентябрь', 'октябрь', 'ноябрь', 'декабрь',
];
function fromExcelSerial(serial) {
// Excel: 1 = 1900-01-01, с известным сдвигом на несуществующий 1900-02-29
const ms = (serial - 25569) * 86400000;
return new Date(ms);
}
function pad(value) {
return String(value).padStart(2, '0');
}
/**
* Приводит дату к ISO YYYY-MM-DD. Понимает: 29.06.2026, 2026-06-29,
* 29/06/2026, Excel-сериал (46174), "июнь 2026", "2026-06".
*/
export function toIsoDate(value) {
if (value === null || value === undefined) return null;
const text = String(value).trim();
if (text === '') return null;
let match = text.match(/^(\d{4})-(\d{2})-(\d{2})/);
if (match) return `${match[1]}-${match[2]}-${match[3]}`;
match = text.match(/^(\d{1,2})[.\-/](\d{1,2})[.\-/](\d{4})/);
if (match) return `${match[3]}-${pad(match[2])}-${pad(match[1])}`;
match = text.match(/^(\d{4})-(\d{2})$/);
if (match) return `${match[1]}-${match[2]}-01`;
// «июнь 2026», «июн.26», «янв 27». Двузначный год здесь безопасен, в отличие от
// «01.07.26»: месяц назван словом, перепутать его с днём невозможно.
match = text.match(/^([А-Яа-яЁё]{3,})\.?\s*(\d{2}|\d{4})$/);
if (match) {
// Родительный падеж («мая 2026») отличается от именительного только у мая:
// у остальных месяцев первые три буквы совпадают («июня» → «июн» → «июнь»).
const word = match[1].toLowerCase();
const index = word.startsWith('мая')
? 4
: MONTH_NAMES.findIndex((name) => name.startsWith(word.slice(0, 3)));
if (index >= 0) {
const year = match[2].length === 2 ? 2000 + Number(match[2]) : Number(match[2]);
return `${year}-${pad(index + 1)}-01`;
}
}
const serial = Number(text.replace(',', '.'));
if (Number.isFinite(serial) && serial > 20000 && serial < 80000) {
const date = fromExcelSerial(serial);
return `${date.getUTCFullYear()}-${pad(date.getUTCMonth() + 1)}-${pad(date.getUTCDate())}`;
}
// Раньше здесь был запасной разбор через new Date(text). Он молча угадывал неверно:
// "01.07.26" превращалось в 2026-01-06 (день с месяцем переставлены, плюс сдвиг суток
// из-за чтения местной полуночи как UTC). Все форматы из docs/DATA.md разбираются выше,
// остальное честнее вернуть как "не понял" - строка попадёт в предупреждения.
return null;
}
/** ISO-дата -> "2026-06" */
export function toMonthKey(value) {
const iso = toIsoDate(value);
return iso ? iso.slice(0, 7) : null;
}
/** "1Q2026", "2026 Q1", "01.02.2026" -> "2026-Q1" */
const ROMAN_QUARTERS = { I: 1, II: 2, III: 3, IV: 4 };
export function toQuarterKey(value) {
if (value === null || value === undefined) return null;
const text = String(value).trim();
// "1Q2026", "1 кв 2026", "3 квартал 2026" (\w в JavaScript не покрывает кириллицу,
// поэтому слово "квартал" разбираем явно)
let match = text.match(/^([1-4])\s*(?:[Qq]|кв(?:артал|\.)?)\s*\.?\s*(\d{4})$/i);
if (match) return `${match[2]}-Q${match[1]}`;
match = text.match(/^(\d{4})[\s-]*(?:[Qq]|кв(?:артал|\.)?)\s*\.?\s*([1-4])$/i);
if (match) return `${match[1]}-Q${match[2]}`;
// римская запись: "II квартал 2026"
match = text.match(/^(I{1,3}|IV)\s*(?:кв(?:артал|\.)?|[Qq])\s*\.?\s*(\d{4})$/i);
if (match) return `${match[2]}-Q${ROMAN_QUARTERS[match[1].toUpperCase()]}`;
// Строка про квартал, но написана незнакомо: не пытаемся разобрать её как дату -
// раньше "II квартал 2026" таким путём уезжало в 2025-Q4. Лучше честное "не понял".
if (/кв/i.test(text)) return null;
const iso = toIsoDate(text);
if (iso) {
const month = Number(iso.slice(5, 7));
return `${iso.slice(0, 4)}-Q${Math.floor((month - 1) / 3) + 1}`;
}
return null;
}
export function monthLabel(monthKey) {
if (!monthKey) return '';
const [year, month] = monthKey.split('-');
const names = ['янв', 'фев', 'мар', 'апр', 'май', 'июн', 'июл', 'авг', 'сен', 'окт', 'ноя', 'дек'];
return `${names[Number(month) - 1]} ${year.slice(2)}`;
}