/* global Chart, ChartDataLabels */
(() => {
const D = window.__DASH__;
if (!D) {
document.body.innerHTML =
'
Нет данных. Запустите npm run dashboard:data
';
return;
}
Chart.register(ChartDataLabels);
Chart.defaults.font.family = 'Manrope, system-ui, sans-serif';
Chart.defaults.color = '#5c6b5a';
Chart.defaults.responsive = true;
Chart.defaults.maintainAspectRatio = false;
Chart.defaults.plugins.legend.labels.boxWidth = 12;
Chart.defaults.plugins.datalabels.display = false;
const COLORS = {
leaf: '#2f6b3a',
leafSoft: '#7a9a78',
wheat: '#b8892d',
wheatSoft: '#e6c87a',
risk: '#a33b2a',
soil: '#6b5a3e',
mid: '#8a7340',
grid: 'rgba(44,36,22,0.08)',
palette: ['#2f6b3a', '#b8892d', '#4f7cac', '#a33b2a', '#6b8f71', '#c4a35a', '#3d5a45', '#8b6b4a', '#5a7d6a', '#9c7a3c', '#2c4a3e'],
};
const charts = {};
const state = {
division: 'Все',
crop: 'Пшеница озимая',
};
const fmt = {
int: (n) => (n == null ? '—' : Number(n).toLocaleString('ru-RU')),
num: (n, d = 1) => (n == null || Number.isNaN(Number(n)) ? '—' : Number(n).toLocaleString('ru-RU', { maximumFractionDigits: d, minimumFractionDigits: d })),
ha: (n) => `${fmt.int(Math.round(n))} га`,
pct: (n) => `${fmt.num(n, 1)}%`,
};
function esc(s) {
return String(s)
.replace(/&/g, '&')
.replace(/"/g, '"')
.replace(//g, '>');
}
function shortDiv(name) {
if (!name) return '—';
return name
.replace(/^Дивизион\s+/i, '')
.replace(/^АО\s+/i, '')
.replace(/"/g, '')
.replace(/зерновая компания/i, 'КЗК');
}
function destroy(id) {
if (charts[id]) {
charts[id].destroy();
delete charts[id];
}
}
function makeChart(id, cfg) {
destroy(id);
const el = document.getElementById(id);
if (!el) return null;
cfg.options = cfg.options || {};
cfg.options.responsive = true;
cfg.options.maintainAspectRatio = false;
charts[id] = new Chart(el, cfg);
return charts[id];
}
function filteredDivisions() {
if (state.division === 'Все') return D.divisions;
return D.divisions.filter((d) => d.division === state.division);
}
function filterByDivision(rows, key = 'division') {
if (state.division === 'Все') return rows;
return rows.filter((r) => r[key] === state.division);
}
/* ---------- Header / filters ---------- */
function renderHeader() {
const o = D.overview;
document.getElementById('heroMeta').innerHTML = `
Период ${D.meta.yearFrom}–${D.meta.yearTo}
Урожайность в ${D.meta.productivityUnit}
Обновлено ${new Date(D.meta.generatedAt).toLocaleString('ru-RU')}
`;
document.getElementById('kpiStrip').innerHTML = `
Поля
${fmt.int(o.fieldsTotal)}
классиф. ${fmt.pct(o.clusteredSharePct)}
Площадь
${fmt.int(Math.round(o.areaTotalHa / 1000))}k
${fmt.ha(o.areaTotalHa)}
Индекс урожайности
${fmt.num(o.avgYieldIndex, 3)}
1.0 = норма дивизиона
Стабильность std
${fmt.num(o.avgStabilityStd, 3)}
ниже — ровнее
Звёзды
${fmt.int(o.starsN)}
${fmt.pct(o.starsSharePct)} классиф.
Зона риска
${fmt.int(o.riskN)}
${fmt.pct(o.riskSharePct)} классиф.
`;
document.getElementById('footMeta').textContent = D.meta.notes.join(' · ');
const insights = document.getElementById('insights');
insights.innerHTML = D.insights
.map(
(i) => `${i.title}
${i.text}
`
)
.join('');
const selD = document.getElementById('fltDivision');
const selC = document.getElementById('fltCrop');
selD.innerHTML =
`` +
D.filters.divisions.map((d) => ``).join('');
selC.innerHTML = D.filters.crops.map((c) => ``).join('');
selD.value = state.division;
selC.value = state.crop;
selD.onchange = () => {
state.division = selD.value;
refresh();
};
selC.onchange = () => {
state.crop = selC.value;
refresh();
};
document.getElementById('btnReset').onclick = () => {
state.division = 'Все';
state.crop = 'Пшеница озимая';
selD.value = state.division;
selC.value = state.crop;
refresh();
};
}
function updateHint() {
document.getElementById('filterHint').textContent =
state.division === 'Все'
? `Культура трендов: ${state.crop}`
: `Фильтр: ${shortDiv(state.division)} · ${state.crop}`;
}
/* ---------- Matrix ---------- */
function renderMatrix() {
const yields = ['Высокоурожайное', 'Среднее', 'Малоурожайное'];
const stabs = ['Стабильное', 'Нестабильное', 'Нет данных'];
const classMap = {
'Высокоурожайное|Стабильное': 'high-stable',
'Высокоурожайное|Нестабильное': 'high-unstable',
'Высокоурожайное|Нет данных': 'high-na',
'Среднее|Стабильное': 'mid-stable',
'Среднее|Нестабильное': 'mid-unstable',
'Среднее|Нет данных': 'mid-na',
'Малоурожайное|Стабильное': 'low-stable',
'Малоурожайное|Нестабильное': 'low-unstable',
'Малоурожайное|Нет данных': 'low-na',
};
let rows = D.clusterMatrix;
if (state.division !== 'Все') {
const map = new Map();
for (const r of D.clusterByDivision.filter((x) => x.division === state.division)) {
const k = `${r.yield_cat}|${r.stab_cat}`;
map.set(k, {
yield_cat: r.yield_cat,
stab_cat: r.stab_cat,
fields: r.fields,
area_ha: r.area_ha,
});
}
rows = [...map.values()];
}
const totalArea = rows.reduce((s, r) => s + (r.area_ha || 0), 0) || 1;
const lookup = Object.fromEntries(rows.map((r) => [`${r.yield_cat}|${r.stab_cat}`, r]));
const host = document.getElementById('matrix');
let html = ``;
html += stabs.map((s) => `${s}
`).join('');
for (const y of yields) {
html += `${y}
`;
for (const s of stabs) {
const cell = lookup[`${y}|${s}`] || { fields: 0, area_ha: 0 };
const share = ((cell.area_ha || 0) / totalArea) * 100;
html += `
${y.split(' ')[0]} · ${s.split(' ')[0]}
${fmt.pct(share)}
${fmt.int(cell.fields)} полей · ${fmt.int(cell.area_ha)} га
`;
}
}
host.innerHTML = html;
const port = state.division === 'Все' ? D.portfolio : rows.map((r) => ({
yield_cat: r.yield_cat,
stab_cat: r.stab_cat,
area_ha: r.area_ha,
area_share_pct: ((r.area_ha || 0) / totalArea) * 100,
}));
makeChart('chartPortfolio', {
type: 'bar',
data: {
labels: port.map((p) => `${p.yield_cat.replace('урожайное', '')} / ${p.stab_cat}`),
datasets: [
{
label: 'Доля площади, %',
data: port.map((p) => p.area_share_pct),
backgroundColor: port.map((p) =>
p.yield_cat === 'Высокоурожайное'
? COLORS.leaf
: p.yield_cat === 'Малоурожайное'
? COLORS.risk
: COLORS.wheat
),
borderRadius: 8,
},
],
},
options: {
indexAxis: 'y',
plugins: { legend: { display: false } },
scales: {
x: { grid: { color: COLORS.grid }, ticks: { callback: (v) => `${v}%` } },
y: { grid: { display: false } },
},
},
});
}
/* ---------- Scatter ---------- */
function renderScatter() {
let pts = D.scatter;
if (state.division !== 'Все') pts = pts.filter((p) => p.division === state.division);
const groups = {
'Высокоурожайное': { color: 'rgba(47,107,58,0.55)', data: [] },
'Среднее': { color: 'rgba(184,137,45,0.5)', data: [] },
'Малоурожайное': { color: 'rgba(163,59,42,0.5)', data: [] },
};
for (const p of pts) {
const g = groups[p.yield_cat];
if (!g) continue;
g.data.push({ x: p.x, y: p.y, r: Math.max(2, Math.min(8, (p.area_ha || 40) / 40)) });
}
makeChart('chartScatter', {
type: 'bubble',
data: {
datasets: Object.entries(groups).map(([label, g]) => ({
label,
data: g.data,
backgroundColor: g.color,
borderWidth: 0,
})),
},
options: {
plugins: {
tooltip: {
callbacks: {
label: (ctx) =>
`индекс ${ctx.raw.x}, std ${ctx.raw.y}`,
},
},
},
scales: {
x: {
title: { display: true, text: 'Индекс урожайности' },
grid: { color: COLORS.grid },
min: 0.5,
max: 1.5,
},
y: {
title: { display: true, text: 'Разброс стабильности (std)' },
grid: { color: COLORS.grid },
min: 0,
max: 0.6,
},
},
},
});
}
/* ---------- Divisions ---------- */
function renderDivisions() {
const rows = filteredDivisions().slice().sort((a, b) => (b.area_ha || 0) - (a.area_ha || 0));
makeChart('chartDivArea', {
type: 'doughnut',
data: {
labels: rows.map((r) => shortDiv(r.division)),
datasets: [
{
data: rows.map((r) => r.area_ha),
backgroundColor: COLORS.palette,
borderWidth: 2,
borderColor: '#fffcf5',
},
],
},
options: {
cutout: '58%',
plugins: {
legend: { position: 'right' },
title: { display: true, text: 'Площадь дивизионов, га', color: '#1e4d2b' },
},
},
});
makeChart('chartDivIndex', {
type: 'bar',
data: {
labels: rows.map((r) => shortDiv(r.division)),
datasets: [
{
label: 'Индекс урожайности',
data: rows.map((r) => r.avg_yield_index),
backgroundColor: rows.map((r) =>
r.avg_yield_index >= 1 ? COLORS.leaf : r.avg_yield_index >= 0.98 ? COLORS.wheat : COLORS.risk
),
borderRadius: 8,
},
],
},
options: {
plugins: {
legend: { display: false },
datalabels: {
display: true,
anchor: 'end',
align: 'top',
formatter: (v) => (v == null ? '' : Number(v).toFixed(3)),
color: '#1a2218',
font: { weight: '600', size: 10 },
},
},
scales: {
y: {
min: 0.9,
max: 1.1,
grid: { color: COLORS.grid },
title: { display: true, text: 'Индекс' },
},
x: { ticks: { maxRotation: 45, minRotation: 0 }, grid: { display: false } },
},
},
});
const tb = document.querySelector('#tblDivisions tbody');
tb.innerHTML = rows
.map(
(r) => `
| ${r.division} |
${fmt.int(r.fields)} |
${fmt.int(r.area_ha)} |
${fmt.num(r.avg_yield_index, 3)} |
${fmt.num(r.avg_stability_std, 3)} |
${fmt.int(r.stars)} |
${fmt.int(r.risk)} |
${fmt.int(r.high_yield)} |
${fmt.int(r.mid_yield)} |
${fmt.int(r.low_yield)} |
`
)
.join('');
}
/* ---------- Crop trends ---------- */
function renderCropTrends() {
const rows = D.byYearCrop.filter((r) => r.crop === state.crop);
makeChart('chartCropTrend', {
type: 'line',
data: {
labels: rows.map((r) => r.year),
datasets: [
{
label: 'Средняя, ц/га',
data: rows.map((r) => r.avg_prod),
borderColor: COLORS.leaf,
backgroundColor: 'rgba(47,107,58,0.12)',
fill: true,
tension: 0.35,
pointRadius: 4,
pointBackgroundColor: COLORS.leaf,
},
{
label: 'Медиана, ц/га',
data: rows.map((r) => r.median_prod),
borderColor: COLORS.wheat,
borderDash: [6, 4],
tension: 0.35,
pointRadius: 3,
pointBackgroundColor: COLORS.wheat,
},
],
},
options: {
plugins: { title: { display: true, text: state.crop, color: '#1e4d2b' } },
scales: {
y: { grid: { color: COLORS.grid }, title: { display: true, text: 'ц/га' } },
x: { grid: { display: false } },
},
},
});
// crop share for latest year in data for selected division filter (structure uses all)
const years = [...new Set(D.cropStructure.map((r) => r.year))].sort((a, b) => b - a);
const y = years[0];
let struct = D.cropStructure.filter((r) => r.year === y);
struct = struct.sort((a, b) => (b.area_ha || 0) - (a.area_ha || 0)).slice(0, 10);
makeChart('chartCropShare', {
type: 'bar',
data: {
labels: struct.map((r) => r.crop),
datasets: [
{
label: `Площадь ${y}, га`,
data: struct.map((r) => r.area_ha),
backgroundColor: COLORS.palette,
borderRadius: 8,
},
],
},
options: {
indexAxis: 'y',
plugins: { legend: { display: false } },
scales: {
x: { grid: { color: COLORS.grid } },
y: { grid: { display: false } },
},
},
});
let dc = D.byDivisionCrop.filter((r) => r.crop === state.crop);
dc = filterByDivision(dc);
dc = dc.sort((a, b) => (b.median_prod || 0) - (a.median_prod || 0));
makeChart('chartDivCrop', {
type: 'bar',
data: {
labels: dc.map((r) => shortDiv(r.division)),
datasets: [
{
label: 'Медиана, ц/га',
data: dc.map((r) => r.median_prod),
backgroundColor: COLORS.leaf,
borderRadius: 8,
},
{
label: 'Средняя, ц/га',
data: dc.map((r) => r.avg_prod),
backgroundColor: COLORS.wheatSoft,
borderRadius: 8,
},
],
},
options: {
plugins: { title: { display: true, text: `${state.crop}: дивизионы`, color: '#1e4d2b' } },
scales: {
y: { grid: { color: COLORS.grid }, title: { display: true, text: 'ц/га' } },
x: { grid: { display: false }, ticks: { maxRotation: 40 } },
},
},
});
}
/* ---------- Wheat ---------- */
function renderWheat() {
let rows = filterByDivision(D.wheatYoy);
const divisions = [...new Set(rows.map((r) => r.division))];
const years = [...new Set(rows.map((r) => r.year))].sort((a, b) => a - b);
makeChart('chartWheat', {
type: 'line',
data: {
labels: years,
datasets: divisions.map((div, i) => ({
label: shortDiv(div),
data: years.map((y) => {
const hit = rows.find((r) => r.division === div && r.year === y);
return hit ? hit.median_prod : null;
}),
borderColor: COLORS.palette[i % COLORS.palette.length],
backgroundColor: COLORS.palette[i % COLORS.palette.length],
tension: 0.3,
spanGaps: true,
pointRadius: 2,
})),
},
options: {
plugins: { legend: { position: 'bottom' } },
scales: {
y: { grid: { color: COLORS.grid }, title: { display: true, text: 'Медиана, ц/га' } },
x: { grid: { display: false } },
},
},
});
const fillWheatTable = (id, list) => {
let data = list;
if (state.division !== 'Все') data = data.filter((r) => r.division === state.division);
document.querySelector(`#${id} tbody`).innerHTML = data
.map(
(r, i) => `
| ${i + 1} |
${r.enterprise} |
${shortDiv(r.division)} |
${fmt.num(r.median_prod, 1)} |
${fmt.num(r.avg_prod, 1)} |
${fmt.int(r.fields)} |
`
)
.join('');
};
fillWheatTable('tblWheatTop', D.wheatEnterprises.top);
fillWheatTable('tblWheatBottom', D.wheatEnterprises.bottom);
}
/* ---------- Rotation / hist / area ---------- */
function renderAux() {
const rot = D.yearsRotation;
makeChart('chartRotation', {
type: 'bar',
data: {
labels: rot.map((r) => r.years),
datasets: [
{
type: 'bar',
label: 'Поля',
data: rot.map((r) => r.fields),
backgroundColor: 'rgba(122,154,120,0.45)',
yAxisID: 'y',
borderRadius: 6,
},
{
type: 'line',
label: 'Индекс урожайности',
data: rot.map((r) => r.avg_yield_index),
borderColor: COLORS.wheat,
backgroundColor: COLORS.wheat,
yAxisID: 'y1',
tension: 0.3,
},
],
},
options: {
scales: {
y: { position: 'left', grid: { color: COLORS.grid }, title: { display: true, text: 'Поля' } },
y1: {
position: 'right',
grid: { drawOnChartArea: false },
min: 0.9,
max: 1.1,
title: { display: true, text: 'Индекс' },
},
x: { title: { display: true, text: 'Лет в обороте' }, grid: { display: false } },
},
},
});
const hist = D.yieldIndexHist;
makeChart('chartHist', {
type: 'bar',
data: {
labels: hist.map((h) => `${fmt.num(h.idx_min, 2)}–${fmt.num(h.idx_max, 2)}`),
datasets: [
{
label: 'Поля',
data: hist.map((h) => h.fields),
backgroundColor: hist.map((h) =>
h.idx_avg >= 1.05 ? COLORS.leaf : h.idx_avg <= 0.95 ? COLORS.risk : COLORS.wheat
),
borderRadius: 6,
},
],
},
options: {
plugins: { legend: { display: false } },
scales: {
y: { grid: { color: COLORS.grid } },
x: { ticks: { maxRotation: 60, font: { size: 9 } }, grid: { display: false } },
},
},
});
makeChart('chartArea', {
type: 'bar',
data: {
labels: D.areaBuckets.map((a) => a.bucket),
datasets: [
{
label: 'Поля',
data: D.areaBuckets.map((a) => a.fields),
backgroundColor: COLORS.leafSoft,
borderRadius: 8,
},
],
},
options: {
plugins: { legend: { display: false } },
scales: {
y: { grid: { color: COLORS.grid } },
x: { grid: { display: false }, title: { display: true, text: 'Площадь поля, га' } },
},
},
});
}
/* ---------- Stars / risks / units ---------- */
function renderLists() {
const fill = (id, rows) => {
let data = rows;
if (state.division !== 'Все') data = data.filter((r) => r.division === state.division);
document.querySelector(`#${id} tbody`).innerHTML = data
.map(
(r) => `
| ${r.field_name} |
${shortDiv(r.division)} |
${r.enterprise || '—'} |
${fmt.num(r.area_ha, 1)} |
${fmt.num(r.yield_index, 3)} |
${fmt.num(r.stability_std, 3)} |
`
)
.join('');
};
fill('tblStars', D.stars);
fill('tblRisks', D.risks);
let units = filterByDivision(D.unitsRisk).slice(0, 12);
makeChart('chartUnitsRisk', {
type: 'bar',
data: {
labels: units.map((u) => `${shortDiv(u.division)} · ${u.unit}`.slice(0, 42)),
datasets: [
{
label: 'Доля риск-полей, %',
data: units.map((u) => u.risk_share_pct),
backgroundColor: COLORS.risk,
borderRadius: 6,
},
],
},
options: {
indexAxis: 'y',
plugins: { legend: { display: false } },
scales: {
x: { grid: { color: COLORS.grid }, ticks: { callback: (v) => `${v}%` } },
y: { grid: { display: false }, ticks: { font: { size: 10 } } },
},
},
});
document.querySelector('#tblUnits tbody').innerHTML = units
.map(
(u) => `
| ${u.division} |
${u.unit} |
${fmt.int(u.fields)} |
${fmt.int(u.area_ha)} |
${fmt.int(u.risk_fields)} |
${fmt.num(u.risk_share_pct, 1)} |
`
)
.join('');
}
/* ---------- Enterprises ---------- */
function renderEnterprises() {
let ents = filterByDivision(D.enterprises).filter((e) => e.avg_yield_index != null);
const top = ents.slice().sort((a, b) => b.avg_yield_index - a.avg_yield_index).slice(0, 12);
const bottom = ents.slice().sort((a, b) => a.avg_yield_index - b.avg_yield_index).slice(0, 12);
const mk = (id, list, color) =>
makeChart(id, {
type: 'bar',
data: {
labels: list.map((e) => e.enterprise.slice(0, 36)),
datasets: [
{
label: 'Индекс',
data: list.map((e) => e.avg_yield_index),
backgroundColor: color,
borderRadius: 6,
},
],
},
options: {
indexAxis: 'y',
plugins: {
legend: { display: false },
datalabels: {
display: true,
anchor: 'end',
align: 'right',
formatter: (v) => Number(v).toFixed(3),
font: { size: 10, weight: '600' },
color: '#1a2218',
},
},
scales: {
x: { min: 0.85, max: 1.2, grid: { color: COLORS.grid } },
y: { grid: { display: false }, ticks: { font: { size: 10 } } },
},
},
});
mk('chartEntTop', top, COLORS.leaf);
mk('chartEntBottom', bottom, COLORS.risk);
}
/* ---------- Coverage ---------- */
function renderCoverage() {
makeChart('chartCoverage', {
type: 'bar',
data: {
labels: D.coverage.map((c) => c.year),
datasets: [
{
label: 'С культурой',
data: D.coverage.map((c) => c.with_crop),
backgroundColor: COLORS.leafSoft,
borderRadius: 6,
},
{
label: 'С урожайностью',
data: D.coverage.map((c) => c.with_prod),
backgroundColor: COLORS.wheat,
borderRadius: 6,
},
],
},
options: {
scales: {
y: { grid: { color: COLORS.grid }, title: { display: true, text: 'Поле-лет' } },
x: { grid: { display: false } },
},
},
});
}
function refresh() {
updateHint();
renderMatrix();
renderScatter();
renderDivisions();
renderCropTrends();
renderWheat();
renderAux();
renderLists();
renderEnterprises();
renderCoverage();
}
renderHeader();
refresh();
// Chart.js иногда раздувает canvas до первого стабильного layout
requestAnimationFrame(() => {
Object.values(charts).forEach((c) => {
try { c.resize(); } catch (_) { /* ignore */ }
});
});
window.addEventListener('resize', () => {
Object.values(charts).forEach((c) => {
try { c.resize(); } catch (_) { /* ignore */ }
});
});
})();