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(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) => { 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(); 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 Файл people.csv не найден или пуст. Положите выгрузку в каталог данных.; } return ( <> {/* Разбивки по дивизионам нет намеренно: заказчик их не использует, разрезы - юридические лица и регионы (решено 06.08.2026). */}
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)} /> {!hasPayroll ? В выгрузке нет показателя ФОТ : 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)} />} ({ key: company, highlight: selectedRegion !== null && resolveRegion(regionMap, company) === selectedRegion, cells: [ company, {amount(total)}, amount(oprLast.get(company) ?? 0), amount(rppLast.get(company) ?? 0), amount(rssLast.get(company) ?? 0), 0.04 ? ' warn' : ''}`}> {percent(absenceLast.get(company) ?? 0)} , 0.015 ? ' warn' : ''}`}> {percent(turnoverLast.get(company) ?? 0)} , amount(disabledLast.get(company) ?? 0), amount(svoLast.get(company) ?? 0), payrollLast.has(company) ? `${amount((payrollLast.get(company) ?? 0) * 1e6)} руб.` : 'нет данных', , ], }))} 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)} руб.` : 'нет данных', '', ]} /> amount(value)} selected={selectedRegion} onSelect={setSelectedRegion} newRegions={dataset.meta.newRegions ?? []} emptyHint="Площадок холдинга нет" /> ); } function sumValues(map: Map): number { return Array.from(map.values()).reduce((total, value) => total + value, 0); }