Files
2026-11-10 16:34:01 +03:00

762 lines
26 KiB
JavaScript
Raw Permalink 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.
/* global Chart, ChartDataLabels */
(() => {
const D = window.__DASH__;
if (!D) {
document.body.innerHTML =
'<p style="padding:2rem;font-family:sans-serif">Нет данных. Запустите <code>npm run dashboard:data</code></p>';
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, '&amp;')
.replace(/"/g, '&quot;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;');
}
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 = `
<span class="chip">Период ${D.meta.yearFrom}–${D.meta.yearTo}</span>
<span class="chip">Урожайность в ${D.meta.productivityUnit}</span>
<span class="chip">Обновлено ${new Date(D.meta.generatedAt).toLocaleString('ru-RU')}</span>
`;
document.getElementById('kpiStrip').innerHTML = `
<div class="kpi"><div class="label">Поля</div><div class="value">${fmt.int(o.fieldsTotal)}</div><div class="sub">классиф. ${fmt.pct(o.clusteredSharePct)}</div></div>
<div class="kpi"><div class="label">Площадь</div><div class="value">${fmt.int(Math.round(o.areaTotalHa / 1000))}k</div><div class="sub">${fmt.ha(o.areaTotalHa)}</div></div>
<div class="kpi gold"><div class="label">Индекс урожайности</div><div class="value">${fmt.num(o.avgYieldIndex, 3)}</div><div class="sub">1.0 = норма дивизиона</div></div>
<div class="kpi"><div class="label">Стабильность std</div><div class="value">${fmt.num(o.avgStabilityStd, 3)}</div><div class="sub">ниже — ровнее</div></div>
<div class="kpi good"><div class="label">Звёзды</div><div class="value">${fmt.int(o.starsN)}</div><div class="sub">${fmt.pct(o.starsSharePct)} классиф.</div></div>
<div class="kpi risk"><div class="label">Зона риска</div><div class="value">${fmt.int(o.riskN)}</div><div class="sub">${fmt.pct(o.riskSharePct)} классиф.</div></div>
`;
document.getElementById('footMeta').textContent = D.meta.notes.join(' · ');
const insights = document.getElementById('insights');
insights.innerHTML = D.insights
.map(
(i) => `<article class="insight"><h3>${i.title}</h3><p>${i.text}</p></article>`
)
.join('');
const selD = document.getElementById('fltDivision');
const selC = document.getElementById('fltCrop');
selD.innerHTML =
`<option value="Все">Все дивизионы</option>` +
D.filters.divisions.map((d) => `<option value="${esc(d)}">${esc(d)}</option>`).join('');
selC.innerHTML = D.filters.crops.map((c) => `<option value="${esc(c)}">${esc(c)}</option>`).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 = `<div class="corner"></div>`;
html += stabs.map((s) => `<div class="colh">${s}</div>`).join('');
for (const y of yields) {
html += `<div class="rowh">${y}</div>`;
for (const s of stabs) {
const cell = lookup[`${y}|${s}`] || { fields: 0, area_ha: 0 };
const share = ((cell.area_ha || 0) / totalArea) * 100;
html += `<div class="mcell ${classMap[`${y}|${s}`]}">
<div class="m-title">${y.split(' ')[0]} · ${s.split(' ')[0]}</div>
<div class="m-val">${fmt.pct(share)}</div>
<div class="m-sub">${fmt.int(cell.fields)} полей · ${fmt.int(cell.area_ha)} га</div>
</div>`;
}
}
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) => `<tr>
<td>${r.division}</td>
<td class="num">${fmt.int(r.fields)}</td>
<td class="num">${fmt.int(r.area_ha)}</td>
<td class="num">${fmt.num(r.avg_yield_index, 3)}</td>
<td class="num">${fmt.num(r.avg_stability_std, 3)}</td>
<td class="num"><span class="badge good">${fmt.int(r.stars)}</span></td>
<td class="num"><span class="badge risk">${fmt.int(r.risk)}</span></td>
<td class="num">${fmt.int(r.high_yield)}</td>
<td class="num">${fmt.int(r.mid_yield)}</td>
<td class="num">${fmt.int(r.low_yield)}</td>
</tr>`
)
.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) => `<tr>
<td class="num">${i + 1}</td>
<td>${r.enterprise}</td>
<td>${shortDiv(r.division)}</td>
<td class="num">${fmt.num(r.median_prod, 1)}</td>
<td class="num">${fmt.num(r.avg_prod, 1)}</td>
<td class="num">${fmt.int(r.fields)}</td>
</tr>`
)
.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) => `<tr>
<td>${r.field_name}</td>
<td>${shortDiv(r.division)}</td>
<td>${r.enterprise || '—'}</td>
<td class="num">${fmt.num(r.area_ha, 1)}</td>
<td class="num">${fmt.num(r.yield_index, 3)}</td>
<td class="num">${fmt.num(r.stability_std, 3)}</td>
</tr>`
)
.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) => `<tr>
<td>${u.division}</td>
<td>${u.unit}</td>
<td class="num">${fmt.int(u.fields)}</td>
<td class="num">${fmt.int(u.area_ha)}</td>
<td class="num">${fmt.int(u.risk_fields)}</td>
<td class="num"><span class="badge risk">${fmt.num(u.risk_share_pct, 1)}</span></td>
</tr>`
)
.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 */ }
});
});
})();