Files
shareholder-panel/client/src/sections/People.tsx
T
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

283 lines
14 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
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 { useMemo, useState } from 'react';
import type { Dataset } from '../types';
import { AmountCard, MetricCard, Panel, SectionHeader, DataTable, Change, Empty } from '../components/ui';
import { BarChart, LineChart } from '../components/charts';
import { RussiaMap, shortLabel } from '../components/RussiaMap';
import type { RegionValue } from '../components/RussiaMap';
import { amount, monthLabel, percent, ratio, people as peopleLabel } from '../lib/format';
import {
HEADCOUNT_METRICS,
headcountByCompany,
headcountByMonth,
metricByMonth,
monthsOfLastYear,
peopleMetricByCompany,
peopleMonths,
regionByCompanyName,
resolveRegion,
sortedEntries,
} from '../lib/aggregate';
export function People({ dataset }: { dataset: Dataset }) {
const months = useMemo(() => peopleMonths(dataset.people), [dataset.people]);
const [selectedRegion, setSelectedRegion] = useState<string | null>(null);
// раздел всегда показывает последний месяц в данных, фильтра периода нет
const visibleMonths = months;
const lastMonth = months[months.length - 1] ?? '';
const previousMonth = months[months.length - 2] ?? '';
const yearMonths = useMemo(() => monthsOfLastYear(months), [months]);
const regionMap = useMemo(() => regionByCompanyName(dataset), [dataset]);
const companiesLast = headcountByCompany(dataset.people, lastMonth);
const companiesPrevious = headcountByCompany(dataset.people, previousMonth);
const oprLast = peopleMetricByCompany(dataset.people, lastMonth, HEADCOUNT_METRICS[0]);
const rppLast = peopleMetricByCompany(dataset.people, lastMonth, HEADCOUNT_METRICS[1]);
const rssLast = peopleMetricByCompany(dataset.people, lastMonth, HEADCOUNT_METRICS[2]);
const absenceLast = peopleMetricByCompany(dataset.people, lastMonth, 'Абсентеизм');
const turnoverLast = peopleMetricByCompany(dataset.people, lastMonth, 'Текучесть');
const disabledLast = peopleMetricByCompany(dataset.people, lastMonth, 'Инвалиды');
const svoLast = peopleMetricByCompany(dataset.people, lastMonth, 'Участники СВО');
const payrollLast = peopleMetricByCompany(dataset.people, lastMonth, 'ФОТ');
// В выгрузке может не быть показателя ФОТ вовсе - тогда честнее написать
// «нет данных», чем показать «0 руб.» как факт.
const hasPayroll = dataset.people.some((row) => row.metric === 'ФОТ');
const noPayrollNote = 'в выгрузке нет показателя ФОТ';
const totalHeadcount = sumValues(companiesLast);
const totalPayroll = sumValues(payrollLast);
const headcountTotal = useMemo(() => headcountByMonth(dataset.people), [dataset.people]);
const payrollTotalByMonth = useMemo(
() => metricByMonth(dataset.people, 'ФОТ'),
[dataset.people],
);
// ФОТ с начала года: месяцы года последнего месяца (в выгрузке ФОТ в млн руб.).
// Пустой результат означает «в выгрузке нет ни одной строки ФОТ» - это
// «нет данных», а не «фонд оплаты труда равен нулю».
const ytdSum = (values: Map<string, number>) => {
const filled = yearMonths.filter((month) => values.has(month));
if (filled.length === 0) return null;
return filled.reduce((total, month) => total + (values.get(month) ?? 0), 0) * 1e6;
};
const totalPayrollYtd = ytdSum(payrollTotalByMonth);
const ytdNote = yearMonths.length > 0
? `с начала года: ${monthLabel(yearMonths[0], true)} - ${monthLabel(lastMonth, true)}`
: undefined;
// относительные показатели усредняем с весом по численности площадки
const weightedRate = (metric: string, month: string) => {
const weights = headcountByCompany(dataset.people, month);
const rows = dataset.people.filter((row) => row.metric === metric && row.month === month);
const totalWeight = rows.reduce((total, row) => total + (weights.get(row.company) ?? 1), 0);
if (totalWeight === 0) return null;
return rows.reduce((total, row) => total + row.value * (weights.get(row.company) ?? 1), 0) / totalWeight;
};
const absence = weightedRate('Абсентеизм', lastMonth);
const turnover = weightedRate('Текучесть', lastMonth);
const disabledTotal = sumValues(disabledLast);
const svoTotal = sumValues(svoLast);
const regionValues: RegionValue[] = useMemo(() => {
const totals = new Map<string, {
people: number; opr: number; rpp: number; rss: number;
payroll: number; hasPayroll: boolean; disabled: number; svo: number;
sites: { label: string; value: string; note?: string }[];
absenceWeighted: number; turnoverWeighted: number;
}>();
companiesLast.forEach((value, company) => {
const region = resolveRegion(regionMap, company);
if (!region) return;
const current = totals.get(region) ?? {
people: 0, opr: 0, rpp: 0, rss: 0, payroll: 0, hasPayroll: false, disabled: 0, svo: 0, sites: [],
absenceWeighted: 0, turnoverWeighted: 0,
};
current.people += value;
current.opr += oprLast.get(company) ?? 0;
current.rpp += rppLast.get(company) ?? 0;
current.rss += rssLast.get(company) ?? 0;
current.payroll += payrollLast.get(company) ?? 0;
if (payrollLast.has(company)) current.hasPayroll = true;
current.disabled += disabledLast.get(company) ?? 0;
current.svo += svoLast.get(company) ?? 0;
current.absenceWeighted += (absenceLast.get(company) ?? 0) * value;
current.turnoverWeighted += (turnoverLast.get(company) ?? 0) * value;
current.sites.push({
label: company,
value: `${amount(value)} чел.`,
});
totals.set(region, current);
});
return Array.from(totals.entries()).map(([region, item]) => ({
region,
short: shortLabel(region),
value: item.people,
note: totalHeadcount > 0
? `${percent(item.people / totalHeadcount)} численности холдинга`
: undefined,
sites: item.sites.slice().sort((a, b) => a.label.localeCompare(b.label, 'ru')),
sitesTitle: `Площадки в регионе: ${item.sites.length}`,
rows: [
{ label: 'Всего', value: peopleLabel(item.people) },
{ label: 'ОПР', value: amount(item.opr) },
{ label: 'РПП', value: amount(item.rpp) },
{ label: 'РСС', value: amount(item.rss) },
{ label: 'Абсентеизм', value: percent(item.people ? item.absenceWeighted / item.people : 0) },
{ label: 'Текучесть', value: percent(item.people ? item.turnoverWeighted / item.people : 0) },
{ label: 'Инвалиды', value: amount(item.disabled) },
{ label: 'Участники СВО', value: amount(item.svo), accent: true },
{ label: 'ФОТ за месяц', value: item.hasPayroll ? `${amount(item.payroll * 1e6)} руб.` : 'нет данных' },
{ label: 'Площадки', value: amount(item.sites.length) },
],
}));
}, [absenceLast, companiesLast, disabledLast, oprLast, payrollLast, regionMap, rppLast, rssLast, svoLast, totalHeadcount, turnoverLast]);
if (months.length === 0) {
return <Empty>Файл people.csv не найден или пуст. Положите выгрузку в каталог данных.</Empty>;
}
return (
<>
<SectionHeader
kicker="Человеческий капитал"
title="Люди"
description="Численность и фонд оплаты труда по холдингу, юридическим лицам и регионам присутствия."
period={`Данные за ${monthLabel(lastMonth, true)}`}
/>
{/* Разбивки по дивизионам нет намеренно: заказчик их не использует,
разрезы - юридические лица и регионы (решено 06.08.2026). */}
<div className="metrics-grid">
<MetricCard
label="Численность холдинга"
value={amount(totalHeadcount)}
unit="чел."
note={`на ${monthLabel(lastMonth, true)}`}
accent
/>
<AmountCard
label="ФОТ с начала года"
value={hasPayroll ? totalPayrollYtd : null}
note={hasPayroll ? ytdNote : noPayrollNote}
/>
<MetricCard
label="Абсентеизм"
value={absence === null ? 'нет данных' : percent(absence)}
note={`средневзвешенный - ${monthLabel(lastMonth, true)}`}
/>
<MetricCard
label="Текучесть"
value={turnover === null ? 'нет данных' : percent(turnover)}
note={`средневзвешенная - ${monthLabel(lastMonth, true)}`}
/>
</div>
<Panel title="Численность холдинга" note="чел. по месяцам">
<LineChart
categories={visibleMonths.map((month) => monthLabel(month))}
series={[{
key: 'headcount',
label: 'Холдинг',
values: visibleMonths.map((month) => headcountTotal.get(month) ?? null),
area: true,
}]}
formatValue={(value) => amount(value)}
formatTooltipValue={(value) => peopleLabel(value)}
tooltipTitle={(index) => monthLabel(visibleMonths[index], true)}
/>
</Panel>
<Panel title="Фонд оплаты труда по месяцам" note="по холдингу, руб.">
{!hasPayroll ? <Empty>В выгрузке нет показателя ФОТ</Empty> : <BarChart
height={300}
categories={visibleMonths.map((month) => monthLabel(month))}
series={[
{
key: 'payroll',
label: 'ФОТ',
values: visibleMonths.map((month) => (payrollTotalByMonth.get(month) ?? 0) * 1e6),
},
]}
formatValue={(value) => amount(value)}
formatTooltipValue={(value) => `${amount(value)} руб.`}
tooltipTitle={(index) => monthLabel(visibleMonths[index], true)}
/>}
</Panel>
<Panel title="Показатели по юридическим лицам" note={`за ${monthLabel(lastMonth, true)} - чел. / %`}>
<DataTable
fit
columns={[
{ key: 'company', label: 'Юридическое лицо', align: 'left', width: '21%' },
{ key: 'total', label: 'Всего', unit: 'чел.', width: '7%' },
{ key: 'opr', label: 'ОПР', unit: 'чел.', width: '7%' },
{ key: 'rpp', label: 'РПП', unit: 'чел.', width: '7%' },
{ key: 'rss', label: 'РСС', unit: 'чел.', width: '7%' },
{ key: 'absence', label: 'Абсентеизм', width: '8%' },
{ key: 'turnover', label: 'Текучесть', width: '8%' },
{ key: 'disabled', label: 'Инвалиды', width: '7%' },
{ key: 'svo', label: 'Участники СВО', width: '8%' },
{ key: 'payroll', label: 'ФОТ', unit: 'за месяц', width: '11%' },
{ key: 'change', label: 'К прошлому месяцу', width: '9%' },
]}
rows={sortedEntries(companiesLast).map(([company, total]) => ({
key: company,
highlight: selectedRegion !== null && resolveRegion(regionMap, company) === selectedRegion,
cells: [
company,
<b key="total">{amount(total)}</b>,
amount(oprLast.get(company) ?? 0),
amount(rppLast.get(company) ?? 0),
amount(rssLast.get(company) ?? 0),
<span key="a" className={`badge${(absenceLast.get(company) ?? 0) > 0.04 ? ' warn' : ''}`}>
{percent(absenceLast.get(company) ?? 0)}
</span>,
<span key="t" className={`badge${(turnoverLast.get(company) ?? 0) > 0.015 ? ' warn' : ''}`}>
{percent(turnoverLast.get(company) ?? 0)}
</span>,
amount(disabledLast.get(company) ?? 0),
amount(svoLast.get(company) ?? 0),
payrollLast.has(company) ? `${amount((payrollLast.get(company) ?? 0) * 1e6)} руб.` : 'нет данных',
<Change key="change" value={ratio(total, companiesPrevious.get(company) ?? null)} />,
],
}))}
footer={[
'Итого',
amount(totalHeadcount),
amount(sumValues(oprLast)),
amount(sumValues(rppLast)),
amount(sumValues(rssLast)),
percent(absence ?? 0),
percent(turnover ?? 0),
amount(disabledTotal),
amount(svoTotal),
hasPayroll ? `${amount(totalPayroll * 1e6)} руб.` : 'нет данных',
'',
]}
/>
</Panel>
<Panel title="Статистика по регионам РФ" note="нажмите на регион - в панели справа появятся его площадки">
<RussiaMap
values={regionValues}
legendTitle="Численность, чел."
formatValue={(value) => amount(value)}
selected={selectedRegion}
onSelect={setSelectedRegion}
newRegions={dataset.meta.newRegions ?? []}
emptyHint="Площадок холдинга нет"
/>
</Panel>
</>
);
}
function sumValues(map: Map<string, number>): number {
return Array.from(map.values()).reduce((total, value) => total + value, 0);
}