init
This commit is contained in:
@@ -0,0 +1,533 @@
|
||||
(() => {
|
||||
const D = window.__FERT__;
|
||||
if (!D) {
|
||||
document.body.innerHTML =
|
||||
'<p style="padding:2rem;font-family:sans-serif">Нет данных. Запустите <code>npm run dashboard:fert</code></p>';
|
||||
return;
|
||||
}
|
||||
|
||||
const state = {
|
||||
divisions: new Set(),
|
||||
units: new Set(),
|
||||
years: new Set(),
|
||||
crops: new Set(['Пшеница озимая']),
|
||||
yieldCats: new Set(),
|
||||
stabCats: new Set(),
|
||||
prodOnly: true,
|
||||
focusOnly: true,
|
||||
};
|
||||
|
||||
const charts = {};
|
||||
const N_BINS = [
|
||||
{ key: '0', label: '0', lo: 0, hi: 0.01 },
|
||||
{ key: '1-50', label: '1–50', lo: 0.01, hi: 50 },
|
||||
{ key: '50-100', label: '50–100', lo: 50, hi: 100 },
|
||||
{ key: '100-150', label: '100–150', lo: 100, hi: 150 },
|
||||
{ key: '150-200', label: '150–200', lo: 150, hi: 200 },
|
||||
{ key: '200+', label: '200+', lo: 200, hi: Infinity },
|
||||
];
|
||||
|
||||
const fmt = {
|
||||
int: (n) => Number(n).toLocaleString('ru-RU'),
|
||||
num: (n, d = 1) =>
|
||||
n == null || Number.isNaN(Number(n))
|
||||
? '—'
|
||||
: Number(n).toLocaleString('ru-RU', {
|
||||
maximumFractionDigits: d,
|
||||
minimumFractionDigits: d,
|
||||
}),
|
||||
};
|
||||
|
||||
function median(arr) {
|
||||
if (!arr.length) return null;
|
||||
const s = [...arr].sort((a, b) => a - b);
|
||||
const m = Math.floor(s.length / 2);
|
||||
return s.length % 2 ? s[m] : (s[m - 1] + s[m]) / 2;
|
||||
}
|
||||
|
||||
function mean(arr) {
|
||||
if (!arr.length) return null;
|
||||
return arr.reduce((a, b) => a + b, 0) / arr.length;
|
||||
}
|
||||
|
||||
function nBin(v) {
|
||||
const n = Number(v) || 0;
|
||||
for (const b of N_BINS) {
|
||||
if (n >= b.lo && n < b.hi) return b;
|
||||
}
|
||||
return N_BINS[N_BINS.length - 1];
|
||||
}
|
||||
|
||||
function colorScale(t) {
|
||||
const c0 = [240, 228, 196];
|
||||
const c1 = [196, 163, 90];
|
||||
const c2 = [47, 107, 58];
|
||||
const mix = (a, b, p) => a.map((v, i) => Math.round(v + (b[i] - v) * p));
|
||||
const rgb = t < 0.5 ? mix(c0, c1, t * 2) : mix(c1, c2, (t - 0.5) * 2);
|
||||
return `rgb(${rgb.join(',')})`;
|
||||
}
|
||||
|
||||
function selected(set) {
|
||||
return [...set];
|
||||
}
|
||||
|
||||
function filterRows() {
|
||||
const divs = selected(state.divisions);
|
||||
const units = selected(state.units);
|
||||
const years = selected(state.years);
|
||||
const crops = selected(state.crops);
|
||||
const ycats = selected(state.yieldCats);
|
||||
const scats = selected(state.stabCats);
|
||||
|
||||
return D.rows.filter((r) => {
|
||||
if (state.focusOnly && !r.focus) return false;
|
||||
if (state.prodOnly && r.productivity == null) return false;
|
||||
if (divs.length && !divs.includes(r.division)) return false;
|
||||
if (units.length && !units.includes(r.unit)) return false;
|
||||
if (years.length && !years.includes(r.year)) return false;
|
||||
if (crops.length && !crops.includes(r.crop)) return false;
|
||||
if (ycats.length && !ycats.includes(r.yieldCat)) return false;
|
||||
if (scats.length && !scats.includes(r.stabCat)) return false;
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
function availableUnits() {
|
||||
const divs = selected(state.divisions);
|
||||
if (!divs.length) return D.filters.units;
|
||||
const set = new Set();
|
||||
for (const d of divs) {
|
||||
for (const u of D.cascade.unitsByDivision[d] || []) set.add(u);
|
||||
}
|
||||
return [...set].sort((a, b) => a.localeCompare(b, 'ru'));
|
||||
}
|
||||
|
||||
function buildMulti(el, options, set, label) {
|
||||
const panel = el.querySelector('[data-panel]');
|
||||
const title = el.querySelector('[data-label]');
|
||||
const updateTitle = () => {
|
||||
const n = set.size;
|
||||
title.textContent = n ? `${label}: ${n}` : label;
|
||||
};
|
||||
panel.innerHTML = `
|
||||
<div class="ms-actions">
|
||||
<button type="button" data-all>Все</button>
|
||||
<button type="button" data-none>Сброс</button>
|
||||
</div>
|
||||
${options
|
||||
.map((o) => {
|
||||
const val = String(o).replace(/&/g, '&').replace(/"/g, '"').replace(/</g, '<');
|
||||
const text = String(o).replace(/&/g, '&').replace(/</g, '<');
|
||||
return `<label><input type="checkbox" value="${val}" ${set.has(o) ? 'checked' : ''}/> <span>${text}</span></label>`;
|
||||
})
|
||||
.join('')}
|
||||
`;
|
||||
panel.querySelector('[data-all]').onclick = (e) => {
|
||||
e.preventDefault();
|
||||
options.forEach((o) => set.add(o));
|
||||
buildMulti(el, options, set, label);
|
||||
};
|
||||
panel.querySelector('[data-none]').onclick = (e) => {
|
||||
e.preventDefault();
|
||||
set.clear();
|
||||
buildMulti(el, options, set, label);
|
||||
};
|
||||
panel.querySelectorAll('input[type=checkbox]').forEach((inp) => {
|
||||
inp.onchange = () => {
|
||||
const opt = options.find((x) => String(x) === inp.value);
|
||||
if (opt === undefined) return;
|
||||
if (inp.checked) set.add(opt);
|
||||
else set.delete(opt);
|
||||
updateTitle();
|
||||
};
|
||||
});
|
||||
updateTitle();
|
||||
}
|
||||
|
||||
function refreshFilterOptions() {
|
||||
const units = new Set(availableUnits());
|
||||
for (const u of [...state.units]) if (!units.has(u)) state.units.delete(u);
|
||||
|
||||
const cropOpts = state.focusOnly ? D.filters.focusCrops : D.filters.crops;
|
||||
for (const c of [...state.crops]) if (!cropOpts.includes(c)) state.crops.delete(c);
|
||||
|
||||
buildMulti(document.getElementById('msDivision'), D.filters.divisions, state.divisions, 'Дивизион');
|
||||
buildMulti(document.getElementById('msUnit'), availableUnits(), state.units, 'Подразделение');
|
||||
buildMulti(document.getElementById('msYear'), D.filters.years, state.years, 'Год');
|
||||
buildMulti(document.getElementById('msCrop'), cropOpts, state.crops, 'Культура');
|
||||
buildMulti(document.getElementById('msYieldCat'), D.filters.yieldCats, state.yieldCats, 'Категория урожайности');
|
||||
buildMulti(document.getElementById('msStabCat'), D.filters.stabCats, state.stabCats, 'Стабильность');
|
||||
}
|
||||
|
||||
function makeChart(id, cfg) {
|
||||
const el = document.getElementById(id);
|
||||
if (!el) return null;
|
||||
if (charts[id]) {
|
||||
charts[id].destroy();
|
||||
delete charts[id];
|
||||
}
|
||||
charts[id] = new Chart(el, cfg);
|
||||
return charts[id];
|
||||
}
|
||||
|
||||
function renderKpi(rows) {
|
||||
const prods = rows.map((r) => r.productivity).filter((x) => x != null);
|
||||
const ns = rows.map((r) => r.nKgHa).filter((x) => x != null);
|
||||
const manure = rows.filter((r) => (r.manureKgHa || 0) > 0);
|
||||
const bal = rows.map((r) => r.nBalance).filter((x) => x != null);
|
||||
document.getElementById('kpiStrip').innerHTML = `
|
||||
<div class="kpi"><div class="label">В выборке</div><div class="value">${fmt.int(rows.length)}</div><div class="sub">из ${fmt.int(D.meta.rowsClean)}</div></div>
|
||||
<div class="kpi gold"><div class="label">Медиана ц/га</div><div class="value">${fmt.num(median(prods), 1)}</div></div>
|
||||
<div class="kpi"><div class="label">Медиана N, кг/га</div><div class="value">${fmt.num(median(ns), 0)}</div></div>
|
||||
<div class="kpi"><div class="label">Медиана баланс N</div><div class="value">${fmt.num(median(bal), 0)}</div><div class="sub">кг д.в./га</div></div>
|
||||
<div class="kpi good"><div class="label">С органикой</div><div class="value">${fmt.int(manure.length)}</div><div class="sub">${rows.length ? fmt.num((100 * manure.length) / rows.length, 1) + '%' : '—'}</div></div>
|
||||
<div class="kpi"><div class="label">Связано с fields</div><div class="value">${fmt.int(rows.filter((r) => r.linked).length)}</div></div>
|
||||
`;
|
||||
}
|
||||
|
||||
function renderDoseN(rows) {
|
||||
const byCrop = new Map();
|
||||
for (const r of rows) {
|
||||
if (r.productivity == null) continue;
|
||||
if (!byCrop.has(r.crop)) byCrop.set(r.crop, []);
|
||||
byCrop.get(r.crop).push(r);
|
||||
}
|
||||
const crops = [...byCrop.keys()].sort((a, b) => a.localeCompare(b, 'ru')).slice(0, 4);
|
||||
const palette = ['#2f6b3a', '#b8892d', '#4a6fa5', '#a33b2a'];
|
||||
|
||||
const datasets = crops.map((crop, i) => {
|
||||
const group = byCrop.get(crop);
|
||||
const xs = [];
|
||||
const ys = [];
|
||||
const sizes = [];
|
||||
for (const b of N_BINS) {
|
||||
const chunk = group.filter((r) => {
|
||||
const bb = nBin(r.nKgHa);
|
||||
return bb.key === b.key;
|
||||
});
|
||||
if (chunk.length < 5) continue;
|
||||
const mid =
|
||||
b.hi === Infinity ? b.lo + 50 : b.lo === 0 && b.hi < 1 ? 0 : (b.lo + b.hi) / 2;
|
||||
xs.push(mid);
|
||||
ys.push(median(chunk.map((r) => r.productivity)));
|
||||
sizes.push(chunk.length);
|
||||
}
|
||||
return {
|
||||
label: crop,
|
||||
data: xs.map((x, j) => ({ x, y: ys[j], n: sizes[j] })),
|
||||
borderColor: palette[i % palette.length],
|
||||
backgroundColor: palette[i % palette.length],
|
||||
showLine: true,
|
||||
tension: 0.25,
|
||||
pointRadius: (ctx) => {
|
||||
const n = ctx.raw?.n || 5;
|
||||
return Math.min(14, 4 + Math.sqrt(n) / 2);
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
makeChart('chartDoseN', {
|
||||
type: 'scatter',
|
||||
data: { datasets },
|
||||
options: {
|
||||
responsive: true,
|
||||
maintainAspectRatio: false,
|
||||
plugins: {
|
||||
legend: { position: 'bottom' },
|
||||
tooltip: {
|
||||
callbacks: {
|
||||
label: (ctx) =>
|
||||
`${ctx.dataset.label}: N≈${fmt.num(ctx.raw.x, 0)} → ${fmt.num(ctx.raw.y, 1)} ц/га (n=${ctx.raw.n})`,
|
||||
},
|
||||
},
|
||||
},
|
||||
scales: {
|
||||
x: {
|
||||
title: { display: true, text: 'N, кг/га (середина бина)' },
|
||||
grid: { color: 'rgba(44,36,22,0.06)' },
|
||||
},
|
||||
y: {
|
||||
title: { display: true, text: 'Медиана, ц/га' },
|
||||
grid: { color: 'rgba(44,36,22,0.06)' },
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function renderBalance(rows) {
|
||||
const withBal = rows.filter((r) => r.nBalance != null && r.productivity != null);
|
||||
const bins = [
|
||||
{ label: '< −80', lo: -Infinity, hi: -80 },
|
||||
{ label: '−80…−40', lo: -80, hi: -40 },
|
||||
{ label: '−40…0', lo: -40, hi: 0 },
|
||||
{ label: '0…40', lo: 0, hi: 40 },
|
||||
{ label: '40…80', lo: 40, hi: 80 },
|
||||
{ label: '> 80', lo: 80, hi: Infinity },
|
||||
];
|
||||
const labels = [];
|
||||
const meds = [];
|
||||
const counts = [];
|
||||
for (const b of bins) {
|
||||
const chunk = withBal.filter((r) => r.nBalance >= b.lo && r.nBalance < b.hi);
|
||||
if (!chunk.length) {
|
||||
labels.push(b.label);
|
||||
meds.push(null);
|
||||
counts.push(0);
|
||||
continue;
|
||||
}
|
||||
labels.push(b.label);
|
||||
meds.push(median(chunk.map((r) => r.productivity)));
|
||||
counts.push(chunk.length);
|
||||
}
|
||||
|
||||
makeChart('chartBalance', {
|
||||
type: 'bar',
|
||||
data: {
|
||||
labels,
|
||||
datasets: [
|
||||
{
|
||||
label: 'Медиана ц/га',
|
||||
data: meds,
|
||||
backgroundColor: '#2f6b3a',
|
||||
borderRadius: 8,
|
||||
},
|
||||
],
|
||||
},
|
||||
options: {
|
||||
responsive: true,
|
||||
maintainAspectRatio: false,
|
||||
plugins: {
|
||||
legend: { display: false },
|
||||
tooltip: {
|
||||
callbacks: {
|
||||
afterLabel: (ctx) => `n = ${counts[ctx.dataIndex]}`,
|
||||
},
|
||||
},
|
||||
},
|
||||
scales: {
|
||||
x: { title: { display: true, text: 'Баланс N, кг/га' }, grid: { display: false } },
|
||||
y: { title: { display: true, text: 'ц/га' }, grid: { color: 'rgba(44,36,22,0.06)' } },
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function renderNpk(rows) {
|
||||
makeChart('chartNpk', {
|
||||
type: 'bar',
|
||||
data: {
|
||||
labels: ['N', 'P₂O₅', 'K₂O', 'Масса удобр.', 'Органика'],
|
||||
datasets: [
|
||||
{
|
||||
label: 'Медиана кг/га',
|
||||
data: [
|
||||
median(rows.map((r) => r.nKgHa).filter((x) => x != null)),
|
||||
median(rows.map((r) => r.pKgHa).filter((x) => x != null)),
|
||||
median(rows.map((r) => r.kKgHa).filter((x) => x != null)),
|
||||
median(rows.map((r) => r.massKgHa).filter((x) => x != null)),
|
||||
median(
|
||||
rows
|
||||
.map((r) => r.manureKgHa)
|
||||
.filter((x) => x != null && x > 0)
|
||||
),
|
||||
],
|
||||
backgroundColor: ['#2f6b3a', '#4a6fa5', '#b8892d', '#7a9a78', '#8a7340'],
|
||||
borderRadius: 8,
|
||||
},
|
||||
],
|
||||
},
|
||||
options: {
|
||||
responsive: true,
|
||||
maintainAspectRatio: false,
|
||||
plugins: { legend: { display: false } },
|
||||
scales: {
|
||||
y: { title: { display: true, text: 'кг/га' }, grid: { color: 'rgba(44,36,22,0.06)' } },
|
||||
x: { grid: { display: false } },
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function renderHeat(rows) {
|
||||
const host = document.getElementById('heatNCat');
|
||||
const withProd = rows.filter((r) => r.productivity != null && r.yieldCat && r.yieldCat !== '—');
|
||||
const cats = [...new Set(withProd.map((r) => r.yieldCat))].sort((a, b) =>
|
||||
a.localeCompare(b, 'ru')
|
||||
);
|
||||
if (!cats.length) {
|
||||
host.innerHTML = '<p class="warn">Недостаточно строк с категорией урожайности.</p>';
|
||||
return;
|
||||
}
|
||||
|
||||
const cell = new Map();
|
||||
let minM = Infinity;
|
||||
let maxM = -Infinity;
|
||||
for (const cat of cats) {
|
||||
for (const b of N_BINS) {
|
||||
const chunk = withProd.filter((r) => r.yieldCat === cat && nBin(r.nKgHa).key === b.key);
|
||||
if (chunk.length < 3) continue;
|
||||
const m = median(chunk.map((r) => r.productivity));
|
||||
cell.set(`${cat}|${b.key}`, { m, n: chunk.length });
|
||||
if (m < minM) minM = m;
|
||||
if (m > maxM) maxM = m;
|
||||
}
|
||||
}
|
||||
const span = maxM - minM || 1;
|
||||
|
||||
let html = `<div class="heat-wrap"><div class="heat-grid" style="grid-template-columns: 120px repeat(${N_BINS.length}, 52px);">`;
|
||||
html += `<div class="heat-corner">кат. ↓ / N →</div>`;
|
||||
for (const b of N_BINS) html += `<div class="heat-x">${b.label}</div>`;
|
||||
for (const cat of cats) {
|
||||
html += `<div class="heat-y">${cat}</div>`;
|
||||
for (const b of N_BINS) {
|
||||
const v = cell.get(`${cat}|${b.key}`);
|
||||
if (!v) {
|
||||
html += `<div class="heat-cell empty" style="width:52px;height:36px" title="нет данных"></div>`;
|
||||
continue;
|
||||
}
|
||||
const t = (v.m - minM) / span;
|
||||
html += `<div class="heat-cell" style="width:52px;height:36px;background:${colorScale(t)}" title="${cat}, N ${b.label}: ${v.m.toFixed(1)} ц/га (n=${v.n})">${v.m.toFixed(0)}</div>`;
|
||||
}
|
||||
}
|
||||
html += `</div></div>
|
||||
<div class="heat-legend"><span>ниже</span><div class="bar"></div><span>выше, ц/га</span></div>`;
|
||||
host.innerHTML = html;
|
||||
}
|
||||
|
||||
function renderManure(rows) {
|
||||
const withP = rows.filter((r) => r.productivity != null);
|
||||
const org = withP.filter((r) => (r.manureKgHa || 0) > 0);
|
||||
const no = withP.filter((r) => !(r.manureKgHa > 0));
|
||||
document.getElementById('manureMeta').textContent =
|
||||
`С органикой: ${org.length}, без: ${no.length}. Сравнение медиан урожайности.`;
|
||||
|
||||
makeChart('chartManure', {
|
||||
type: 'bar',
|
||||
data: {
|
||||
labels: ['Без органики', 'С навозом / ППЖ'],
|
||||
datasets: [
|
||||
{
|
||||
label: 'Медиана ц/га',
|
||||
data: [
|
||||
median(no.map((r) => r.productivity)),
|
||||
median(org.map((r) => r.productivity)),
|
||||
],
|
||||
backgroundColor: ['#c4a35a', '#2f6b3a'],
|
||||
borderRadius: 8,
|
||||
},
|
||||
],
|
||||
},
|
||||
options: {
|
||||
responsive: true,
|
||||
maintainAspectRatio: false,
|
||||
plugins: {
|
||||
legend: { display: false },
|
||||
tooltip: {
|
||||
callbacks: {
|
||||
afterLabel: (ctx) => `n = ${ctx.dataIndex === 0 ? no.length : org.length}`,
|
||||
},
|
||||
},
|
||||
},
|
||||
scales: {
|
||||
y: { title: { display: true, text: 'ц/га' }, grid: { color: 'rgba(44,36,22,0.06)' } },
|
||||
x: { grid: { display: false } },
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function renderTable(rows) {
|
||||
const tbody = document.querySelector('#tblSample tbody');
|
||||
const sample = [...rows]
|
||||
.sort((a, b) => (b.productivity || 0) - (a.productivity || 0))
|
||||
.slice(0, 300);
|
||||
document.getElementById('sampleMeta').textContent =
|
||||
`Показаны топ-${sample.length} по урожайности из ${rows.length} в фильтре`;
|
||||
tbody.innerHTML = sample
|
||||
.map(
|
||||
(r) => `<tr>
|
||||
<td>${esc(r.field)}</td>
|
||||
<td>${esc(r.division)}</td>
|
||||
<td>${r.year}</td>
|
||||
<td>${esc(r.crop)}</td>
|
||||
<td>${fmt.num(r.nKgHa, 0)}</td>
|
||||
<td>${fmt.num(r.pKgHa, 0)}</td>
|
||||
<td>${fmt.num(r.kKgHa, 0)}</td>
|
||||
<td>${fmt.num(r.manureKgHa, 0)}</td>
|
||||
<td>${fmt.num(r.nBalance, 0)}</td>
|
||||
<td>${fmt.num(r.productivity, 1)}</td>
|
||||
<td>${esc(r.yieldCat)}</td>
|
||||
<td>${fmt.num(r.areaHa, 0)}</td>
|
||||
</tr>`
|
||||
)
|
||||
.join('');
|
||||
}
|
||||
|
||||
function esc(s) {
|
||||
return String(s ?? '')
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>');
|
||||
}
|
||||
|
||||
function renderNotes() {
|
||||
const ul = document.getElementById('notesList');
|
||||
ul.innerHTML = (D.meta.notes || [])
|
||||
.map((n) => `<li>${esc(n)}</li>`)
|
||||
.join('');
|
||||
const rem = D.removalPerT || {};
|
||||
const remLines = Object.entries(rem)
|
||||
.slice(0, 6)
|
||||
.map(
|
||||
([crop, v]) =>
|
||||
`<li>Вынос ${esc(crop)}: N ${v.n}, P₂O₅ ${v.p}, K₂O ${v.k} кг/т продукции</li>`
|
||||
)
|
||||
.join('');
|
||||
ul.innerHTML += remLines;
|
||||
}
|
||||
|
||||
function render() {
|
||||
state.prodOnly = document.getElementById('chkProdOnly').checked;
|
||||
state.focusOnly = document.getElementById('chkFocusOnly').checked;
|
||||
refreshFilterOptions();
|
||||
const rows = filterRows();
|
||||
renderKpi(rows);
|
||||
renderDoseN(rows);
|
||||
renderBalance(rows);
|
||||
renderNpk(rows);
|
||||
renderHeat(rows);
|
||||
renderManure(rows);
|
||||
renderTable(rows);
|
||||
document.getElementById('footMeta').textContent =
|
||||
`Сгенерировано ${new Date(D.meta.generatedAt).toLocaleString('ru-RU')} · строк ${D.meta.rowsClean}`;
|
||||
}
|
||||
|
||||
document.getElementById('btnApply').onclick = () => render();
|
||||
document.getElementById('btnReset').onclick = () => {
|
||||
state.divisions.clear();
|
||||
state.units.clear();
|
||||
state.years.clear();
|
||||
state.crops = new Set(['Пшеница озимая']);
|
||||
state.yieldCats.clear();
|
||||
state.stabCats.clear();
|
||||
document.getElementById('chkProdOnly').checked = true;
|
||||
document.getElementById('chkFocusOnly').checked = true;
|
||||
render();
|
||||
};
|
||||
document.getElementById('chkProdOnly').onchange = () => render();
|
||||
document.getElementById('chkFocusOnly').onchange = () => render();
|
||||
|
||||
// close other dropdowns
|
||||
document.querySelectorAll('.ms').forEach((ms) => {
|
||||
ms.addEventListener('toggle', () => {
|
||||
if (!ms.open) return;
|
||||
document.querySelectorAll('.ms').forEach((o) => {
|
||||
if (o !== ms) o.open = false;
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
renderNotes();
|
||||
render();
|
||||
})();
|
||||
Reference in New Issue
Block a user