chore: первый коммит — панель акционера под контроль версий
Код сервера и интерфейса, документы проекта, генератор демонстрационных данных. Не включены: выгрузки samples/ (внутренняя отчётность) и каталог data/ — демонстрационный набор воспроизводится `npm run seed` побайтно, а на сервере его место занимают настоящие выгрузки. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,247 @@
|
||||
import type { Dataset, PeopleRow, TaxRow } from '../types';
|
||||
|
||||
export function uniqueSorted(values: (string | null | undefined)[]): string[] {
|
||||
return Array.from(new Set(values.filter((value): value is string => Boolean(value)))).sort();
|
||||
}
|
||||
|
||||
export function sum(values: (number | null | undefined)[]): number {
|
||||
return values.reduce((total: number, value) => total + (value ?? 0), 0);
|
||||
}
|
||||
|
||||
export function groupSum<T>(rows: T[], key: (row: T) => string | null, value: (row: T) => number | null): Map<string, number> {
|
||||
const result = new Map<string, number>();
|
||||
rows.forEach((row) => {
|
||||
const groupKey = key(row);
|
||||
if (!groupKey) return;
|
||||
result.set(groupKey, (result.get(groupKey) ?? 0) + (value(row) ?? 0));
|
||||
});
|
||||
return result;
|
||||
}
|
||||
|
||||
export function sortedEntries(map: Map<string, number>, direction: 'asc' | 'desc' = 'desc'): [string, number][] {
|
||||
return Array.from(map.entries()).sort((a, b) => (direction === 'desc' ? b[1] - a[1] : a[1] - b[1]));
|
||||
}
|
||||
|
||||
/* -------------------------------- Люди -------------------------------- */
|
||||
|
||||
export const HEADCOUNT_METRICS = [
|
||||
'Численность категория ОПР',
|
||||
'Численность категория РПП',
|
||||
'Численность категория РСС',
|
||||
];
|
||||
|
||||
export const RATE_METRICS = ['Абсентеизм', 'Текучесть'];
|
||||
|
||||
export function peopleMonths(rows: PeopleRow[]): string[] {
|
||||
return uniqueSorted(rows.map((row) => row.month));
|
||||
}
|
||||
|
||||
export function headcountByMonth(rows: PeopleRow[], companies?: Set<string>): Map<string, number> {
|
||||
return groupSum(
|
||||
rows.filter((row) => HEADCOUNT_METRICS.includes(row.metric) && (!companies || companies.has(row.company))),
|
||||
(row) => row.month,
|
||||
(row) => row.value,
|
||||
);
|
||||
}
|
||||
|
||||
export function metricByMonth(rows: PeopleRow[], metric: string, companies?: Set<string>): Map<string, number> {
|
||||
return groupSum(
|
||||
rows.filter((row) => row.metric === metric && (!companies || companies.has(row.company))),
|
||||
(row) => row.month,
|
||||
(row) => row.value,
|
||||
);
|
||||
}
|
||||
|
||||
/** Среднее по площадкам - для относительных показателей (абсентеизм, текучесть). */
|
||||
export function averageMetricByMonth(rows: PeopleRow[], metric: string, weights?: Map<string, number>): Map<string, number> {
|
||||
const totals = new Map<string, { weighted: number; weight: number }>();
|
||||
rows.filter((row) => row.metric === metric).forEach((row) => {
|
||||
const weight = weights?.get(row.company) ?? 1;
|
||||
const current = totals.get(row.month) ?? { weighted: 0, weight: 0 };
|
||||
current.weighted += row.value * weight;
|
||||
current.weight += weight;
|
||||
totals.set(row.month, current);
|
||||
});
|
||||
return new Map(Array.from(totals.entries()).map(([month, item]) => [month, item.weight > 0 ? item.weighted / item.weight : 0]));
|
||||
}
|
||||
|
||||
export function headcountByCompany(rows: PeopleRow[], month: string): Map<string, number> {
|
||||
return groupSum(
|
||||
rows.filter((row) => row.month === month && HEADCOUNT_METRICS.includes(row.metric)),
|
||||
(row) => row.company,
|
||||
(row) => row.value,
|
||||
);
|
||||
}
|
||||
|
||||
export function peopleMetricByCompany(rows: PeopleRow[], month: string, metric: string): Map<string, number> {
|
||||
return groupSum(
|
||||
rows.filter((row) => row.month === month && row.metric === metric),
|
||||
(row) => row.company,
|
||||
(row) => row.value,
|
||||
);
|
||||
}
|
||||
|
||||
/* -------------------------------- Налоги -------------------------------- */
|
||||
|
||||
export const TAX_COLUMNS: { key: keyof TaxRow; label: string }[] = [
|
||||
{ key: 'vat', label: 'НДС' },
|
||||
{ key: 'profitFederal', label: 'Прибыль, федеральный' },
|
||||
{ key: 'profitRegional', label: 'Прибыль, региональный' },
|
||||
{ key: 'insurance', label: 'Страховые взносы' },
|
||||
{ key: 'property', label: 'Имущество' },
|
||||
{ key: 'land', label: 'Земля' },
|
||||
{ key: 'transport', label: 'Транспорт' },
|
||||
];
|
||||
|
||||
export function taxTotal(row: TaxRow): number {
|
||||
return TAX_COLUMNS.reduce((total, column) => total + (Number(row[column.key]) || 0), 0);
|
||||
}
|
||||
|
||||
export function taxBudgetLevels(rows: TaxRow[]): { label: string; value: number }[] {
|
||||
const federal = sum(rows.map((row) => row.vat + row.profitFederal));
|
||||
const regional = sum(rows.map((row) => row.profitRegional + row.property + row.land + row.transport));
|
||||
const social = sum(rows.map((row) => row.insurance));
|
||||
return [
|
||||
{ label: 'Федеральный бюджет РФ', value: federal },
|
||||
{ label: 'Региональные бюджеты', value: regional },
|
||||
{ label: 'Социальная защита граждан', value: social },
|
||||
];
|
||||
}
|
||||
|
||||
/* ------------------------------ Финрезультат ------------------------------ */
|
||||
|
||||
export const FINANCE_ORDER = [
|
||||
'1. Выручка',
|
||||
'2. Прямая себестоимость',
|
||||
'3. Маржинальная прибыль',
|
||||
'4. Производственные накладные расходы (ПНР)',
|
||||
'5. Валовая прибыль',
|
||||
'6. Коммерческие, административные и прочие',
|
||||
'7. EBIT (операционная прибыль)',
|
||||
'8. Процентные доходы',
|
||||
'9. Чистая прибыль',
|
||||
];
|
||||
|
||||
export function financeIndicatorLabel(indicator: string): string {
|
||||
return indicator.replace(/^\d+\.\s*/, '');
|
||||
}
|
||||
|
||||
export function financeSeries(
|
||||
dataset: Dataset,
|
||||
indicator: string,
|
||||
months: string[],
|
||||
companies?: Set<string>,
|
||||
): { fact: (number | null)[]; budget: (number | null)[]; forecast: (number | null)[] } {
|
||||
const rows = dataset.finance.filter(
|
||||
(row) => row.indicator === indicator && (!companies || companies.has(row.company)),
|
||||
);
|
||||
const byMonth = new Map<string, { fact: number | null; budget: number | null; forecast: number | null }>();
|
||||
rows.forEach((row) => {
|
||||
const current = byMonth.get(row.month) ?? { fact: null, budget: null, forecast: null };
|
||||
if (row.fact !== null) current.fact = (current.fact ?? 0) + row.fact;
|
||||
if (row.budget !== null) current.budget = (current.budget ?? 0) + row.budget;
|
||||
if (row.forecast !== null) current.forecast = (current.forecast ?? 0) + row.forecast;
|
||||
byMonth.set(row.month, current);
|
||||
});
|
||||
return {
|
||||
fact: months.map((month) => byMonth.get(month)?.fact ?? null),
|
||||
budget: months.map((month) => byMonth.get(month)?.budget ?? null),
|
||||
forecast: months.map((month) => byMonth.get(month)?.forecast ?? null),
|
||||
};
|
||||
}
|
||||
|
||||
export function financeTotal(
|
||||
dataset: Dataset,
|
||||
indicator: string,
|
||||
months: string[],
|
||||
field: 'fact' | 'budget' | 'forecast' = 'fact',
|
||||
companies?: Set<string>,
|
||||
): number {
|
||||
const monthSet = new Set(months);
|
||||
return sum(
|
||||
dataset.finance
|
||||
.filter((row) => row.indicator === indicator && monthSet.has(row.month) && (!companies || companies.has(row.company)))
|
||||
.map((row) => row[field]),
|
||||
);
|
||||
}
|
||||
|
||||
export function financeByCompany(
|
||||
dataset: Dataset,
|
||||
indicator: string,
|
||||
months: string[],
|
||||
field: 'fact' | 'budget' | 'forecast' = 'fact',
|
||||
): Map<string, number> {
|
||||
const monthSet = new Set(months);
|
||||
return groupSum(
|
||||
dataset.finance.filter((row) => row.indicator === indicator && monthSet.has(row.month)),
|
||||
(row) => row.company,
|
||||
(row) => row[field],
|
||||
);
|
||||
}
|
||||
|
||||
/* --------------------------------- Регионы --------------------------------- */
|
||||
|
||||
/* --------------------------------- Дивизионы --------------------------------- */
|
||||
|
||||
export const MANAGEMENT_DIVISION = 'Управляющая компания';
|
||||
export const OTHER_DIVISION = 'Прочее';
|
||||
|
||||
/** Дивизион по наименованию организации или площадки. */
|
||||
export function divisionByCompanyName(dataset: Dataset): Map<string, string> {
|
||||
const map = new Map<string, string>();
|
||||
dataset.companies.forEach((company) => {
|
||||
if (company.division) map.set(company.name.toLowerCase(), company.division);
|
||||
});
|
||||
return map;
|
||||
}
|
||||
|
||||
export function resolveDivision(map: Map<string, string>, name: string): string {
|
||||
return map.get(name.toLowerCase()) ?? OTHER_DIVISION;
|
||||
}
|
||||
|
||||
export function isManagementDivision(division: string): boolean {
|
||||
return division.toLowerCase().includes('управляющ');
|
||||
}
|
||||
|
||||
/* --------------------------------- Периоды --------------------------------- */
|
||||
|
||||
/** Квартал месяца: 2026-07 -> 2026-Q3. */
|
||||
export function quarterOfMonth(month: string): string {
|
||||
const [year, monthNumber] = month.split('-');
|
||||
return `${year}-Q${Math.floor((Number(monthNumber) - 1) / 3) + 1}`;
|
||||
}
|
||||
|
||||
export function yearOf(key: string): string {
|
||||
return key.split('-')[0];
|
||||
}
|
||||
|
||||
/** Месяцы последнего квартала из набора. */
|
||||
export function monthsOfLastQuarter(months: string[]): string[] {
|
||||
const last = months[months.length - 1];
|
||||
if (!last) return [];
|
||||
const quarter = quarterOfMonth(last);
|
||||
return months.filter((month) => quarterOfMonth(month) === quarter);
|
||||
}
|
||||
|
||||
/** Месяцы года последнего месяца из набора. */
|
||||
export function monthsOfLastYear(months: string[]): string[] {
|
||||
const last = months[months.length - 1];
|
||||
if (!last) return [];
|
||||
const year = yearOf(last);
|
||||
return months.filter((month) => yearOf(month) === year);
|
||||
}
|
||||
|
||||
export function regionByCompanyName(dataset: Dataset): Map<string, string> {
|
||||
const map = new Map<string, string>();
|
||||
dataset.companies.forEach((company) => {
|
||||
if (company.region) map.set(company.name.toLowerCase(), company.region);
|
||||
});
|
||||
Object.entries(dataset.companyRegions ?? {}).forEach(([name, region]) => {
|
||||
if (!map.has(name)) map.set(name, region);
|
||||
});
|
||||
return map;
|
||||
}
|
||||
|
||||
export function resolveRegion(map: Map<string, string>, name: string): string | null {
|
||||
return map.get(name.toLowerCase()) ?? null;
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
const MONTH_SHORT = ['янв', 'фев', 'мар', 'апр', 'май', 'июн', 'июл', 'авг', 'сен', 'окт', 'ноя', 'дек'];
|
||||
const MONTH_FULL = [
|
||||
'январь', 'февраль', 'март', 'апрель', 'май', 'июнь',
|
||||
'июль', 'август', 'сентябрь', 'октябрь', 'ноябрь', 'декабрь',
|
||||
];
|
||||
|
||||
export function monthLabel(monthKey: string, full = false): string {
|
||||
if (!monthKey) return '';
|
||||
const [year, month] = monthKey.split('-');
|
||||
const index = Number(month) - 1;
|
||||
const name = full ? MONTH_FULL[index] : MONTH_SHORT[index];
|
||||
return full ? `${name} ${year}` : `${name} ${year.slice(2)}`;
|
||||
}
|
||||
|
||||
export function quarterLabel(key: string): string {
|
||||
const [year, quarter] = key.split('-Q');
|
||||
return `${quarter} кв. ${year}`;
|
||||
}
|
||||
|
||||
export function dateLabel(iso: string): string {
|
||||
if (!iso) return '';
|
||||
const [year, month, day] = iso.split('-');
|
||||
return `${day}.${month}.${year}`;
|
||||
}
|
||||
|
||||
export function shortDateLabel(iso: string): string {
|
||||
if (!iso) return '';
|
||||
const [, month, day] = iso.split('-');
|
||||
return `${day}.${month}`;
|
||||
}
|
||||
|
||||
/** Число с русскими разделителями и заданной точностью. */
|
||||
export function num(value: number | null | undefined, digits = 0): string {
|
||||
if (value === null || value === undefined || !Number.isFinite(value)) return '-';
|
||||
return value.toLocaleString('ru-RU', { minimumFractionDigits: digits, maximumFractionDigits: digits });
|
||||
}
|
||||
|
||||
export type Scaled = { value: string; suffix: string };
|
||||
|
||||
/**
|
||||
* Адаптивный формат числа: до тысячи - как есть, дальше - тысячи, миллионы
|
||||
* и миллиарды с одним знаком после запятой.
|
||||
* 842 -> 842
|
||||
* 351 550 -> 351,6 тыс
|
||||
* 125 230 000 -> 125,2 млн
|
||||
* 367 120 000 000 -> 367,1 млрд
|
||||
*/
|
||||
export function scale(value: number | null | undefined): Scaled {
|
||||
if (value === null || value === undefined || !Number.isFinite(value)) return { value: '-', suffix: '' };
|
||||
const abs = Math.abs(value);
|
||||
if (abs >= 1e9) return { value: num(value / 1e9, 1), suffix: 'млрд' };
|
||||
if (abs >= 1e6) return { value: num(value / 1e6, 1), suffix: 'млн' };
|
||||
if (abs >= 1e3) return { value: num(value / 1e3, 1), suffix: 'тыс' };
|
||||
return { value: Number.isInteger(value) ? num(value, 0) : num(value, 1), suffix: '' };
|
||||
}
|
||||
|
||||
/** Адаптивное число одной строкой: "351,55 тыс". */
|
||||
export function amount(value: number | null | undefined): string {
|
||||
const scaled = scale(value);
|
||||
return scaled.suffix ? `${scaled.value} ${scaled.suffix}` : scaled.value;
|
||||
}
|
||||
|
||||
/** Адаптивная сумма с валютой: "125,23 млн руб.". */
|
||||
export function money(value: number | null | undefined): string {
|
||||
if (value === null || value === undefined || !Number.isFinite(value)) return '-';
|
||||
return `${amount(value)} руб.`;
|
||||
}
|
||||
|
||||
/** Адаптивное количество людей: "12,13 тыс чел.". */
|
||||
export function people(value: number | null | undefined): string {
|
||||
if (value === null || value === undefined || !Number.isFinite(value)) return '-';
|
||||
return `${amount(value)} чел.`;
|
||||
}
|
||||
|
||||
/** Значение со знаком: "+2,45 млн". */
|
||||
export function signedAmount(value: number | null | undefined): string {
|
||||
if (value === null || value === undefined || !Number.isFinite(value)) return '-';
|
||||
return `${value > 0 ? '+' : value < 0 ? '-' : ''}${amount(Math.abs(value))}`;
|
||||
}
|
||||
|
||||
/** Доля в процентах: 0,0309 -> "3,1%". */
|
||||
export function percent(value: number | null | undefined, digits = 1): string {
|
||||
if (value === null || value === undefined || !Number.isFinite(value)) return '-';
|
||||
return `${num(value * 100, digits)}%`;
|
||||
}
|
||||
|
||||
export function signedPercent(value: number | null | undefined, digits = 1): string {
|
||||
if (value === null || value === undefined || !Number.isFinite(value)) return '-';
|
||||
return `${value > 0 ? '+' : ''}${num(value * 100, digits)}%`;
|
||||
}
|
||||
|
||||
export function ratio(current: number | null, previous: number | null): number | null {
|
||||
if (current === null || previous === null || previous === 0) return null;
|
||||
return current / previous - 1;
|
||||
}
|
||||
|
||||
/** Короткая подпись для оси графика: без валюты, с суффиксом. */
|
||||
export function axisValue(value: number): string {
|
||||
const abs = Math.abs(value);
|
||||
if (abs >= 1e9) return `${num(value / 1e9, 1)} млрд`;
|
||||
if (abs >= 1e6) return `${num(value / 1e6, 1)} млн`;
|
||||
if (abs >= 1e3) return `${num(value / 1e3, 1)} тыс`;
|
||||
return Number.isInteger(value) ? num(value, 0) : num(value, 1);
|
||||
}
|
||||
Reference in New Issue
Block a user