(() => { const D = window.__DATES__; if (!D) { document.body.innerHTML = '

Нет данных. Запустите npm run dashboard:dates

'; return; } const state = { divisions: new Set(), units: new Set(), years: new Set(), crops: new Set(['Пшеница озимая']), varieties: new Set(), }; 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 isoWeek(iso) { const d = new Date(`${iso}T00:00:00Z`); const day = d.getUTCDay() || 7; d.setUTCDate(d.getUTCDate() + 4 - day); const yearStart = new Date(Date.UTC(d.getUTCFullYear(), 0, 1)); return Math.ceil(((d - yearStart) / 86400000 + 1) / 7); } function weekLabel(w) { return `н${String(w).padStart(2, '0')}`; } function daysBetween(a, b) { const ms = new Date(`${b}T00:00:00Z`) - new Date(`${a}T00:00:00Z`); return Math.round(ms / 86400000); } 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 colorScale(t) { // 0 → wheat pale, 1 → deep leaf 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 vars = selected(state.varieties); return D.rows.filter((r) => { 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 (vars.length && !vars.includes(r.variety)) 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 availableVarieties() { const crops = selected(state.crops); if (!crops.length) return D.filters.varieties; const set = new Set(); for (const c of crops) { for (const v of D.cascade.varietiesByCrop[c] || []) set.add(v); } 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 = `
${options .map((o) => { const val = String(o).replace(/&/g, '&').replace(/"/g, '"').replace(/ ${text}`; }) .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() { // prune invalid selections const units = new Set(availableUnits()); for (const u of [...state.units]) if (!units.has(u)) state.units.delete(u); const vars = new Set(availableVarieties()); for (const v of [...state.varieties]) if (!vars.has(v)) state.varieties.delete(v); 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'), D.filters.crops, state.crops, 'Культура'); buildMulti(document.getElementById('msVariety'), availableVarieties(), state.varieties, 'Гибрид / сорт'); } function buildHeatmap(rows, crop) { const cropRows = rows.filter((r) => r.crop === crop); if (!cropRows.length) return ''; const cells = new Map(); // key sowWeek|harvWeek -> prods[] const sowWeeks = new Set(); const harvWeeks = new Set(); for (const r of cropRows) { const sw = isoWeek(r.sowing); const hw = isoWeek(r.harvest); sowWeeks.add(sw); harvWeeks.add(hw); const key = `${sw}|${hw}`; if (!cells.has(key)) cells.set(key, []); cells.get(key).push(r.productivity); } const xs = [...sowWeeks].sort((a, b) => a - b); const ys = [...harvWeeks].sort((a, b) => a - b); const medians = []; for (const vals of cells.values()) medians.push(median(vals)); const vmin = Math.min(...medians); const vmax = Math.max(...medians); const span = vmax - vmin || 1; const allProds = cropRows.map((r) => r.productivity); const kpi = { n: cropRows.length, median: median(allProds), mean: mean(allProds), days: mean(cropRows.map((r) => daysBetween(r.sowing, r.harvest))), }; let html = `

${crop}

Наблюдений
${fmt.int(kpi.n)}
Медиана, ц/га
${fmt.num(kpi.median, 1)}
Средняя, ц/га
${fmt.num(kpi.mean, 1)}
Ср. вегетация, дней
${fmt.num(kpi.days, 0)}
`; html += `
уборка ↓ / сев →
`; for (const x of xs) html += `
${weekLabel(x)}
`; for (const y of ys) { html += `
${weekLabel(y)}
`; for (const x of xs) { const vals = cells.get(`${x}|${y}`); if (!vals || !vals.length) { html += `
`; continue; } const med = median(vals); const t = (med - vmin) / span; const title = `Сев ${weekLabel(x)}, уборка ${weekLabel(y)}\nмедиана ${med.toFixed(1)} ц/га\nn=${vals.length}`; html += `
${med.toFixed(0)}
`; } } html += `
${fmt.num(vmin, 1)} ${fmt.num(vmax, 1)} ц/га · ячейка = медиана урожайности, подпись — ц/га, пустые — нет наблюдений
`; return html; } function render() { const rows = filterRows(); const crops = selected(state.crops); const cropList = crops.length ? crops : [...new Set(rows.map((r) => r.crop))].sort((a, b) => a.localeCompare(b, 'ru')); const prods = rows.map((r) => r.productivity); document.getElementById('kpiStrip').innerHTML = `
В выборке
${fmt.int(rows.length)}
из ${fmt.int(D.meta.rowsClean)}
Культур на графиках
${fmt.int(cropList.filter((c) => rows.some((r) => r.crop === c)).length)}
без смешивания
Медиана ц/га
${fmt.num(median(prods), 1)}
Средняя ц/га
${fmt.num(mean(prods), 1)}
`; const host = document.getElementById('heatmaps'); if (!rows.length) { host.innerHTML = `
Нет строк по текущим фильтрам. Снимите часть ограничений.
`; } else if (!cropList.length) { host.innerHTML = `
Выберите хотя бы одну культуру — культуры на heatmap не смешиваются.
`; } else { host.innerHTML = cropList.map((c) => buildHeatmap(rows, c)).join('') || `
По выбранным культурам нет данных в выборке.
`; } const sample = [...rows] .sort((a, b) => b.productivity - a.productivity) .slice(0, 250); document.getElementById('sampleMeta').textContent = `Показаны топ-${sample.length} из ${fmt.int(rows.length)} по урожайности (ц/га)`; document.querySelector('#tblSample tbody').innerHTML = sample .map( (r) => ` ${r.field} ${r.division} ${r.unit} ${r.year} ${r.crop} ${r.variety} ${r.sowing} ${r.harvest} ${daysBetween(r.sowing, r.harvest)} ${fmt.num(r.productivity, 1)} ${fmt.num(r.areaHa, 1)} ` ) .join(''); } // close other details when opening one document.querySelectorAll('details.ms').forEach((d) => { d.addEventListener('toggle', () => { if (!d.open) return; document.querySelectorAll('details.ms').forEach((o) => { if (o !== d) o.open = false; }); // refresh cascaded lists when opening division-dependent if (d.id === 'msUnit' || d.id === 'msVariety' || d.id === 'msDivision' || d.id === 'msCrop') { refreshFilterOptions(); } }); }); document.getElementById('btnApply').onclick = () => { document.querySelectorAll('details.ms').forEach((d) => { d.open = false; }); refreshFilterOptions(); render(); }; document.getElementById('btnReset').onclick = () => { state.divisions.clear(); state.units.clear(); state.years.clear(); state.crops.clear(); state.crops.add('Пшеница озимая'); state.varieties.clear(); refreshFilterOptions(); render(); }; document.getElementById('footMeta').textContent = D.meta.notes.join(' · '); // default years with densest both-date data for (const y of [2025, 2026]) { if (D.filters.years.includes(y)) state.years.add(y); } refreshFilterOptions(); render(); })();