init
This commit is contained in:
@@ -0,0 +1,25 @@
|
|||||||
|
# 2026-08-12 Project Memory
|
||||||
|
|
||||||
|
> Auto-generated by AI Agent. Entries are append-only within a day.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## [09:48] fields_history CSV file export
|
||||||
|
|
||||||
|
**Type**: solution
|
||||||
|
**Tags**: `refactor`, `export`
|
||||||
|
|
||||||
|
В конце `fields_history.js` вместо `console.table` / CSV в консоль — запись в `fields_history_${SEASON_YEAR}.csv` (UTF-8 с BOM для Excel). Паттерн как в `get_weather.js` (`fs` + `path`).
|
||||||
|
|
||||||
|
**Status**: ✅ verified
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## [12:15] fields_history_pg.js Cropwise → Postgres sync
|
||||||
|
|
||||||
|
**Type**: solution
|
||||||
|
**Tags**: `architecture`, `dependency`, `performance`
|
||||||
|
|
||||||
|
Добавлен `fields_history_pg.js`: создаёт БД `ak_fields`, таблицы `crops` / `group_folders` / `field_groups` / `fields`, синкает API. Фильтр ветки `GROUP_FOLDER_ROOT_ID=27`. В `fields`: `zone_hierarchy` + `history_items` JSONB (без фильтра по годам). `.env` + `pg`/`dotenv`. Параллелизм `CONCURRENCY=20` + resume по уже залитым `history_items`.
|
||||||
|
|
||||||
|
**Status**: ✅ verified
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
# 2026-11-09 Project Memory
|
||||||
|
|
||||||
|
> Auto-generated by AI Agent. Entries are append-only within a day.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## [19:09] Dashboard урожайности ak_fields + clusters
|
||||||
|
|
||||||
|
**Type**: decision
|
||||||
|
**Tags**: `architecture`, `analytics`, `dashboard`
|
||||||
|
|
||||||
|
Интерактивный дашборд в `dashboard/`: JSON из Postgres (`build-data.js`), кластеры копируются из `fertilizer_project_test.fields_clustered_all` → `ak_fields.fields_clustered_all` (`sync-clusters.js`, join по `field_id`). UI: `index.html` + Chart.js, данные в `data/dashboard.json` и `dashboard-data.js`. npm: `dashboard:clusters`, `dashboard:data`, `dashboard:build`, `dashboard`. Разрезы: дивизионы/предприятия/ПО, матрица урожайность×стабильность, тренды культур ц/га 2018–2025, пшеница-флагман, звёзды/риск.
|
||||||
|
|
||||||
|
**Status**: ✅ verified
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
# 2026-11-10 Project Memory
|
||||||
|
|
||||||
|
> Auto-generated by AI Agent. Entries are append-only within a day.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## [12:30] Страница анализа дат сева/уборки + навигация
|
||||||
|
|
||||||
|
**Type**: solution
|
||||||
|
**Tags**: `analytics`, `dashboard`
|
||||||
|
|
||||||
|
Добавлены `dashboard/dates.html` (heatmap неделя сева × неделя уборки → медиана ц/га, мультифильтры дивизион/ПО/год/культура/гибрид, таблица выборки), данные `npm run dashboard:dates` → `data/dates-data.js`. Заглушки `predecessor.html`, `fertilizers.html` с описанием будущего дашборда. Общая `site-nav` на всех страницах.
|
||||||
|
|
||||||
|
**Status**: ✅ verified
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## [15:55] Загрузка актов удобрений + страница анализа
|
||||||
|
|
||||||
|
**Type**: solution
|
||||||
|
**Tags**: `analytics`, `dashboard`, `postgres`, `fertilizer`
|
||||||
|
|
||||||
|
CSV `data/fertilizer_field_final_utf.csv` → таблица `fertilizer_field_acts` (39 050 строк) + view `v_fertilizer_field`. Связь с `fields` по `field_name`→`fields.name` (`field_id`): 36 158 linked / 9 387 полей. Скрипт `load_fertilizer_field.js` / `npm run fertilizer:load`. Дашборд: `fertilizers.html` + `fertilizers-app.js`, данные `npm run dashboard:fert`. Агроконтекст: вынос NPK из skill `agriculture_operations.md`, баланс внесено−вынос, dose–response по N, органика.
|
||||||
|
|
||||||
|
**Status**: ✅ verified
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## [16:08] Страница аудита качества данных удобрений
|
||||||
|
|
||||||
|
**Type**: solution
|
||||||
|
**Tags**: `analytics`, `dashboard`, `data-quality`
|
||||||
|
|
||||||
|
Добавлена `fertilizer-quality.html`: флаги выбросов NPK/массы/органики, missing_dv, npk_gt_mass, multi_crop; вердикт пригодности к анализу влияния. Данные: `npm run dashboard:fert-quality`. На текущей выгрузке ~84% строк «готовы к анализу», verdict=`usable`.
|
||||||
|
|
||||||
|
**Status**: ✅ verified
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
# Project Overview
|
||||||
|
|
||||||
|
**Name**: cropwise_weather
|
||||||
|
**Tech Stack**: Node.js, axios, pg, dotenv, Cropwise Operations API (v3), PostgreSQL, Chart.js dashboard
|
||||||
|
**Last Updated**: 2026-11-10
|
||||||
|
|
||||||
|
## Architecture
|
||||||
|
Scripts fetch field/weather data from Cropwise Operations API. CSV reports locally (`get_weather.js`, `fields_history.js`) and Postgres sync (`fields_history_pg.js` → DB `ak_fields`). Fertilizer write-off acts live in `fertilizer_field_acts` (linked to `fields` by name). Analytics dashboard in `dashboard/` reads aggregates from JSON regenerated by `build-data.js` / `build-dates-data.js` / `build-fertilizers-data.js`.
|
||||||
|
|
||||||
|
## Key Decisions
|
||||||
|
- Reports written as UTF-8 CSV files (with BOM for Excel Cyrillic) instead of console dump — 2026-08-12
|
||||||
|
- Field history sync scopes to group_folder subtree root id=27; history_items stored as JSONB on fields — 2026-08-12
|
||||||
|
- Field clusters live in `ak_fields.fields_clustered_all` (synced from `fertilizer_project_test`); dashboard is static JSON + HTML, no backend — 2026-11-09
|
||||||
|
- Factor pages: dates heatmap (`dates.html`), fertilizers analysis (`fertilizers.html`), fertilizer quality audit (`fertilizer-quality.html`), stub for predecessor; shared site-nav — 2026-11-10
|
||||||
|
- Fertilizer acts: table `fertilizer_field_acts` + view `v_fertilizer_field`; join key = field name — 2026-11-10
|
||||||
|
|
||||||
|
## Known Issues
|
||||||
|
|
||||||
|
## Resolved Patterns
|
||||||
|
- CSV export: `fs.writeFileSync` + `path.join(__dirname, ...)` with season/year in filename
|
||||||
|
- PG sync of many fields: Pool + CONCURRENCY workers + resume skip where history_items already set
|
||||||
|
- Dashboard rebuild: `npm run dashboard:build` then open `dashboard/index.html` or `npm run dashboard`
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
node_modules
|
||||||
|
.env
|
||||||
@@ -0,0 +1,761 @@
|
|||||||
|
/* 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, '&')
|
||||||
|
.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 = `
|
||||||
|
<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 */ }
|
||||||
|
});
|
||||||
|
});
|
||||||
|
})();
|
||||||
@@ -0,0 +1,660 @@
|
|||||||
|
/**
|
||||||
|
* Агрегирует ak_fields (+ fields_clustered_all) → data/dashboard.json
|
||||||
|
* Запуск: node dashboard/build-data.js
|
||||||
|
*/
|
||||||
|
require('dotenv').config({ path: require('path').join(__dirname, '..', '.env') });
|
||||||
|
const fs = require('fs');
|
||||||
|
const path = require('path');
|
||||||
|
const { Client } = require('pg');
|
||||||
|
|
||||||
|
const YEAR_FROM = Number(process.env.DASH_YEAR_FROM || 2018);
|
||||||
|
const YEAR_TO = Number(process.env.DASH_YEAR_TO || 2025);
|
||||||
|
const OUT = path.join(__dirname, 'data', 'dashboard.json');
|
||||||
|
|
||||||
|
/** Основные товарные культуры для сравнения урожайности (ц/га) */
|
||||||
|
const FOCUS_CROPS = [
|
||||||
|
'Пшеница озимая',
|
||||||
|
'Подсолнечник масличный',
|
||||||
|
'Кукуруза на зерно',
|
||||||
|
'Соя',
|
||||||
|
'Свекла сахарная',
|
||||||
|
'Ячмень озимый',
|
||||||
|
'Горох',
|
||||||
|
'Рис',
|
||||||
|
'Рапс озимый',
|
||||||
|
'Пшеница яровая мягкая',
|
||||||
|
'Лен масличный',
|
||||||
|
];
|
||||||
|
|
||||||
|
/** Верхние границы ц/га для отсечения явных выбросов */
|
||||||
|
const PROD_MAX = {
|
||||||
|
'Пшеница озимая': 120,
|
||||||
|
'Пшеница яровая мягкая': 100,
|
||||||
|
'Ячмень озимый': 120,
|
||||||
|
'Подсолнечник масличный': 50,
|
||||||
|
'Кукуруза на зерно': 150,
|
||||||
|
Соя: 50,
|
||||||
|
'Свекла сахарная': 800,
|
||||||
|
Горох: 60,
|
||||||
|
Рис: 120,
|
||||||
|
'Рапс озимый': 50,
|
||||||
|
'Лен масличный': 30,
|
||||||
|
};
|
||||||
|
|
||||||
|
function pg() {
|
||||||
|
return new Client({
|
||||||
|
host: process.env.PGHOST,
|
||||||
|
port: Number(process.env.PGPORT || 5432),
|
||||||
|
database: process.env.PGDATABASE || 'ak_fields',
|
||||||
|
user: process.env.PGUSER,
|
||||||
|
password: process.env.PGPASSWORD,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function round(n, d = 1) {
|
||||||
|
if (n == null || Number.isNaN(Number(n))) return null;
|
||||||
|
const f = 10 ** d;
|
||||||
|
return Math.round(Number(n) * f) / f;
|
||||||
|
}
|
||||||
|
|
||||||
|
function num(v) {
|
||||||
|
if (v == null) return null;
|
||||||
|
const n = Number(v);
|
||||||
|
return Number.isFinite(n) ? n : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function main() {
|
||||||
|
const c = pg();
|
||||||
|
await c.connect();
|
||||||
|
console.log(`Building dashboard data (${YEAR_FROM}–${YEAR_TO})...`);
|
||||||
|
|
||||||
|
// Ensure clusters table exists
|
||||||
|
const hasClusters = await c.query(`
|
||||||
|
SELECT EXISTS (
|
||||||
|
SELECT 1 FROM information_schema.tables
|
||||||
|
WHERE table_schema='public' AND table_name='fields_clustered_all'
|
||||||
|
) AS ok`);
|
||||||
|
if (!hasClusters.rows[0].ok) {
|
||||||
|
console.warn('fields_clustered_all missing — run: node dashboard/sync-clusters.js');
|
||||||
|
}
|
||||||
|
|
||||||
|
const meta = {
|
||||||
|
generatedAt: new Date().toISOString(),
|
||||||
|
company: 'АО фирма «Агрокомплекс» им. Н.И. Ткачева',
|
||||||
|
yearFrom: YEAR_FROM,
|
||||||
|
yearTo: YEAR_TO,
|
||||||
|
productivityUnit: 'ц/га',
|
||||||
|
areaUnit: 'га',
|
||||||
|
notes: [
|
||||||
|
'Урожайность — productivity из history_items Cropwise (ц/га).',
|
||||||
|
'Индекс урожайности и стабильность — из fields_clustered_all (нормализованный индекс относительно дивизиона/культуры).',
|
||||||
|
'Иерархия: Компания → Дивизион → Предприятие → Подразделение (zone_hierarchy).',
|
||||||
|
'Выбросы урожайности отфильтрованы по культуре для трендов и рейтингов.',
|
||||||
|
],
|
||||||
|
};
|
||||||
|
|
||||||
|
const overview = await c.query(`
|
||||||
|
SELECT
|
||||||
|
COUNT(*)::int AS fields_total,
|
||||||
|
ROUND(SUM(COALESCE(calculated_area,0))::numeric, 0)::float AS area_total_ha,
|
||||||
|
ROUND(AVG(NULLIF(calculated_area,0))::numeric, 1)::float AS area_avg_ha,
|
||||||
|
COUNT(*) FILTER (WHERE c.field_id IS NOT NULL)::int AS fields_clustered,
|
||||||
|
ROUND(AVG(c.yield_index_median)::numeric, 3)::float AS avg_yield_index,
|
||||||
|
ROUND(AVG(c.stability_std)::numeric, 3)::float AS avg_stability_std,
|
||||||
|
COUNT(*) FILTER (WHERE c.yield_category_rules = 'Высокоурожайное')::int AS high_yield_n,
|
||||||
|
COUNT(*) FILTER (WHERE c.yield_category_rules = 'Малоурожайное')::int AS low_yield_n,
|
||||||
|
COUNT(*) FILTER (WHERE c.stability_category = 'Стабильное')::int AS stable_n,
|
||||||
|
COUNT(*) FILTER (WHERE c.stability_category = 'Нестабильное')::int AS unstable_n,
|
||||||
|
COUNT(*) FILTER (
|
||||||
|
WHERE c.yield_category_rules = 'Высокоурожайное'
|
||||||
|
AND c.stability_category = 'Стабильное'
|
||||||
|
)::int AS stars_n,
|
||||||
|
COUNT(*) FILTER (
|
||||||
|
WHERE c.yield_category_rules = 'Малоурожайное'
|
||||||
|
AND c.stability_category = 'Нестабильное'
|
||||||
|
)::int AS risk_n
|
||||||
|
FROM fields f
|
||||||
|
LEFT JOIN fields_clustered_all c ON c.field_id = f.id
|
||||||
|
`);
|
||||||
|
|
||||||
|
const divisions = await c.query(`
|
||||||
|
WITH base AS (
|
||||||
|
SELECT
|
||||||
|
f.id,
|
||||||
|
f.calculated_area,
|
||||||
|
NULLIF(trim(both FROM split_part(f.zone_hierarchy, ' -> ', 2)), '') AS division,
|
||||||
|
c.yield_index_median,
|
||||||
|
c.stability_std,
|
||||||
|
c.yield_category_rules,
|
||||||
|
c.stability_category,
|
||||||
|
c.years_in_rotation
|
||||||
|
FROM fields f
|
||||||
|
LEFT JOIN fields_clustered_all c ON c.field_id = f.id
|
||||||
|
)
|
||||||
|
SELECT
|
||||||
|
COALESCE(division, 'Без дивизиона') AS division,
|
||||||
|
COUNT(*)::int AS fields,
|
||||||
|
ROUND(SUM(COALESCE(calculated_area,0))::numeric, 0)::float AS area_ha,
|
||||||
|
ROUND(AVG(yield_index_median)::numeric, 3)::float AS avg_yield_index,
|
||||||
|
ROUND(AVG(stability_std)::numeric, 3)::float AS avg_stability_std,
|
||||||
|
ROUND(AVG(years_in_rotation)::numeric, 1)::float AS avg_years_rotation,
|
||||||
|
COUNT(*) FILTER (WHERE yield_category_rules = 'Высокоурожайное')::int AS high_yield,
|
||||||
|
COUNT(*) FILTER (WHERE yield_category_rules = 'Среднее')::int AS mid_yield,
|
||||||
|
COUNT(*) FILTER (WHERE yield_category_rules = 'Малоурожайное')::int AS low_yield,
|
||||||
|
COUNT(*) FILTER (WHERE stability_category = 'Стабильное')::int AS stable,
|
||||||
|
COUNT(*) FILTER (WHERE stability_category = 'Нестабильное')::int AS unstable,
|
||||||
|
COUNT(*) FILTER (WHERE stability_category = 'Нет данных')::int AS stab_na,
|
||||||
|
COUNT(*) FILTER (
|
||||||
|
WHERE yield_category_rules = 'Высокоурожайное' AND stability_category = 'Стабильное'
|
||||||
|
)::int AS stars,
|
||||||
|
COUNT(*) FILTER (
|
||||||
|
WHERE yield_category_rules = 'Малоурожайное' AND stability_category = 'Нестабильное'
|
||||||
|
)::int AS risk
|
||||||
|
FROM base
|
||||||
|
GROUP BY 1
|
||||||
|
ORDER BY area_ha DESC NULLS LAST
|
||||||
|
`);
|
||||||
|
|
||||||
|
const enterprises = await c.query(`
|
||||||
|
WITH base AS (
|
||||||
|
SELECT
|
||||||
|
f.id,
|
||||||
|
f.calculated_area,
|
||||||
|
NULLIF(trim(both FROM split_part(f.zone_hierarchy, ' -> ', 2)), '') AS division,
|
||||||
|
NULLIF(trim(both FROM split_part(f.zone_hierarchy, ' -> ', 3)), '') AS enterprise,
|
||||||
|
c.yield_index_median,
|
||||||
|
c.yield_category_rules,
|
||||||
|
c.stability_category
|
||||||
|
FROM fields f
|
||||||
|
LEFT JOIN fields_clustered_all c ON c.field_id = f.id
|
||||||
|
)
|
||||||
|
SELECT
|
||||||
|
COALESCE(division, 'Без дивизиона') AS division,
|
||||||
|
COALESCE(enterprise, 'Без предприятия') AS enterprise,
|
||||||
|
COUNT(*)::int AS fields,
|
||||||
|
ROUND(SUM(COALESCE(calculated_area,0))::numeric, 0)::float AS area_ha,
|
||||||
|
ROUND(AVG(yield_index_median)::numeric, 3)::float AS avg_yield_index,
|
||||||
|
COUNT(*) FILTER (
|
||||||
|
WHERE yield_category_rules = 'Высокоурожайное' AND stability_category = 'Стабильное'
|
||||||
|
)::int AS stars,
|
||||||
|
COUNT(*) FILTER (
|
||||||
|
WHERE yield_category_rules = 'Малоурожайное' AND stability_category = 'Нестабильное'
|
||||||
|
)::int AS risk
|
||||||
|
FROM base
|
||||||
|
WHERE enterprise IS NOT NULL AND enterprise <> ''
|
||||||
|
GROUP BY 1, 2
|
||||||
|
HAVING COUNT(*) >= 10
|
||||||
|
ORDER BY avg_yield_index DESC NULLS LAST
|
||||||
|
`);
|
||||||
|
|
||||||
|
const clusterMatrix = await c.query(`
|
||||||
|
SELECT
|
||||||
|
yield_category_rules AS yield_cat,
|
||||||
|
stability_category AS stab_cat,
|
||||||
|
COUNT(*)::int AS fields,
|
||||||
|
ROUND(SUM(COALESCE(area_ha,0))::numeric, 0)::float AS area_ha,
|
||||||
|
ROUND(AVG(yield_index_median)::numeric, 3)::float AS avg_yield_index,
|
||||||
|
ROUND(AVG(stability_std)::numeric, 3)::float AS avg_stability_std,
|
||||||
|
ROUND(AVG(years_in_rotation)::numeric, 1)::float AS avg_years
|
||||||
|
FROM fields_clustered_all
|
||||||
|
GROUP BY 1, 2
|
||||||
|
ORDER BY 1, 2
|
||||||
|
`);
|
||||||
|
|
||||||
|
const clusterByDivision = await c.query(`
|
||||||
|
SELECT
|
||||||
|
division,
|
||||||
|
yield_category_rules AS yield_cat,
|
||||||
|
stability_category AS stab_cat,
|
||||||
|
COUNT(*)::int AS fields,
|
||||||
|
ROUND(SUM(COALESCE(area_ha,0))::numeric, 0)::float AS area_ha
|
||||||
|
FROM fields_clustered_all
|
||||||
|
GROUP BY 1, 2, 3
|
||||||
|
ORDER BY 1, 2, 3
|
||||||
|
`);
|
||||||
|
|
||||||
|
const yieldIndexHist = await c.query(`
|
||||||
|
SELECT
|
||||||
|
width_bucket(yield_index_median, 0.4, 1.6, 12) AS bucket,
|
||||||
|
COUNT(*)::int AS fields,
|
||||||
|
ROUND(MIN(yield_index_median)::numeric, 3)::float AS idx_min,
|
||||||
|
ROUND(MAX(yield_index_median)::numeric, 3)::float AS idx_max,
|
||||||
|
ROUND(AVG(yield_index_median)::numeric, 3)::float AS idx_avg
|
||||||
|
FROM fields_clustered_all
|
||||||
|
WHERE yield_index_median BETWEEN 0.4 AND 1.6
|
||||||
|
GROUP BY 1
|
||||||
|
ORDER BY 1
|
||||||
|
`);
|
||||||
|
|
||||||
|
const yearsRotation = await c.query(`
|
||||||
|
SELECT
|
||||||
|
years_in_rotation AS years,
|
||||||
|
COUNT(*)::int AS fields,
|
||||||
|
ROUND(AVG(yield_index_median)::numeric, 3)::float AS avg_yield_index,
|
||||||
|
ROUND(AVG(stability_std)::numeric, 3)::float AS avg_stability_std,
|
||||||
|
COUNT(*) FILTER (WHERE yield_category_rules = 'Высокоурожайное')::int AS high_yield,
|
||||||
|
COUNT(*) FILTER (WHERE yield_category_rules = 'Малоурожайное')::int AS low_yield
|
||||||
|
FROM fields_clustered_all
|
||||||
|
WHERE years_in_rotation IS NOT NULL
|
||||||
|
GROUP BY 1
|
||||||
|
ORDER BY 1
|
||||||
|
`);
|
||||||
|
|
||||||
|
const areaBuckets = await c.query(`
|
||||||
|
SELECT bucket, COUNT(*)::int AS fields, ROUND(SUM(area)::numeric,0)::float AS area_ha
|
||||||
|
FROM (
|
||||||
|
SELECT
|
||||||
|
calculated_area AS area,
|
||||||
|
CASE
|
||||||
|
WHEN calculated_area IS NULL OR calculated_area <= 0 THEN 'нет данных'
|
||||||
|
WHEN calculated_area < 20 THEN '<20'
|
||||||
|
WHEN calculated_area < 50 THEN '20–50'
|
||||||
|
WHEN calculated_area < 100 THEN '50–100'
|
||||||
|
WHEN calculated_area < 150 THEN '100–150'
|
||||||
|
WHEN calculated_area < 250 THEN '150–250'
|
||||||
|
ELSE '≥250'
|
||||||
|
END AS bucket
|
||||||
|
FROM fields
|
||||||
|
) t
|
||||||
|
GROUP BY bucket
|
||||||
|
ORDER BY
|
||||||
|
CASE bucket
|
||||||
|
WHEN '<20' THEN 1 WHEN '20–50' THEN 2 WHEN '50–100' THEN 3
|
||||||
|
WHEN '100–150' THEN 4 WHEN '150–250' THEN 5 WHEN '≥250' THEN 6
|
||||||
|
ELSE 7
|
||||||
|
END
|
||||||
|
`);
|
||||||
|
|
||||||
|
// Year × crop productivity (filtered)
|
||||||
|
const cropCase = FOCUS_CROPS.map(
|
||||||
|
(name) => `WHEN '${name.replace(/'/g, "''")}' THEN ${PROD_MAX[name] || 200}`
|
||||||
|
).join('\n');
|
||||||
|
|
||||||
|
const byYearCrop = await c.query(`
|
||||||
|
WITH hist AS (
|
||||||
|
SELECT
|
||||||
|
f.id AS field_id,
|
||||||
|
NULLIF(trim(both FROM split_part(f.zone_hierarchy, ' -> ', 2)), '') AS division,
|
||||||
|
f.calculated_area,
|
||||||
|
(item->>'year')::int AS year,
|
||||||
|
cr.name AS crop,
|
||||||
|
NULLIF(item->>'productivity','')::float AS productivity
|
||||||
|
FROM fields f
|
||||||
|
CROSS JOIN LATERAL jsonb_array_elements(f.history_items) item
|
||||||
|
LEFT JOIN crops cr ON cr.id = NULLIF(item->>'crop_id','')::bigint
|
||||||
|
WHERE f.history_items IS NOT NULL
|
||||||
|
AND jsonb_typeof(f.history_items) = 'array'
|
||||||
|
AND (item->>'year')::int BETWEEN $1 AND $2
|
||||||
|
AND cr.name = ANY($3::text[])
|
||||||
|
AND NULLIF(item->>'productivity','') IS NOT NULL
|
||||||
|
),
|
||||||
|
clean AS (
|
||||||
|
SELECT *
|
||||||
|
FROM hist
|
||||||
|
WHERE productivity > 0
|
||||||
|
AND productivity <= CASE crop ${cropCase} ELSE 200 END
|
||||||
|
)
|
||||||
|
SELECT
|
||||||
|
year,
|
||||||
|
crop,
|
||||||
|
COUNT(*)::int AS fields,
|
||||||
|
ROUND(AVG(productivity)::numeric, 1)::float AS avg_prod,
|
||||||
|
ROUND(PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY productivity)::numeric, 1)::float AS median_prod,
|
||||||
|
ROUND(SUM(COALESCE(calculated_area,0))::numeric, 0)::float AS area_ha
|
||||||
|
FROM clean
|
||||||
|
GROUP BY 1, 2
|
||||||
|
ORDER BY 1, 2
|
||||||
|
`, [YEAR_FROM, YEAR_TO, FOCUS_CROPS]);
|
||||||
|
|
||||||
|
const byDivisionCrop = await c.query(`
|
||||||
|
WITH hist AS (
|
||||||
|
SELECT
|
||||||
|
NULLIF(trim(both FROM split_part(f.zone_hierarchy, ' -> ', 2)), '') AS division,
|
||||||
|
f.calculated_area,
|
||||||
|
(item->>'year')::int AS year,
|
||||||
|
cr.name AS crop,
|
||||||
|
NULLIF(item->>'productivity','')::float AS productivity
|
||||||
|
FROM fields f
|
||||||
|
CROSS JOIN LATERAL jsonb_array_elements(f.history_items) item
|
||||||
|
LEFT JOIN crops cr ON cr.id = NULLIF(item->>'crop_id','')::bigint
|
||||||
|
WHERE f.history_items IS NOT NULL
|
||||||
|
AND (item->>'year')::int BETWEEN $1 AND $2
|
||||||
|
AND cr.name = ANY($3::text[])
|
||||||
|
AND NULLIF(item->>'productivity','') IS NOT NULL
|
||||||
|
),
|
||||||
|
clean AS (
|
||||||
|
SELECT *
|
||||||
|
FROM hist
|
||||||
|
WHERE productivity > 0
|
||||||
|
AND productivity <= CASE crop ${cropCase} ELSE 200 END
|
||||||
|
AND division IS NOT NULL
|
||||||
|
)
|
||||||
|
SELECT
|
||||||
|
division,
|
||||||
|
crop,
|
||||||
|
COUNT(*)::int AS fields,
|
||||||
|
ROUND(AVG(productivity)::numeric, 1)::float AS avg_prod,
|
||||||
|
ROUND(PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY productivity)::numeric, 1)::float AS median_prod,
|
||||||
|
ROUND(SUM(COALESCE(calculated_area,0))::numeric, 0)::float AS area_ha
|
||||||
|
FROM clean
|
||||||
|
GROUP BY 1, 2
|
||||||
|
ORDER BY division, area_ha DESC
|
||||||
|
`, [YEAR_FROM, YEAR_TO, FOCUS_CROPS]);
|
||||||
|
|
||||||
|
// Crop structure latest complete year in range
|
||||||
|
const cropStructure = await c.query(`
|
||||||
|
WITH hist AS (
|
||||||
|
SELECT
|
||||||
|
(item->>'year')::int AS year,
|
||||||
|
cr.name AS crop,
|
||||||
|
COALESCE(cr.standard_name, cr.name) AS crop_key,
|
||||||
|
f.calculated_area,
|
||||||
|
NULLIF(item->>'productivity','')::float AS productivity
|
||||||
|
FROM fields f
|
||||||
|
CROSS JOIN LATERAL jsonb_array_elements(f.history_items) item
|
||||||
|
LEFT JOIN crops cr ON cr.id = NULLIF(item->>'crop_id','')::bigint
|
||||||
|
WHERE f.history_items IS NOT NULL
|
||||||
|
AND (item->>'year')::int BETWEEN $1 AND $2
|
||||||
|
AND item->>'crop_id' IS NOT NULL
|
||||||
|
AND cr.name IS NOT NULL
|
||||||
|
)
|
||||||
|
SELECT
|
||||||
|
year,
|
||||||
|
crop,
|
||||||
|
COUNT(*)::int AS fields,
|
||||||
|
ROUND(SUM(COALESCE(calculated_area,0))::numeric, 0)::float AS area_ha,
|
||||||
|
ROUND(AVG(productivity) FILTER (WHERE productivity > 0)::numeric, 1)::float AS avg_prod
|
||||||
|
FROM hist
|
||||||
|
GROUP BY 1, 2
|
||||||
|
ORDER BY year, area_ha DESC
|
||||||
|
`, [YEAR_FROM, YEAR_TO]);
|
||||||
|
|
||||||
|
// YoY for winter wheat by division (flagship crop)
|
||||||
|
const wheatYoy = await c.query(`
|
||||||
|
WITH hist AS (
|
||||||
|
SELECT
|
||||||
|
NULLIF(trim(both FROM split_part(f.zone_hierarchy, ' -> ', 2)), '') AS division,
|
||||||
|
(item->>'year')::int AS year,
|
||||||
|
NULLIF(item->>'productivity','')::float AS productivity,
|
||||||
|
f.calculated_area
|
||||||
|
FROM fields f
|
||||||
|
CROSS JOIN LATERAL jsonb_array_elements(f.history_items) item
|
||||||
|
LEFT JOIN crops cr ON cr.id = NULLIF(item->>'crop_id','')::bigint
|
||||||
|
WHERE f.history_items IS NOT NULL
|
||||||
|
AND cr.name = 'Пшеница озимая'
|
||||||
|
AND (item->>'year')::int BETWEEN $1 AND $2
|
||||||
|
AND NULLIF(item->>'productivity','')::float BETWEEN 5 AND 120
|
||||||
|
)
|
||||||
|
SELECT
|
||||||
|
division,
|
||||||
|
year,
|
||||||
|
COUNT(*)::int AS fields,
|
||||||
|
ROUND(AVG(productivity)::numeric, 1)::float AS avg_prod,
|
||||||
|
ROUND(PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY productivity)::numeric, 1)::float AS median_prod,
|
||||||
|
ROUND(SUM(COALESCE(calculated_area,0))::numeric, 0)::float AS area_ha
|
||||||
|
FROM hist
|
||||||
|
WHERE division IS NOT NULL
|
||||||
|
GROUP BY 1, 2
|
||||||
|
ORDER BY 1, 2
|
||||||
|
`, [YEAR_FROM, YEAR_TO]);
|
||||||
|
|
||||||
|
// Top / bottom enterprises by wheat median last 3 years
|
||||||
|
const wheatEnterprises = await c.query(`
|
||||||
|
WITH hist AS (
|
||||||
|
SELECT
|
||||||
|
NULLIF(trim(both FROM split_part(f.zone_hierarchy, ' -> ', 2)), '') AS division,
|
||||||
|
NULLIF(trim(both FROM split_part(f.zone_hierarchy, ' -> ', 3)), '') AS enterprise,
|
||||||
|
NULLIF(item->>'productivity','')::float AS productivity,
|
||||||
|
f.calculated_area
|
||||||
|
FROM fields f
|
||||||
|
CROSS JOIN LATERAL jsonb_array_elements(f.history_items) item
|
||||||
|
LEFT JOIN crops cr ON cr.id = NULLIF(item->>'crop_id','')::bigint
|
||||||
|
WHERE f.history_items IS NOT NULL
|
||||||
|
AND cr.name = 'Пшеница озимая'
|
||||||
|
AND (item->>'year')::int BETWEEN $1::int AND $2::int
|
||||||
|
AND NULLIF(item->>'productivity','')::float BETWEEN 5 AND 120
|
||||||
|
)
|
||||||
|
SELECT
|
||||||
|
division,
|
||||||
|
enterprise,
|
||||||
|
COUNT(*)::int AS fields,
|
||||||
|
ROUND(AVG(productivity)::numeric, 1)::float AS avg_prod,
|
||||||
|
ROUND(PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY productivity)::numeric, 1)::float AS median_prod,
|
||||||
|
ROUND(SUM(COALESCE(calculated_area,0))::numeric, 0)::float AS area_ha
|
||||||
|
FROM hist
|
||||||
|
WHERE enterprise IS NOT NULL AND enterprise <> ''
|
||||||
|
GROUP BY 1, 2
|
||||||
|
HAVING COUNT(*) >= 30
|
||||||
|
ORDER BY median_prod DESC
|
||||||
|
`, [YEAR_TO - 2, YEAR_TO]);
|
||||||
|
|
||||||
|
// Stars and risk fields samples
|
||||||
|
const stars = await c.query(`
|
||||||
|
SELECT
|
||||||
|
f.name AS field_name,
|
||||||
|
NULLIF(trim(both FROM split_part(f.zone_hierarchy, ' -> ', 2)), '') AS division,
|
||||||
|
NULLIF(trim(both FROM split_part(f.zone_hierarchy, ' -> ', 3)), '') AS enterprise,
|
||||||
|
ROUND(COALESCE(f.calculated_area, 0)::numeric, 1)::float AS area_ha,
|
||||||
|
ROUND(COALESCE(c.yield_index_median, 0)::numeric, 3)::float AS yield_index,
|
||||||
|
ROUND(COALESCE(c.stability_std, 0)::numeric, 3)::float AS stability_std,
|
||||||
|
c.years_in_rotation
|
||||||
|
FROM fields_clustered_all c
|
||||||
|
JOIN fields f ON f.id = c.field_id
|
||||||
|
WHERE c.yield_category_rules = 'Высокоурожайное'
|
||||||
|
AND c.stability_category = 'Стабильное'
|
||||||
|
ORDER BY c.yield_index_median DESC NULLS LAST
|
||||||
|
LIMIT 25
|
||||||
|
`);
|
||||||
|
|
||||||
|
const risks = await c.query(`
|
||||||
|
SELECT
|
||||||
|
f.name AS field_name,
|
||||||
|
NULLIF(trim(both FROM split_part(f.zone_hierarchy, ' -> ', 2)), '') AS division,
|
||||||
|
NULLIF(trim(both FROM split_part(f.zone_hierarchy, ' -> ', 3)), '') AS enterprise,
|
||||||
|
ROUND(COALESCE(f.calculated_area, 0)::numeric, 1)::float AS area_ha,
|
||||||
|
ROUND(COALESCE(c.yield_index_median, 0)::numeric, 3)::float AS yield_index,
|
||||||
|
ROUND(COALESCE(c.stability_std, 0)::numeric, 3)::float AS stability_std,
|
||||||
|
c.years_in_rotation
|
||||||
|
FROM fields_clustered_all c
|
||||||
|
JOIN fields f ON f.id = c.field_id
|
||||||
|
WHERE c.yield_category_rules = 'Малоурожайное'
|
||||||
|
AND c.stability_category = 'Нестабильное'
|
||||||
|
ORDER BY c.yield_index_median ASC NULLS LAST, c.stability_std DESC NULLS LAST
|
||||||
|
LIMIT 25
|
||||||
|
`);
|
||||||
|
|
||||||
|
// Scatter sample for yield index vs stability (sampled)
|
||||||
|
const scatter = await c.query(`
|
||||||
|
SELECT
|
||||||
|
ROUND(yield_index_median::numeric, 3)::float AS x,
|
||||||
|
ROUND(stability_std::numeric, 3)::float AS y,
|
||||||
|
yield_category_rules AS yield_cat,
|
||||||
|
stability_category AS stab_cat,
|
||||||
|
division,
|
||||||
|
ROUND(COALESCE(area_ha, 0)::numeric, 0)::float AS area_ha
|
||||||
|
FROM fields_clustered_all
|
||||||
|
WHERE yield_index_median IS NOT NULL AND stability_std IS NOT NULL
|
||||||
|
ORDER BY random()
|
||||||
|
LIMIT 2500
|
||||||
|
`);
|
||||||
|
|
||||||
|
// Coverage by year
|
||||||
|
const coverage = await c.query(`
|
||||||
|
SELECT
|
||||||
|
(item->>'year')::int AS year,
|
||||||
|
COUNT(*) FILTER (WHERE item->>'crop_id' IS NOT NULL)::int AS with_crop,
|
||||||
|
COUNT(*) FILTER (WHERE NULLIF(item->>'productivity','') IS NOT NULL)::int AS with_prod,
|
||||||
|
ROUND(AVG(NULLIF(item->>'productivity','')::float)
|
||||||
|
FILTER (WHERE NULLIF(item->>'productivity','')::float BETWEEN 0.1 AND 800)::numeric, 1)::float AS avg_prod_raw
|
||||||
|
FROM fields f
|
||||||
|
CROSS JOIN LATERAL jsonb_array_elements(f.history_items) item
|
||||||
|
WHERE f.history_items IS NOT NULL
|
||||||
|
AND (item->>'year')::int BETWEEN $1 AND ($2 + 1)
|
||||||
|
GROUP BY 1
|
||||||
|
ORDER BY 1
|
||||||
|
`, [YEAR_FROM, YEAR_TO]);
|
||||||
|
|
||||||
|
// Portfolio mix: share of area in each yield×stability cell
|
||||||
|
const portfolio = await c.query(`
|
||||||
|
SELECT
|
||||||
|
yield_category_rules AS yield_cat,
|
||||||
|
stability_category AS stab_cat,
|
||||||
|
COUNT(*)::int AS fields,
|
||||||
|
ROUND(SUM(COALESCE(area_ha,0))::numeric, 0)::float AS area_ha,
|
||||||
|
ROUND((
|
||||||
|
100.0 * SUM(COALESCE(area_ha,0)) / NULLIF(SUM(SUM(COALESCE(area_ha,0))) OVER (), 0)
|
||||||
|
)::numeric, 1)::float AS area_share_pct
|
||||||
|
FROM fields_clustered_all
|
||||||
|
GROUP BY 1, 2
|
||||||
|
ORDER BY area_ha DESC
|
||||||
|
`);
|
||||||
|
|
||||||
|
// Units (ПО) top by risk share within each division
|
||||||
|
const unitsRisk = await c.query(`
|
||||||
|
WITH base AS (
|
||||||
|
SELECT
|
||||||
|
NULLIF(trim(both FROM split_part(f.zone_hierarchy, ' -> ', 2)), '') AS division,
|
||||||
|
NULLIF(trim(both FROM split_part(f.zone_hierarchy, ' -> ', 4)), '') AS unit,
|
||||||
|
c.yield_category_rules,
|
||||||
|
c.stability_category,
|
||||||
|
COALESCE(c.area_ha, f.calculated_area, 0)::float AS area_ha
|
||||||
|
FROM fields f
|
||||||
|
JOIN fields_clustered_all c ON c.field_id = f.id
|
||||||
|
),
|
||||||
|
agg AS (
|
||||||
|
SELECT
|
||||||
|
division,
|
||||||
|
COALESCE(NULLIF(unit,''), '—') AS unit,
|
||||||
|
COUNT(*)::int AS fields,
|
||||||
|
ROUND(SUM(area_ha)::numeric, 0)::float AS area_ha,
|
||||||
|
COUNT(*) FILTER (
|
||||||
|
WHERE yield_category_rules = 'Малоурожайное' AND stability_category = 'Нестабильное'
|
||||||
|
)::int AS risk_fields,
|
||||||
|
ROUND((
|
||||||
|
100.0 * COUNT(*) FILTER (
|
||||||
|
WHERE yield_category_rules = 'Малоурожайное' AND stability_category = 'Нестабильное'
|
||||||
|
) / NULLIF(COUNT(*), 0)
|
||||||
|
)::numeric, 1)::float AS risk_share_pct
|
||||||
|
FROM base
|
||||||
|
WHERE division IS NOT NULL
|
||||||
|
GROUP BY 1, 2
|
||||||
|
HAVING COUNT(*) >= 20
|
||||||
|
)
|
||||||
|
SELECT * FROM agg
|
||||||
|
ORDER BY risk_share_pct DESC NULLS LAST
|
||||||
|
LIMIT 40
|
||||||
|
`);
|
||||||
|
|
||||||
|
// Insights (computed in JS)
|
||||||
|
const ov = overview.rows[0];
|
||||||
|
const divRows = divisions.rows;
|
||||||
|
const bestDiv = [...divRows]
|
||||||
|
.filter((d) => d.avg_yield_index != null)
|
||||||
|
.sort((a, b) => b.avg_yield_index - a.avg_yield_index)[0];
|
||||||
|
const worstDiv = [...divRows]
|
||||||
|
.filter((d) => d.avg_yield_index != null)
|
||||||
|
.sort((a, b) => a.avg_yield_index - b.avg_yield_index)[0];
|
||||||
|
|
||||||
|
const wheatLatest = byYearCrop.rows.filter(
|
||||||
|
(r) => r.crop === 'Пшеница озимая' && r.year === YEAR_TO
|
||||||
|
)[0];
|
||||||
|
const wheatPrev = byYearCrop.rows.filter(
|
||||||
|
(r) => r.crop === 'Пшеница озимая' && r.year === YEAR_TO - 1
|
||||||
|
)[0];
|
||||||
|
let wheatDelta = null;
|
||||||
|
if (wheatLatest && wheatPrev && wheatPrev.avg_prod) {
|
||||||
|
wheatDelta = round(
|
||||||
|
((wheatLatest.avg_prod - wheatPrev.avg_prod) / wheatPrev.avg_prod) * 100,
|
||||||
|
1
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const insights = [
|
||||||
|
{
|
||||||
|
title: 'Портфель полей',
|
||||||
|
text: `Классифицировано ${ov.fields_clustered.toLocaleString('ru-RU')} полей из ${ov.fields_total.toLocaleString('ru-RU')}. «Звёзды» (высокая урожайность + стабильность): ${ov.stars_n.toLocaleString('ru-RU')}; зона риска (низкая + нестабильная): ${ov.risk_n.toLocaleString('ru-RU')}.`,
|
||||||
|
},
|
||||||
|
bestDiv && {
|
||||||
|
title: 'Лучший дивизион по индексу',
|
||||||
|
text: `${bestDiv.division}: индекс ${bestDiv.avg_yield_index}, площадь ${Number(bestDiv.area_ha).toLocaleString('ru-RU')} га, звёзд ${bestDiv.stars}.`,
|
||||||
|
},
|
||||||
|
worstDiv && {
|
||||||
|
title: 'Дивизион с запасом роста',
|
||||||
|
text: `${worstDiv.division}: индекс ${worstDiv.avg_yield_index}, риск-полей ${worstDiv.risk}. Фокус на агротехнологии и выравнивание нестабильных участков.`,
|
||||||
|
},
|
||||||
|
wheatLatest && {
|
||||||
|
title: `Озимая пшеница ${YEAR_TO}`,
|
||||||
|
text: `Средняя ${wheatLatest.avg_prod} ц/га (медиана ${wheatLatest.median_prod}) на ${Number(wheatLatest.area_ha).toLocaleString('ru-RU')} га${
|
||||||
|
wheatDelta != null
|
||||||
|
? `; к ${YEAR_TO - 1}: ${wheatDelta > 0 ? '+' : ''}${wheatDelta}%`
|
||||||
|
: ''
|
||||||
|
}.`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: 'Бизнес-логика разрезов',
|
||||||
|
text: 'Индекс урожайности сравнивает поле с нормой дивизиона; стабильность показывает повторяемость. Сочетание «высоко + стабильно» — кандидат в эталон севооборота и питания; «мало + нестабильно» — приоритет диагностики (почва, предшественник, сроки).',
|
||||||
|
},
|
||||||
|
].filter(Boolean);
|
||||||
|
|
||||||
|
const payload = {
|
||||||
|
meta,
|
||||||
|
overview: {
|
||||||
|
fieldsTotal: ov.fields_total,
|
||||||
|
areaTotalHa: num(ov.area_total_ha),
|
||||||
|
areaAvgHa: num(ov.area_avg_ha),
|
||||||
|
fieldsClustered: ov.fields_clustered,
|
||||||
|
avgYieldIndex: num(ov.avg_yield_index),
|
||||||
|
avgStabilityStd: num(ov.avg_stability_std),
|
||||||
|
highYieldN: ov.high_yield_n,
|
||||||
|
lowYieldN: ov.low_yield_n,
|
||||||
|
stableN: ov.stable_n,
|
||||||
|
unstableN: ov.unstable_n,
|
||||||
|
starsN: ov.stars_n,
|
||||||
|
riskN: ov.risk_n,
|
||||||
|
clusteredSharePct: round((ov.fields_clustered / ov.fields_total) * 100, 1),
|
||||||
|
starsSharePct: round((ov.stars_n / Math.max(ov.fields_clustered, 1)) * 100, 1),
|
||||||
|
riskSharePct: round((ov.risk_n / Math.max(ov.fields_clustered, 1)) * 100, 1),
|
||||||
|
},
|
||||||
|
insights,
|
||||||
|
filters: {
|
||||||
|
divisions: divRows.map((d) => d.division),
|
||||||
|
crops: FOCUS_CROPS,
|
||||||
|
years: Array.from({ length: YEAR_TO - YEAR_FROM + 1 }, (_, i) => YEAR_FROM + i),
|
||||||
|
},
|
||||||
|
divisions: divRows,
|
||||||
|
enterprises: enterprises.rows,
|
||||||
|
clusterMatrix: clusterMatrix.rows,
|
||||||
|
clusterByDivision: clusterByDivision.rows,
|
||||||
|
portfolio: portfolio.rows,
|
||||||
|
yieldIndexHist: yieldIndexHist.rows,
|
||||||
|
yearsRotation: yearsRotation.rows,
|
||||||
|
areaBuckets: areaBuckets.rows,
|
||||||
|
byYearCrop: byYearCrop.rows,
|
||||||
|
byDivisionCrop: byDivisionCrop.rows,
|
||||||
|
cropStructure: cropStructure.rows,
|
||||||
|
wheatYoy: wheatYoy.rows,
|
||||||
|
wheatEnterprises: {
|
||||||
|
top: wheatEnterprises.rows.slice(0, 15),
|
||||||
|
bottom: [...wheatEnterprises.rows].reverse().slice(0, 15),
|
||||||
|
},
|
||||||
|
stars: stars.rows,
|
||||||
|
risks: risks.rows,
|
||||||
|
scatter: scatter.rows,
|
||||||
|
coverage: coverage.rows,
|
||||||
|
unitsRisk: unitsRisk.rows,
|
||||||
|
};
|
||||||
|
|
||||||
|
fs.mkdirSync(path.dirname(OUT), { recursive: true });
|
||||||
|
fs.writeFileSync(OUT, JSON.stringify(payload));
|
||||||
|
const jsOut = path.join(__dirname, 'data', 'dashboard-data.js');
|
||||||
|
fs.writeFileSync(jsOut, `window.__DASH__=${JSON.stringify(payload)};\n`);
|
||||||
|
const mb = (fs.statSync(OUT).size / 1024 / 1024).toFixed(2);
|
||||||
|
console.log(`Wrote ${OUT} (${mb} MB)`);
|
||||||
|
console.log(`Wrote ${jsOut}`);
|
||||||
|
await c.end();
|
||||||
|
}
|
||||||
|
|
||||||
|
main().catch((e) => {
|
||||||
|
console.error(e);
|
||||||
|
process.exit(1);
|
||||||
|
});
|
||||||
@@ -0,0 +1,157 @@
|
|||||||
|
/**
|
||||||
|
* Выгрузка поле-лет с sowing_date + harvesting_date + productivity
|
||||||
|
* → data/dates.json + data/dates-data.js
|
||||||
|
*/
|
||||||
|
require('dotenv').config({ path: require('path').join(__dirname, '..', '.env') });
|
||||||
|
const fs = require('fs');
|
||||||
|
const path = require('path');
|
||||||
|
const { Client } = require('pg');
|
||||||
|
|
||||||
|
const OUT_JSON = path.join(__dirname, 'data', 'dates.json');
|
||||||
|
const OUT_JS = path.join(__dirname, 'data', 'dates-data.js');
|
||||||
|
|
||||||
|
const PROD_MAX = {
|
||||||
|
'Пшеница озимая': 120,
|
||||||
|
'Пшеница яровая мягкая': 100,
|
||||||
|
'Ячмень озимый': 120,
|
||||||
|
'Подсолнечник масличный': 50,
|
||||||
|
'Подсолнечник СПК (крупноплодный)': 50,
|
||||||
|
'Кукуруза на зерно': 150,
|
||||||
|
'Кукуруза на силос и зеленый корм': 800,
|
||||||
|
Соя: 50,
|
||||||
|
'Свекла сахарная': 800,
|
||||||
|
'Горох яровой': 60,
|
||||||
|
Горох: 60,
|
||||||
|
Рис: 120,
|
||||||
|
'Рапс озимый': 50,
|
||||||
|
'Лен масличный': 30,
|
||||||
|
};
|
||||||
|
|
||||||
|
function pg() {
|
||||||
|
return new Client({
|
||||||
|
host: process.env.PGHOST,
|
||||||
|
port: Number(process.env.PGPORT || 5432),
|
||||||
|
database: process.env.PGDATABASE || 'ak_fields',
|
||||||
|
user: process.env.PGUSER,
|
||||||
|
password: process.env.PGPASSWORD,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function uniqSorted(arr) {
|
||||||
|
return [...new Set(arr.filter(Boolean))].sort((a, b) =>
|
||||||
|
String(a).localeCompare(String(b), 'ru')
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function main() {
|
||||||
|
const c = pg();
|
||||||
|
await c.connect();
|
||||||
|
console.log('Extracting sowing/harvesting rows...');
|
||||||
|
|
||||||
|
const { rows } = await c.query(`
|
||||||
|
SELECT
|
||||||
|
f.name AS field,
|
||||||
|
NULLIF(trim(both FROM split_part(f.zone_hierarchy, ' -> ', 2)), '') AS division,
|
||||||
|
NULLIF(trim(both FROM split_part(f.zone_hierarchy, ' -> ', 3)), '') AS enterprise,
|
||||||
|
NULLIF(trim(both FROM split_part(f.zone_hierarchy, ' -> ', 4)), '') AS unit,
|
||||||
|
(item->>'year')::int AS year,
|
||||||
|
cr.name AS crop,
|
||||||
|
NULLIF(item->>'variety', '') AS variety,
|
||||||
|
(item->>'sowing_date')::date AS sowing_date,
|
||||||
|
(item->>'harvesting_date')::date AS harvesting_date,
|
||||||
|
NULLIF(item->>'productivity', '')::float AS productivity,
|
||||||
|
ROUND(COALESCE(f.calculated_area, 0)::numeric, 1)::float AS area_ha
|
||||||
|
FROM fields f
|
||||||
|
CROSS JOIN LATERAL jsonb_array_elements(f.history_items) item
|
||||||
|
LEFT JOIN crops cr ON cr.id = NULLIF(item->>'crop_id', '')::bigint
|
||||||
|
WHERE f.history_items IS NOT NULL
|
||||||
|
AND jsonb_typeof(f.history_items) = 'array'
|
||||||
|
AND NULLIF(item->>'sowing_date', '') IS NOT NULL
|
||||||
|
AND NULLIF(item->>'harvesting_date', '') IS NOT NULL
|
||||||
|
AND NULLIF(item->>'productivity', '')::float > 0
|
||||||
|
AND cr.name IS NOT NULL
|
||||||
|
AND (item->>'harvesting_date')::date >= (item->>'sowing_date')::date
|
||||||
|
`);
|
||||||
|
|
||||||
|
const cleaned = [];
|
||||||
|
let droppedProd = 0;
|
||||||
|
for (const r of rows) {
|
||||||
|
const max = PROD_MAX[r.crop] ?? 200;
|
||||||
|
if (r.productivity > max) {
|
||||||
|
droppedProd += 1;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
cleaned.push({
|
||||||
|
field: r.field,
|
||||||
|
division: r.division || 'Без дивизиона',
|
||||||
|
enterprise: r.enterprise || '—',
|
||||||
|
unit: r.unit || '—',
|
||||||
|
year: r.year,
|
||||||
|
crop: r.crop,
|
||||||
|
variety: r.variety || '—',
|
||||||
|
sowing: r.sowing_date.toISOString().slice(0, 10),
|
||||||
|
harvest: r.harvesting_date.toISOString().slice(0, 10),
|
||||||
|
productivity: Math.round(r.productivity * 10) / 10,
|
||||||
|
areaHa: r.area_ha,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const filters = {
|
||||||
|
divisions: uniqSorted(cleaned.map((r) => r.division)),
|
||||||
|
units: uniqSorted(cleaned.map((r) => r.unit)),
|
||||||
|
enterprises: uniqSorted(cleaned.map((r) => r.enterprise)),
|
||||||
|
years: uniqSorted(cleaned.map((r) => r.year)).sort((a, b) => a - b),
|
||||||
|
crops: uniqSorted(cleaned.map((r) => r.crop)),
|
||||||
|
varieties: uniqSorted(cleaned.map((r) => r.variety)),
|
||||||
|
};
|
||||||
|
|
||||||
|
// unit → divisions map for cascading filters
|
||||||
|
const unitsByDivision = {};
|
||||||
|
const varietiesByCrop = {};
|
||||||
|
for (const r of cleaned) {
|
||||||
|
if (!unitsByDivision[r.division]) unitsByDivision[r.division] = new Set();
|
||||||
|
unitsByDivision[r.division].add(r.unit);
|
||||||
|
if (!varietiesByCrop[r.crop]) varietiesByCrop[r.crop] = new Set();
|
||||||
|
varietiesByCrop[r.crop].add(r.variety);
|
||||||
|
}
|
||||||
|
const cascade = {
|
||||||
|
unitsByDivision: Object.fromEntries(
|
||||||
|
Object.entries(unitsByDivision).map(([k, v]) => [k, [...v].sort((a, b) => a.localeCompare(b, 'ru'))])
|
||||||
|
),
|
||||||
|
varietiesByCrop: Object.fromEntries(
|
||||||
|
Object.entries(varietiesByCrop).map(([k, v]) => [k, [...v].sort((a, b) => a.localeCompare(b, 'ru'))])
|
||||||
|
),
|
||||||
|
};
|
||||||
|
|
||||||
|
const payload = {
|
||||||
|
meta: {
|
||||||
|
generatedAt: new Date().toISOString(),
|
||||||
|
company: 'АО фирма «Агрокомплекс» им. Н.И. Ткачева',
|
||||||
|
productivityUnit: 'ц/га',
|
||||||
|
rowsRaw: rows.length,
|
||||||
|
rowsClean: cleaned.length,
|
||||||
|
droppedProdOutliers: droppedProd,
|
||||||
|
notes: [
|
||||||
|
'Только записи с sowing_date, harvesting_date и productivity > 0.',
|
||||||
|
'Отброшены строки, где уборка раньше сева.',
|
||||||
|
'Отброшены выбросы урожайности по культуре.',
|
||||||
|
'Heatmap не смешивает культуры: отдельная матрица на каждую выбранную культуру.',
|
||||||
|
],
|
||||||
|
},
|
||||||
|
filters,
|
||||||
|
cascade,
|
||||||
|
rows: cleaned,
|
||||||
|
};
|
||||||
|
|
||||||
|
fs.mkdirSync(path.dirname(OUT_JSON), { recursive: true });
|
||||||
|
fs.writeFileSync(OUT_JSON, JSON.stringify(payload));
|
||||||
|
fs.writeFileSync(OUT_JS, `window.__DATES__=${JSON.stringify(payload)};\n`);
|
||||||
|
const mb = (fs.statSync(OUT_JSON).size / 1024 / 1024).toFixed(2);
|
||||||
|
console.log(`Wrote ${OUT_JSON} (${mb} MB), rows=${cleaned.length}, droppedProd=${droppedProd}`);
|
||||||
|
await c.end();
|
||||||
|
}
|
||||||
|
|
||||||
|
main().catch((e) => {
|
||||||
|
console.error(e);
|
||||||
|
process.exit(1);
|
||||||
|
});
|
||||||
@@ -0,0 +1,494 @@
|
|||||||
|
/**
|
||||||
|
* Аудит качества fertilizer_field_acts → пригодность к факторному анализу.
|
||||||
|
* Запуск: node dashboard/build-fertilizer-quality-data.js
|
||||||
|
*/
|
||||||
|
require('dotenv').config({ path: require('path').join(__dirname, '..', '.env') });
|
||||||
|
const fs = require('fs');
|
||||||
|
const path = require('path');
|
||||||
|
const { Client } = require('pg');
|
||||||
|
|
||||||
|
const OUT_JSON = path.join(__dirname, 'data', 'fertilizer-quality.json');
|
||||||
|
const OUT_JS = path.join(__dirname, 'data', 'fertilizer-quality-data.js');
|
||||||
|
|
||||||
|
/** Мягкие/жёсткие потолки д.в. кг/га (юг РФ, сезонный итог по актам) */
|
||||||
|
const LIMITS = {
|
||||||
|
default: { nSoft: 280, nHard: 400, pSoft: 180, pHard: 300, kSoft: 250, kHard: 450 },
|
||||||
|
'Пшеница озимая': { nSoft: 280, nHard: 400, pSoft: 150, pHard: 250, kSoft: 180, kHard: 350 },
|
||||||
|
'Пшеница яровая мягкая': { nSoft: 250, nHard: 350, pSoft: 140, pHard: 220, kSoft: 160, kHard: 300 },
|
||||||
|
'Ячмень озимый': { nSoft: 220, nHard: 320, pSoft: 140, pHard: 220, kSoft: 160, kHard: 300 },
|
||||||
|
'Кукуруза на зерно': { nSoft: 280, nHard: 420, pSoft: 160, pHard: 280, kSoft: 220, kHard: 400 },
|
||||||
|
'Подсолнечник масличный': { nSoft: 140, nHard: 220, pSoft: 120, pHard: 200, kSoft: 200, kHard: 350 },
|
||||||
|
'Подсолнечник СПК (крупноплодный)': { nSoft: 140, nHard: 220, pSoft: 120, pHard: 200, kSoft: 200, kHard: 350 },
|
||||||
|
Соя: { nSoft: 100, nHard: 180, pSoft: 120, pHard: 200, kSoft: 160, kHard: 300 },
|
||||||
|
'Свекла сахарная': { nSoft: 220, nHard: 350, pSoft: 160, pHard: 280, kSoft: 280, kHard: 450 },
|
||||||
|
'Горох яровой': { nSoft: 80, nHard: 150, pSoft: 120, pHard: 200, kSoft: 140, kHard: 280 },
|
||||||
|
Горох: { nSoft: 80, nHard: 150, pSoft: 120, pHard: 200, kSoft: 140, kHard: 280 },
|
||||||
|
'Рапс озимый': { nSoft: 220, nHard: 320, pSoft: 140, pHard: 240, kSoft: 180, kHard: 320 },
|
||||||
|
'Лен масличный': { nSoft: 120, nHard: 200, pSoft: 100, pHard: 180, kSoft: 120, kHard: 220 },
|
||||||
|
};
|
||||||
|
|
||||||
|
const MASS_SOFT = 1500; // кг/га минералки без органики
|
||||||
|
const MASS_HARD = 3000;
|
||||||
|
const MANURE_SOFT = 60000; // кг/га
|
||||||
|
const MANURE_HARD = 120000;
|
||||||
|
const ACTS_SOFT = 25;
|
||||||
|
const ACTS_HARD = 50;
|
||||||
|
|
||||||
|
const PROD_MAX = {
|
||||||
|
'Пшеница озимая': 120,
|
||||||
|
'Пшеница яровая мягкая': 100,
|
||||||
|
'Ячмень озимый': 120,
|
||||||
|
'Подсолнечник масличный': 50,
|
||||||
|
'Подсолнечник СПК (крупноплодный)': 50,
|
||||||
|
'Кукуруза на зерно': 150,
|
||||||
|
'Кукуруза на силос и зеленый корм': 800,
|
||||||
|
Соя: 50,
|
||||||
|
'Свекла сахарная': 800,
|
||||||
|
'Горох яровой': 60,
|
||||||
|
Горох: 60,
|
||||||
|
Рис: 120,
|
||||||
|
'Рапс озимый': 50,
|
||||||
|
'Лен масличный': 30,
|
||||||
|
};
|
||||||
|
|
||||||
|
const FLAG_META = {
|
||||||
|
unlinked: { label: 'Нет связи с fields', severity: 'warn', analysis: 'partial' },
|
||||||
|
multi_crop: { label: 'Несколько культур в строке', severity: 'warn', analysis: 'exclude' },
|
||||||
|
zero_input: { label: 'Нулевые масса и NPK', severity: 'info', analysis: 'exclude' },
|
||||||
|
missing_dv: { label: 'Есть масса, нет д.в. NPK', severity: 'hard', analysis: 'exclude' },
|
||||||
|
incomplete_dv_acts: { label: 'Не все акты с д.в.', severity: 'warn', analysis: 'caution' },
|
||||||
|
n_soft: { label: 'N выше мягкого потолка', severity: 'warn', analysis: 'caution' },
|
||||||
|
n_hard: { label: 'N выше жёсткого потолка', severity: 'hard', analysis: 'exclude' },
|
||||||
|
p_soft: { label: 'P₂O₅ выше мягкого потолка', severity: 'warn', analysis: 'caution' },
|
||||||
|
p_hard: { label: 'P₂O₅ выше жёсткого потолка', severity: 'hard', analysis: 'exclude' },
|
||||||
|
k_soft: { label: 'K₂O выше мягкого потолка', severity: 'warn', analysis: 'caution' },
|
||||||
|
k_hard: { label: 'K₂O выше жёсткого потолка', severity: 'hard', analysis: 'exclude' },
|
||||||
|
mass_soft: { label: 'Масса удобрений высокая', severity: 'warn', analysis: 'caution' },
|
||||||
|
mass_hard: { label: 'Масса удобрений экстремальная', severity: 'hard', analysis: 'exclude' },
|
||||||
|
manure_soft: { label: 'Органика высокая', severity: 'warn', analysis: 'caution' },
|
||||||
|
manure_hard: { label: 'Органика экстремальная', severity: 'hard', analysis: 'exclude' },
|
||||||
|
npk_gt_mass: { label: 'NPK > массы (без органики)', severity: 'hard', analysis: 'exclude' },
|
||||||
|
acts_soft: { label: 'Много актов на поле-год', severity: 'warn', analysis: 'caution' },
|
||||||
|
acts_hard: { label: 'Сверхмного актов', severity: 'hard', analysis: 'exclude' },
|
||||||
|
prod_outlier: { label: 'Выброс урожайности', severity: 'hard', analysis: 'exclude' },
|
||||||
|
high_n_zero_yield: { label: 'Высокий N при нулевом урожае', severity: 'warn', analysis: 'caution' },
|
||||||
|
};
|
||||||
|
|
||||||
|
function pg() {
|
||||||
|
return new Client({
|
||||||
|
host: process.env.PGHOST,
|
||||||
|
port: Number(process.env.PGPORT || 5432),
|
||||||
|
database: process.env.PGDATABASE || 'ak_fields',
|
||||||
|
user: process.env.PGUSER,
|
||||||
|
password: process.env.PGPASSWORD,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function num(v) {
|
||||||
|
if (v == null) return null;
|
||||||
|
const n = Number(v);
|
||||||
|
return Number.isFinite(n) ? n : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function round(n, d = 1) {
|
||||||
|
if (n == null || Number.isNaN(Number(n))) return null;
|
||||||
|
const f = 10 ** d;
|
||||||
|
return Math.round(Number(n) * f) / f;
|
||||||
|
}
|
||||||
|
|
||||||
|
function primaryCrop(crop) {
|
||||||
|
if (!crop) return null;
|
||||||
|
return String(crop).split(';')[0].trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
function limitsFor(crop) {
|
||||||
|
return LIMITS[crop] || LIMITS.default;
|
||||||
|
}
|
||||||
|
|
||||||
|
function percentile(sorted, p) {
|
||||||
|
if (!sorted.length) return null;
|
||||||
|
const idx = (sorted.length - 1) * p;
|
||||||
|
const lo = Math.floor(idx);
|
||||||
|
const hi = Math.ceil(idx);
|
||||||
|
if (lo === hi) return sorted[lo];
|
||||||
|
return sorted[lo] * (1 - (idx - lo)) + sorted[hi] * (idx - lo);
|
||||||
|
}
|
||||||
|
|
||||||
|
function hist(values, edges) {
|
||||||
|
const bins = edges.slice(0, -1).map((lo, i) => ({
|
||||||
|
lo,
|
||||||
|
hi: edges[i + 1],
|
||||||
|
label: edges[i + 1] === Infinity ? `${lo}+` : `${lo}–${edges[i + 1]}`,
|
||||||
|
n: 0,
|
||||||
|
}));
|
||||||
|
for (const v of values) {
|
||||||
|
const x = Number(v);
|
||||||
|
if (!Number.isFinite(x)) continue;
|
||||||
|
for (const b of bins) {
|
||||||
|
if (x >= b.lo && x < b.hi) {
|
||||||
|
b.n += 1;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return bins;
|
||||||
|
}
|
||||||
|
|
||||||
|
function flagRow(r) {
|
||||||
|
const flags = [];
|
||||||
|
const crop = r.crop;
|
||||||
|
const lim = limitsFor(crop);
|
||||||
|
const n = r.nKgHa || 0;
|
||||||
|
const p = r.pKgHa || 0;
|
||||||
|
const k = r.kKgHa || 0;
|
||||||
|
const mass = r.massKgHa || 0;
|
||||||
|
const manure = r.manureKgHa || 0;
|
||||||
|
const mineralMass = Math.max(0, mass - manure);
|
||||||
|
const npk = n + p + k;
|
||||||
|
|
||||||
|
if (!r.linked) flags.push('unlinked');
|
||||||
|
if (r.multiCrop) flags.push('multi_crop');
|
||||||
|
if (mass <= 0 && npk <= 0 && manure <= 0) flags.push('zero_input');
|
||||||
|
if (mass > 0 && npk <= 0) flags.push('missing_dv');
|
||||||
|
if (r.acts != null && r.actsDv != null && r.acts > 0 && r.actsDv < r.acts) {
|
||||||
|
flags.push('incomplete_dv_acts');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (n >= lim.nHard) flags.push('n_hard');
|
||||||
|
else if (n >= lim.nSoft) flags.push('n_soft');
|
||||||
|
if (p >= lim.pHard) flags.push('p_hard');
|
||||||
|
else if (p >= lim.pSoft) flags.push('p_soft');
|
||||||
|
if (k >= lim.kHard) flags.push('k_hard');
|
||||||
|
else if (k >= lim.kSoft) flags.push('k_soft');
|
||||||
|
|
||||||
|
if (mineralMass >= MASS_HARD) flags.push('mass_hard');
|
||||||
|
else if (mineralMass >= MASS_SOFT) flags.push('mass_soft');
|
||||||
|
if (manure >= MANURE_HARD) flags.push('manure_hard');
|
||||||
|
else if (manure >= MANURE_SOFT) flags.push('manure_soft');
|
||||||
|
|
||||||
|
// д.в. не может заметно превышать массу минералки (грубая хим. проверка)
|
||||||
|
if (manure <= 0 && mineralMass > 0 && npk > mineralMass * 1.05) flags.push('npk_gt_mass');
|
||||||
|
|
||||||
|
if ((r.acts || 0) >= ACTS_HARD) flags.push('acts_hard');
|
||||||
|
else if ((r.acts || 0) >= ACTS_SOFT) flags.push('acts_soft');
|
||||||
|
|
||||||
|
if (r.productivity != null && r.productivity > 0) {
|
||||||
|
const max = PROD_MAX[crop] ?? 200;
|
||||||
|
if (r.productivity > max) flags.push('prod_outlier');
|
||||||
|
}
|
||||||
|
if ((r.productivity == null || r.productivity <= 0) && n >= lim.nSoft) {
|
||||||
|
flags.push('high_n_zero_yield');
|
||||||
|
}
|
||||||
|
|
||||||
|
return flags;
|
||||||
|
}
|
||||||
|
|
||||||
|
function severityOf(flags) {
|
||||||
|
let hard = 0;
|
||||||
|
let warn = 0;
|
||||||
|
for (const f of flags) {
|
||||||
|
const s = FLAG_META[f]?.severity;
|
||||||
|
if (s === 'hard') hard += 1;
|
||||||
|
else if (s === 'warn') warn += 1;
|
||||||
|
}
|
||||||
|
if (hard) return 'exclude';
|
||||||
|
if (warn) return 'caution';
|
||||||
|
return 'ok';
|
||||||
|
}
|
||||||
|
|
||||||
|
function bump(map, key, field = 'n') {
|
||||||
|
if (!map[key]) map[key] = { n: 0, ok: 0, caution: 0, exclude: 0 };
|
||||||
|
map[key][field] += 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function main() {
|
||||||
|
const c = pg();
|
||||||
|
await c.connect();
|
||||||
|
console.log('Building fertilizer quality audit...');
|
||||||
|
|
||||||
|
const exists = await c.query(`
|
||||||
|
SELECT EXISTS (
|
||||||
|
SELECT 1 FROM information_schema.tables
|
||||||
|
WHERE table_schema='public' AND table_name='fertilizer_field_acts'
|
||||||
|
) AS ok
|
||||||
|
`);
|
||||||
|
if (!exists.rows[0].ok) {
|
||||||
|
console.error('Table fertilizer_field_acts missing. Run: npm run fertilizer:load');
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
const { rows } = await c.query(`
|
||||||
|
SELECT
|
||||||
|
a.field_name AS field,
|
||||||
|
a.field_id IS NOT NULL AS linked,
|
||||||
|
NULLIF(trim(both FROM split_part(f.zone_hierarchy, ' -> ', 2)), '') AS division,
|
||||||
|
a.year,
|
||||||
|
a.crop AS crop_raw,
|
||||||
|
a.nomenclature,
|
||||||
|
a.area_ha::float AS area_ha,
|
||||||
|
a.acts_count AS acts,
|
||||||
|
a.acts_with_dv AS acts_dv,
|
||||||
|
a.fertilizer_mass_kg_ha::float AS mass_kg_ha,
|
||||||
|
a.manure_kg_ha::float AS manure_kg_ha,
|
||||||
|
a.n_kg_ha::float AS n_kg_ha,
|
||||||
|
a.p2o5_kg_ha::float AS p_kg_ha,
|
||||||
|
a.k2o_kg_ha::float AS k_kg_ha,
|
||||||
|
a.productivity::float AS productivity,
|
||||||
|
a.yield_category
|
||||||
|
FROM fertilizer_field_acts a
|
||||||
|
LEFT JOIN fields f ON f.id = a.field_id
|
||||||
|
WHERE a.year BETWEEN 2019 AND 2025
|
||||||
|
`);
|
||||||
|
|
||||||
|
const byFlag = {};
|
||||||
|
const byYear = {};
|
||||||
|
const byCrop = {};
|
||||||
|
const byDivision = {};
|
||||||
|
const examples = [];
|
||||||
|
const nVals = [];
|
||||||
|
const pVals = [];
|
||||||
|
const kVals = [];
|
||||||
|
const massVals = [];
|
||||||
|
const manureVals = [];
|
||||||
|
const actsVals = [];
|
||||||
|
|
||||||
|
let ok = 0;
|
||||||
|
let caution = 0;
|
||||||
|
let exclude = 0;
|
||||||
|
let withProd = 0;
|
||||||
|
let withDv = 0;
|
||||||
|
let withManure = 0;
|
||||||
|
let linked = 0;
|
||||||
|
let analysisReady = 0; // ok|caution + productivity + dv
|
||||||
|
|
||||||
|
for (const raw of rows) {
|
||||||
|
const crop = primaryCrop(raw.crop_raw);
|
||||||
|
const multiCrop = !!(raw.crop_raw && String(raw.crop_raw).includes(';'));
|
||||||
|
const r = {
|
||||||
|
field: raw.field,
|
||||||
|
linked: !!raw.linked,
|
||||||
|
division: raw.division || 'Без дивизиона',
|
||||||
|
year: raw.year,
|
||||||
|
crop,
|
||||||
|
multiCrop,
|
||||||
|
nomenclature: raw.nomenclature || '',
|
||||||
|
areaHa: round(num(raw.area_ha), 1),
|
||||||
|
acts: raw.acts,
|
||||||
|
actsDv: raw.acts_dv,
|
||||||
|
massKgHa: round(num(raw.mass_kg_ha), 1),
|
||||||
|
manureKgHa: round(num(raw.manure_kg_ha), 1),
|
||||||
|
nKgHa: round(num(raw.n_kg_ha), 1),
|
||||||
|
pKgHa: round(num(raw.p_kg_ha), 1),
|
||||||
|
kKgHa: round(num(raw.k_kg_ha), 1),
|
||||||
|
productivity:
|
||||||
|
raw.productivity != null && Number(raw.productivity) > 0
|
||||||
|
? round(num(raw.productivity), 1)
|
||||||
|
: null,
|
||||||
|
yieldCat: raw.yield_category || '—',
|
||||||
|
};
|
||||||
|
|
||||||
|
if (r.linked) linked += 1;
|
||||||
|
if (r.productivity != null) withProd += 1;
|
||||||
|
if ((r.nKgHa || 0) + (r.pKgHa || 0) + (r.kKgHa || 0) > 0) withDv += 1;
|
||||||
|
if ((r.manureKgHa || 0) > 0) withManure += 1;
|
||||||
|
|
||||||
|
if (r.nKgHa != null) nVals.push(r.nKgHa);
|
||||||
|
if (r.pKgHa != null) pVals.push(r.pKgHa);
|
||||||
|
if (r.kKgHa != null) kVals.push(r.kKgHa);
|
||||||
|
if (r.massKgHa != null) massVals.push(r.massKgHa);
|
||||||
|
if ((r.manureKgHa || 0) > 0) manureVals.push(r.manureKgHa);
|
||||||
|
if (r.acts != null) actsVals.push(r.acts);
|
||||||
|
|
||||||
|
const flags = flagRow(r);
|
||||||
|
const status = severityOf(flags);
|
||||||
|
if (status === 'ok') ok += 1;
|
||||||
|
else if (status === 'caution') caution += 1;
|
||||||
|
else exclude += 1;
|
||||||
|
|
||||||
|
const usableForImpact =
|
||||||
|
(status === 'ok' || status === 'caution') &&
|
||||||
|
r.productivity != null &&
|
||||||
|
(r.nKgHa || 0) + (r.pKgHa || 0) + (r.kKgHa || 0) > 0 &&
|
||||||
|
!r.multiCrop;
|
||||||
|
if (usableForImpact) analysisReady += 1;
|
||||||
|
|
||||||
|
for (const f of flags) {
|
||||||
|
byFlag[f] = (byFlag[f] || 0) + 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
bump(byYear, String(r.year), 'n');
|
||||||
|
bump(byYear, String(r.year), status);
|
||||||
|
bump(byCrop, r.crop || '—', 'n');
|
||||||
|
bump(byCrop, r.crop || '—', status);
|
||||||
|
bump(byDivision, r.division, 'n');
|
||||||
|
bump(byDivision, r.division, status);
|
||||||
|
|
||||||
|
if (flags.length) {
|
||||||
|
examples.push({
|
||||||
|
field: r.field,
|
||||||
|
division: r.division,
|
||||||
|
year: r.year,
|
||||||
|
crop: r.crop,
|
||||||
|
nKgHa: r.nKgHa,
|
||||||
|
pKgHa: r.pKgHa,
|
||||||
|
kKgHa: r.kKgHa,
|
||||||
|
massKgHa: r.massKgHa,
|
||||||
|
manureKgHa: r.manureKgHa,
|
||||||
|
acts: r.acts,
|
||||||
|
actsDv: r.actsDv,
|
||||||
|
productivity: r.productivity,
|
||||||
|
status,
|
||||||
|
flags,
|
||||||
|
score: flags.reduce((s, f) => s + (FLAG_META[f]?.severity === 'hard' ? 3 : 1), 0),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
examples.sort((a, b) => b.score - a.score || (b.nKgHa || 0) - (a.nKgHa || 0));
|
||||||
|
const topExamples = examples.slice(0, 250).map(({ score, ...rest }) => rest);
|
||||||
|
|
||||||
|
const sortNums = (arr) => [...arr].sort((a, b) => a - b);
|
||||||
|
const nS = sortNums(nVals);
|
||||||
|
const pS = sortNums(pVals);
|
||||||
|
const kS = sortNums(kVals);
|
||||||
|
const mS = sortNums(massVals);
|
||||||
|
|
||||||
|
const dist = {
|
||||||
|
n: hist(nVals, [0, 1, 50, 100, 150, 200, 250, 300, 400, 600, Infinity]),
|
||||||
|
p: hist(pVals, [0, 1, 30, 60, 100, 150, 200, 300, Infinity]),
|
||||||
|
k: hist(kVals, [0, 1, 30, 60, 100, 150, 200, 300, 450, Infinity]),
|
||||||
|
mass: hist(massVals, [0, 1, 100, 300, 500, 800, 1200, 2000, 3000, Infinity]),
|
||||||
|
manure: hist(manureVals, [0, 5000, 20000, 40000, 60000, 100000, Infinity]),
|
||||||
|
acts: hist(actsVals, [0, 1, 5, 10, 15, 25, 50, Infinity]),
|
||||||
|
};
|
||||||
|
|
||||||
|
const flagRows = Object.entries(byFlag)
|
||||||
|
.map(([id, n]) => ({
|
||||||
|
id,
|
||||||
|
n,
|
||||||
|
pct: round((100 * n) / rows.length, 1),
|
||||||
|
...FLAG_META[id],
|
||||||
|
}))
|
||||||
|
.sort((a, b) => b.n - a.n);
|
||||||
|
|
||||||
|
const toArr = (map) =>
|
||||||
|
Object.entries(map)
|
||||||
|
.map(([key, v]) => ({
|
||||||
|
key,
|
||||||
|
...v,
|
||||||
|
okPct: round((100 * v.ok) / v.n, 1),
|
||||||
|
cautionPct: round((100 * v.caution) / v.n, 1),
|
||||||
|
excludePct: round((100 * v.exclude) / v.n, 1),
|
||||||
|
}))
|
||||||
|
.sort((a, b) => b.n - a.n);
|
||||||
|
|
||||||
|
const total = rows.length;
|
||||||
|
const verdict =
|
||||||
|
analysisReady / total >= 0.55
|
||||||
|
? 'usable'
|
||||||
|
: analysisReady / total >= 0.35
|
||||||
|
? 'usable_with_filters'
|
||||||
|
: 'weak';
|
||||||
|
|
||||||
|
const payload = {
|
||||||
|
meta: {
|
||||||
|
generatedAt: new Date().toISOString(),
|
||||||
|
company: 'АО фирма «Агрокомплекс» им. Н.И. Ткачева',
|
||||||
|
rows: total,
|
||||||
|
years: '2019–2025',
|
||||||
|
nutrientUnit: 'кг д.в./га',
|
||||||
|
massUnit: 'кг/га',
|
||||||
|
limitsNote:
|
||||||
|
'Потолки — ориентир сезонного итога по актам для юга РФ, не техкарта хозяйства.',
|
||||||
|
notes: [
|
||||||
|
'Жёсткие флаги → исключать из dose–response; мягкие → оставлять с осторожностью.',
|
||||||
|
'missing_dv: масса списана, но д.в. не рассчитано — для NPK-анализа непригодно.',
|
||||||
|
'npk_gt_mass: сумма д.в. больше массы минералки — ошибка единиц или расчёта.',
|
||||||
|
'Баланс выноса на этой странице не считается — только sanity-check входных доз.',
|
||||||
|
'Доля «готова к анализу влияния» = без hard-флагов + есть урожайность + есть NPK + одна культура.',
|
||||||
|
],
|
||||||
|
},
|
||||||
|
limits: LIMITS,
|
||||||
|
thresholds: {
|
||||||
|
massSoft: MASS_SOFT,
|
||||||
|
massHard: MASS_HARD,
|
||||||
|
manureSoft: MANURE_SOFT,
|
||||||
|
manureHard: MANURE_HARD,
|
||||||
|
actsSoft: ACTS_SOFT,
|
||||||
|
actsHard: ACTS_HARD,
|
||||||
|
},
|
||||||
|
flagMeta: FLAG_META,
|
||||||
|
summary: {
|
||||||
|
rows: total,
|
||||||
|
linked,
|
||||||
|
linkedPct: round((100 * linked) / total, 1),
|
||||||
|
withDv,
|
||||||
|
withDvPct: round((100 * withDv) / total, 1),
|
||||||
|
withProd,
|
||||||
|
withProdPct: round((100 * withProd) / total, 1),
|
||||||
|
withManure,
|
||||||
|
withManurePct: round((100 * withManure) / total, 1),
|
||||||
|
ok,
|
||||||
|
caution,
|
||||||
|
exclude,
|
||||||
|
okPct: round((100 * ok) / total, 1),
|
||||||
|
cautionPct: round((100 * caution) / total, 1),
|
||||||
|
excludePct: round((100 * exclude) / total, 1),
|
||||||
|
analysisReady,
|
||||||
|
analysisReadyPct: round((100 * analysisReady) / total, 1),
|
||||||
|
verdict,
|
||||||
|
verdictText:
|
||||||
|
verdict === 'usable'
|
||||||
|
? 'Данные в целом пригодны для анализа влияния при фильтрации hard-выбросов.'
|
||||||
|
: verdict === 'usable_with_filters'
|
||||||
|
? 'Анализ влияния возможен, но нужна жёсткая фильтрация и проверка по культурам/годам.'
|
||||||
|
: 'Качество слабое: большая доля строк непригодна; факторный анализ будет смещён.',
|
||||||
|
},
|
||||||
|
quantiles: {
|
||||||
|
n: {
|
||||||
|
p50: round(percentile(nS, 0.5), 1),
|
||||||
|
p90: round(percentile(nS, 0.9), 1),
|
||||||
|
p99: round(percentile(nS, 0.99), 1),
|
||||||
|
max: nS.length ? round(nS[nS.length - 1], 1) : null,
|
||||||
|
},
|
||||||
|
p: {
|
||||||
|
p50: round(percentile(pS, 0.5), 1),
|
||||||
|
p90: round(percentile(pS, 0.9), 1),
|
||||||
|
p99: round(percentile(pS, 0.99), 1),
|
||||||
|
max: pS.length ? round(pS[pS.length - 1], 1) : null,
|
||||||
|
},
|
||||||
|
k: {
|
||||||
|
p50: round(percentile(kS, 0.5), 1),
|
||||||
|
p90: round(percentile(kS, 0.9), 1),
|
||||||
|
p99: round(percentile(kS, 0.99), 1),
|
||||||
|
max: kS.length ? round(kS[kS.length - 1], 1) : null,
|
||||||
|
},
|
||||||
|
mass: {
|
||||||
|
p50: round(percentile(mS, 0.5), 1),
|
||||||
|
p90: round(percentile(mS, 0.9), 1),
|
||||||
|
p99: round(percentile(mS, 0.99), 1),
|
||||||
|
max: mS.length ? round(mS[mS.length - 1], 1) : null,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
distributions: dist,
|
||||||
|
flags: flagRows,
|
||||||
|
byYear: toArr(byYear).sort((a, b) => Number(a.key) - Number(b.key)),
|
||||||
|
byCrop: toArr(byCrop).slice(0, 25),
|
||||||
|
byDivision: toArr(byDivision),
|
||||||
|
examples: topExamples,
|
||||||
|
};
|
||||||
|
|
||||||
|
fs.mkdirSync(path.dirname(OUT_JSON), { recursive: true });
|
||||||
|
fs.writeFileSync(OUT_JSON, JSON.stringify(payload));
|
||||||
|
fs.writeFileSync(OUT_JS, `window.__FERT_Q__=${JSON.stringify(payload)};\n`);
|
||||||
|
const mb = (fs.statSync(OUT_JSON).size / 1024 / 1024).toFixed(2);
|
||||||
|
console.log(
|
||||||
|
`Wrote ${OUT_JSON} (${mb} MB). ready=${payload.summary.analysisReadyPct}% verdict=${verdict}`
|
||||||
|
);
|
||||||
|
await c.end();
|
||||||
|
}
|
||||||
|
|
||||||
|
main().catch((e) => {
|
||||||
|
console.error(e);
|
||||||
|
process.exit(1);
|
||||||
|
});
|
||||||
@@ -0,0 +1,241 @@
|
|||||||
|
/**
|
||||||
|
* Выгрузка fertilizer_field_acts (+ zone из fields) → data/fertilizers.json + fertilizers-data.js
|
||||||
|
* Запуск: node dashboard/build-fertilizers-data.js
|
||||||
|
*/
|
||||||
|
require('dotenv').config({ path: require('path').join(__dirname, '..', '.env') });
|
||||||
|
const fs = require('fs');
|
||||||
|
const path = require('path');
|
||||||
|
const { Client } = require('pg');
|
||||||
|
|
||||||
|
const OUT_JSON = path.join(__dirname, 'data', 'fertilizers.json');
|
||||||
|
const OUT_JS = path.join(__dirname, 'data', 'fertilizers-data.js');
|
||||||
|
|
||||||
|
/** Вынос питательных веществ, кг д.в. на 1 т основной продукции (порядок величины) */
|
||||||
|
const REMOVAL_PER_T = {
|
||||||
|
'Пшеница озимая': { n: 32.5, p: 11, k: 22.5 },
|
||||||
|
'Пшеница яровая мягкая': { n: 32.5, p: 11, k: 22.5 },
|
||||||
|
'Ячмень озимый': { n: 28, p: 11, k: 22 },
|
||||||
|
'Кукуруза на зерно': { n: 27.5, p: 11, k: 27.5 },
|
||||||
|
'Подсолнечник масличный': { n: 55, p: 27.5, k: 100 },
|
||||||
|
'Подсолнечник СПК (крупноплодный)': { n: 55, p: 27.5, k: 100 },
|
||||||
|
Соя: { n: 75, p: 17.5, k: 35 },
|
||||||
|
'Свекла сахарная': { n: 5, p: 1.5, k: 7 },
|
||||||
|
'Горох яровой': { n: 55, p: 15, k: 30 },
|
||||||
|
Горох: { n: 55, p: 15, k: 30 },
|
||||||
|
'Рапс озимый': { n: 50, p: 22, k: 40 },
|
||||||
|
'Лен масличный': { n: 40, p: 15, k: 30 },
|
||||||
|
};
|
||||||
|
|
||||||
|
const PROD_MAX = {
|
||||||
|
'Пшеница озимая': 120,
|
||||||
|
'Пшеница яровая мягкая': 100,
|
||||||
|
'Ячмень озимый': 120,
|
||||||
|
'Подсолнечник масличный': 50,
|
||||||
|
'Подсолнечник СПК (крупноплодный)': 50,
|
||||||
|
'Кукуруза на зерно': 150,
|
||||||
|
'Кукуруза на силос и зеленый корм': 800,
|
||||||
|
Соя: 50,
|
||||||
|
'Свекла сахарная': 800,
|
||||||
|
'Горох яровой': 60,
|
||||||
|
Горох: 60,
|
||||||
|
Рис: 120,
|
||||||
|
'Рапс озимый': 50,
|
||||||
|
'Лен масличный': 30,
|
||||||
|
};
|
||||||
|
|
||||||
|
const FOCUS_CROPS = Object.keys(REMOVAL_PER_T);
|
||||||
|
|
||||||
|
function pg() {
|
||||||
|
return new Client({
|
||||||
|
host: process.env.PGHOST,
|
||||||
|
port: Number(process.env.PGPORT || 5432),
|
||||||
|
database: process.env.PGDATABASE || 'ak_fields',
|
||||||
|
user: process.env.PGUSER,
|
||||||
|
password: process.env.PGPASSWORD,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function uniqSorted(arr) {
|
||||||
|
return [...new Set(arr.filter((x) => x != null && x !== ''))].sort((a, b) =>
|
||||||
|
String(a).localeCompare(String(b), 'ru')
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function round(n, d = 1) {
|
||||||
|
if (n == null || Number.isNaN(Number(n))) return null;
|
||||||
|
const f = 10 ** d;
|
||||||
|
return Math.round(Number(n) * f) / f;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Первая культура из строки вида "Культура A; Культура B" */
|
||||||
|
function primaryCrop(crop) {
|
||||||
|
if (!crop) return null;
|
||||||
|
return crop.split(';')[0].trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
function isFocusCrop(crop) {
|
||||||
|
return FOCUS_CROPS.includes(crop);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function main() {
|
||||||
|
const c = pg();
|
||||||
|
await c.connect();
|
||||||
|
console.log('Extracting fertilizer_field_acts...');
|
||||||
|
|
||||||
|
const exists = await c.query(`
|
||||||
|
SELECT EXISTS (
|
||||||
|
SELECT 1 FROM information_schema.tables
|
||||||
|
WHERE table_schema='public' AND table_name='fertilizer_field_acts'
|
||||||
|
) AS ok
|
||||||
|
`);
|
||||||
|
if (!exists.rows[0].ok) {
|
||||||
|
console.error('Table fertilizer_field_acts missing. Run: node load_fertilizer_field.js');
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
const { rows } = await c.query(`
|
||||||
|
SELECT
|
||||||
|
a.field_name AS field,
|
||||||
|
a.field_id IS NOT NULL AS linked,
|
||||||
|
NULLIF(trim(both FROM split_part(f.zone_hierarchy, ' -> ', 2)), '') AS division,
|
||||||
|
NULLIF(trim(both FROM split_part(f.zone_hierarchy, ' -> ', 3)), '') AS enterprise,
|
||||||
|
NULLIF(trim(both FROM split_part(f.zone_hierarchy, ' -> ', 4)), '') AS unit,
|
||||||
|
a.year,
|
||||||
|
a.crop,
|
||||||
|
a.nomenclature,
|
||||||
|
ROUND(COALESCE(a.area_ha, 0)::numeric, 1)::float AS area_ha,
|
||||||
|
a.acts_count,
|
||||||
|
a.acts_with_dv,
|
||||||
|
a.yield_category,
|
||||||
|
a.stability_category,
|
||||||
|
a.fertilizer_mass_kg_ha::float AS mass_kg_ha,
|
||||||
|
a.manure_kg_ha::float AS manure_kg_ha,
|
||||||
|
a.n_kg_ha::float AS n_kg_ha,
|
||||||
|
a.p2o5_kg_ha::float AS p_kg_ha,
|
||||||
|
a.k2o_kg_ha::float AS k_kg_ha,
|
||||||
|
a.productivity::float AS productivity
|
||||||
|
FROM fertilizer_field_acts a
|
||||||
|
LEFT JOIN fields f ON f.id = a.field_id
|
||||||
|
WHERE a.year BETWEEN 2019 AND 2025
|
||||||
|
`);
|
||||||
|
|
||||||
|
const cleaned = [];
|
||||||
|
let droppedProd = 0;
|
||||||
|
let multiCrop = 0;
|
||||||
|
|
||||||
|
for (const r of rows) {
|
||||||
|
const crop = primaryCrop(r.crop);
|
||||||
|
if (!crop) continue;
|
||||||
|
if (r.crop && r.crop.includes(';')) multiCrop += 1;
|
||||||
|
|
||||||
|
const prod = r.productivity;
|
||||||
|
if (prod != null && prod > 0) {
|
||||||
|
const max = PROD_MAX[crop] ?? 200;
|
||||||
|
if (prod > max) {
|
||||||
|
droppedProd += 1;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const rem = REMOVAL_PER_T[crop];
|
||||||
|
let nBalance = null;
|
||||||
|
let pBalance = null;
|
||||||
|
let kBalance = null;
|
||||||
|
if (rem && prod != null && prod > 0) {
|
||||||
|
const tHa = prod / 10; // ц/га → т/га
|
||||||
|
nBalance = round((r.n_kg_ha || 0) - rem.n * tHa, 1);
|
||||||
|
pBalance = round((r.p_kg_ha || 0) - rem.p * tHa, 1);
|
||||||
|
kBalance = round((r.k_kg_ha || 0) - rem.k * tHa, 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
cleaned.push({
|
||||||
|
field: r.field,
|
||||||
|
linked: !!r.linked,
|
||||||
|
division: r.division || 'Без дивизиона',
|
||||||
|
unit: r.unit || '—',
|
||||||
|
year: r.year,
|
||||||
|
crop,
|
||||||
|
areaHa: r.area_ha,
|
||||||
|
yieldCat: r.yield_category || '—',
|
||||||
|
stabCat: r.stability_category || '—',
|
||||||
|
massKgHa: round(r.mass_kg_ha, 1),
|
||||||
|
manureKgHa: round(r.manure_kg_ha, 1),
|
||||||
|
nKgHa: round(r.n_kg_ha, 1),
|
||||||
|
pKgHa: round(r.p_kg_ha, 1),
|
||||||
|
kKgHa: round(r.k_kg_ha, 1),
|
||||||
|
productivity: prod != null && prod > 0 ? round(prod, 1) : null,
|
||||||
|
nBalance,
|
||||||
|
focus: isFocusCrop(crop),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const filters = {
|
||||||
|
divisions: uniqSorted(cleaned.map((r) => r.division)),
|
||||||
|
units: uniqSorted(cleaned.map((r) => r.unit)),
|
||||||
|
years: uniqSorted(cleaned.map((r) => r.year)).sort((a, b) => a - b),
|
||||||
|
crops: uniqSorted(cleaned.map((r) => r.crop)),
|
||||||
|
focusCrops: FOCUS_CROPS.filter((c) => cleaned.some((r) => r.crop === c)),
|
||||||
|
yieldCats: uniqSorted(cleaned.map((r) => r.yieldCat)),
|
||||||
|
stabCats: uniqSorted(cleaned.map((r) => r.stabCat)),
|
||||||
|
};
|
||||||
|
|
||||||
|
const unitsByDivision = {};
|
||||||
|
for (const r of cleaned) {
|
||||||
|
if (!unitsByDivision[r.division]) unitsByDivision[r.division] = new Set();
|
||||||
|
unitsByDivision[r.division].add(r.unit);
|
||||||
|
}
|
||||||
|
const cascade = {
|
||||||
|
unitsByDivision: Object.fromEntries(
|
||||||
|
Object.entries(unitsByDivision).map(([k, v]) => [
|
||||||
|
k,
|
||||||
|
[...v].sort((a, b) => a.localeCompare(b, 'ru')),
|
||||||
|
])
|
||||||
|
),
|
||||||
|
};
|
||||||
|
|
||||||
|
const linkedRows = cleaned.filter((r) => r.linked).length;
|
||||||
|
const withProd = cleaned.filter((r) => r.productivity != null).length;
|
||||||
|
const withManure = cleaned.filter((r) => (r.manureKgHa || 0) > 0).length;
|
||||||
|
|
||||||
|
const payload = {
|
||||||
|
meta: {
|
||||||
|
generatedAt: new Date().toISOString(),
|
||||||
|
company: 'АО фирма «Агрокомплекс» им. Н.И. Ткачева',
|
||||||
|
productivityUnit: 'ц/га',
|
||||||
|
nutrientUnit: 'кг д.в./га',
|
||||||
|
rowsRaw: rows.length,
|
||||||
|
rowsClean: cleaned.length,
|
||||||
|
linkedRows,
|
||||||
|
withProductivity: withProd,
|
||||||
|
withManure,
|
||||||
|
droppedProdOutliers: droppedProd,
|
||||||
|
multiCropRows: multiCrop,
|
||||||
|
notes: [
|
||||||
|
'Источник: акты списания удобрений на поля (агрегат поле×год).',
|
||||||
|
'N/P₂O₅/K₂O — рассчитанное действующее вещество, кг/га.',
|
||||||
|
'Баланс = внесено − ориентировочный вынос (кг/га). Отрицательный = вынос больше внесения (почва/последействие).',
|
||||||
|
'Соя: вынос N биологический; значительная доля — фиксация, не доза удобрения.',
|
||||||
|
'Культуры с «;» в акте свёрнуты до первой культуры.',
|
||||||
|
'Годы 2019–2025; выбросы урожайности отфильтрованы по культуре.',
|
||||||
|
],
|
||||||
|
},
|
||||||
|
removalPerT: REMOVAL_PER_T,
|
||||||
|
filters,
|
||||||
|
cascade,
|
||||||
|
rows: cleaned,
|
||||||
|
};
|
||||||
|
|
||||||
|
fs.mkdirSync(path.dirname(OUT_JSON), { recursive: true });
|
||||||
|
fs.writeFileSync(OUT_JSON, JSON.stringify(payload));
|
||||||
|
fs.writeFileSync(OUT_JS, `window.__FERT__=${JSON.stringify(payload)};\n`);
|
||||||
|
const mb = (fs.statSync(OUT_JSON).size / 1024 / 1024).toFixed(2);
|
||||||
|
console.log(
|
||||||
|
`Wrote ${OUT_JSON} (${mb} MB), rows=${cleaned.length}, linked=${linkedRows}, droppedProd=${droppedProd}`
|
||||||
|
);
|
||||||
|
await c.end();
|
||||||
|
}
|
||||||
|
|
||||||
|
main().catch((e) => {
|
||||||
|
console.error(e);
|
||||||
|
process.exit(1);
|
||||||
|
});
|
||||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -0,0 +1,318 @@
|
|||||||
|
(() => {
|
||||||
|
const D = window.__DATES__;
|
||||||
|
if (!D) {
|
||||||
|
document.body.innerHTML =
|
||||||
|
'<p style="padding:2rem;font-family:sans-serif">Нет данных. Запустите <code>npm run dashboard:dates</code></p>';
|
||||||
|
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 = `
|
||||||
|
<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() {
|
||||||
|
// 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 = `<article class="panel crop-block" data-crop="${crop}">
|
||||||
|
<h3>${crop}</h3>
|
||||||
|
<div class="heat-meta">
|
||||||
|
<div class="kpi"><div class="label">Наблюдений</div><div class="value">${fmt.int(kpi.n)}</div></div>
|
||||||
|
<div class="kpi"><div class="label">Медиана, ц/га</div><div class="value">${fmt.num(kpi.median, 1)}</div></div>
|
||||||
|
<div class="kpi"><div class="label">Средняя, ц/га</div><div class="value">${fmt.num(kpi.mean, 1)}</div></div>
|
||||||
|
<div class="kpi"><div class="label">Ср. вегетация, дней</div><div class="value">${fmt.num(kpi.days, 0)}</div></div>
|
||||||
|
</div>
|
||||||
|
<div class="heat-wrap"><div class="heat-grid" style="grid-template-columns: 52px repeat(${xs.length}, 34px);">`;
|
||||||
|
|
||||||
|
html += `<div class="heat-corner">уборка ↓ / сев →</div>`;
|
||||||
|
for (const x of xs) html += `<div class="heat-x">${weekLabel(x)}</div>`;
|
||||||
|
|
||||||
|
for (const y of ys) {
|
||||||
|
html += `<div class="heat-y">${weekLabel(y)}</div>`;
|
||||||
|
for (const x of xs) {
|
||||||
|
const vals = cells.get(`${x}|${y}`);
|
||||||
|
if (!vals || !vals.length) {
|
||||||
|
html += `<div class="heat-cell empty" title="нет данных"></div>`;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const med = median(vals);
|
||||||
|
const t = (med - vmin) / span;
|
||||||
|
const title = `Сев ${weekLabel(x)}, уборка ${weekLabel(y)}\nмедиана ${med.toFixed(1)} ц/га\nn=${vals.length}`;
|
||||||
|
html += `<div class="heat-cell" style="background:${colorScale(t)}" title="${title}">${med.toFixed(0)}</div>`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
html += `</div></div>
|
||||||
|
<div class="heat-legend">
|
||||||
|
<span>${fmt.num(vmin, 1)}</span>
|
||||||
|
<div class="bar" aria-hidden="true"></div>
|
||||||
|
<span>${fmt.num(vmax, 1)} ц/га</span>
|
||||||
|
<span>· ячейка = медиана урожайности, подпись — ц/га, пустые — нет наблюдений</span>
|
||||||
|
</div>
|
||||||
|
</article>`;
|
||||||
|
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 = `
|
||||||
|
<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"><div class="label">Культур на графиках</div><div class="value">${fmt.int(cropList.filter((c) => rows.some((r) => r.crop === c)).length)}</div><div class="sub">без смешивания</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">Средняя ц/га</div><div class="value">${fmt.num(mean(prods), 1)}</div></div>
|
||||||
|
`;
|
||||||
|
|
||||||
|
const host = document.getElementById('heatmaps');
|
||||||
|
if (!rows.length) {
|
||||||
|
host.innerHTML = `<div class="warn">Нет строк по текущим фильтрам. Снимите часть ограничений.</div>`;
|
||||||
|
} else if (!cropList.length) {
|
||||||
|
host.innerHTML = `<div class="warn">Выберите хотя бы одну культуру — культуры на heatmap не смешиваются.</div>`;
|
||||||
|
} else {
|
||||||
|
host.innerHTML = cropList.map((c) => buildHeatmap(rows, c)).join('') ||
|
||||||
|
`<div class="warn">По выбранным культурам нет данных в выборке.</div>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
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) => `<tr>
|
||||||
|
<td title="${r.field}">${r.field}</td>
|
||||||
|
<td title="${r.division}">${r.division}</td>
|
||||||
|
<td title="${r.unit}">${r.unit}</td>
|
||||||
|
<td class="num">${r.year}</td>
|
||||||
|
<td>${r.crop}</td>
|
||||||
|
<td title="${r.variety}">${r.variety}</td>
|
||||||
|
<td>${r.sowing}</td>
|
||||||
|
<td>${r.harvest}</td>
|
||||||
|
<td class="num">${daysBetween(r.sowing, r.harvest)}</td>
|
||||||
|
<td class="num">${fmt.num(r.productivity, 1)}</td>
|
||||||
|
<td class="num">${fmt.num(r.areaHa, 1)}</td>
|
||||||
|
</tr>`
|
||||||
|
)
|
||||||
|
.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();
|
||||||
|
})();
|
||||||
@@ -0,0 +1,98 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="ru">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8" />
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||||
|
<title>Даты сева и уборки — влияние на урожайность</title>
|
||||||
|
<link rel="preconnect" href="https://fonts.googleapis.com" />
|
||||||
|
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
|
||||||
|
<link href="https://fonts.googleapis.com/css2?family=Manrope:wght@400;500;600;700;800&family=Fraunces:opsz,wght@9..144,500;9..144,700&display=swap" rel="stylesheet" />
|
||||||
|
<link rel="stylesheet" href="styles.css" />
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div class="bg-orb bg-orb-a" aria-hidden="true"></div>
|
||||||
|
<div class="bg-orb bg-orb-b" aria-hidden="true"></div>
|
||||||
|
|
||||||
|
<nav class="site-nav" aria-label="Разделы анализа">
|
||||||
|
<a href="index.html">Портфель полей</a>
|
||||||
|
<a class="active" href="dates.html">Даты сева и уборки</a>
|
||||||
|
<a href="predecessor.html">Предшественник</a>
|
||||||
|
<a href="fertilizers.html">Удобрения</a>
|
||||||
|
<a href="fertilizer-quality.html">Качество удобрений</a>
|
||||||
|
</nav>
|
||||||
|
|
||||||
|
<header class="page-head">
|
||||||
|
<p class="eyebrow">Факторный анализ · Cropwise</p>
|
||||||
|
<h1>Влияние дат сева и уборки на урожайность</h1>
|
||||||
|
<p>
|
||||||
|
Heatmap: ось X — неделя сева, ось Y — неделя уборки, цвет — медиана урожайности (ц/га).
|
||||||
|
Культуры на одном графике не смешиваются: для каждой выбранной культуры — своя матрица.
|
||||||
|
</p>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<nav class="filters dense" aria-label="Фильтры">
|
||||||
|
<details class="ms" id="msDivision">
|
||||||
|
<summary><span data-label>Дивизион</span></summary>
|
||||||
|
<div class="ms-panel" data-panel></div>
|
||||||
|
</details>
|
||||||
|
<details class="ms" id="msUnit">
|
||||||
|
<summary><span data-label>Подразделение</span></summary>
|
||||||
|
<div class="ms-panel" data-panel></div>
|
||||||
|
</details>
|
||||||
|
<details class="ms" id="msYear">
|
||||||
|
<summary><span data-label>Год</span></summary>
|
||||||
|
<div class="ms-panel" data-panel></div>
|
||||||
|
</details>
|
||||||
|
<details class="ms" id="msCrop">
|
||||||
|
<summary><span data-label>Культура</span></summary>
|
||||||
|
<div class="ms-panel" data-panel></div>
|
||||||
|
</details>
|
||||||
|
<details class="ms" id="msVariety">
|
||||||
|
<summary><span data-label>Гибрид / сорт</span></summary>
|
||||||
|
<div class="ms-panel" data-panel></div>
|
||||||
|
</details>
|
||||||
|
<button type="button" class="ghost" id="btnApply">Применить</button>
|
||||||
|
<button type="button" class="ghost" id="btnReset">Сбросить</button>
|
||||||
|
</nav>
|
||||||
|
|
||||||
|
<main>
|
||||||
|
<section class="heat-meta" id="kpiStrip"></section>
|
||||||
|
<section id="heatmaps"></section>
|
||||||
|
|
||||||
|
<section class="panel">
|
||||||
|
<header class="panel-h">
|
||||||
|
<h2>Данные выборки</h2>
|
||||||
|
<p id="sampleMeta">Отфильтрованные поле-годы с датами сева и уборки</p>
|
||||||
|
</header>
|
||||||
|
<div class="table-wrap" style="max-height: 480px">
|
||||||
|
<table id="tblSample">
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th>Поле</th>
|
||||||
|
<th>Дивизион</th>
|
||||||
|
<th>Подразделение</th>
|
||||||
|
<th>Год</th>
|
||||||
|
<th>Культура</th>
|
||||||
|
<th>Гибрид</th>
|
||||||
|
<th>Сев</th>
|
||||||
|
<th>Уборка</th>
|
||||||
|
<th>Дней</th>
|
||||||
|
<th>ц/га</th>
|
||||||
|
<th>га</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody></tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
</main>
|
||||||
|
|
||||||
|
<footer class="foot">
|
||||||
|
<p>Перегенерация: <code>npm run dashboard:dates</code></p>
|
||||||
|
<p id="footMeta"></p>
|
||||||
|
</footer>
|
||||||
|
|
||||||
|
<script src="data/dates-data.js"></script>
|
||||||
|
<script src="dates-app.js"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,289 @@
|
|||||||
|
(() => {
|
||||||
|
const D = window.__FERT_Q__;
|
||||||
|
if (!D) {
|
||||||
|
document.body.innerHTML =
|
||||||
|
'<p style="padding:2rem;font-family:sans-serif">Нет данных. Запустите <code>npm run dashboard:fert-quality</code></p>';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const charts = {};
|
||||||
|
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,
|
||||||
|
}),
|
||||||
|
pct: (n) => (n == null ? '—' : `${fmt.num(n, 1)}%`),
|
||||||
|
};
|
||||||
|
|
||||||
|
function esc(s) {
|
||||||
|
return String(s ?? '')
|
||||||
|
.replace(/&/g, '&')
|
||||||
|
.replace(/</g, '<')
|
||||||
|
.replace(/>/g, '>');
|
||||||
|
}
|
||||||
|
|
||||||
|
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];
|
||||||
|
}
|
||||||
|
|
||||||
|
const s = D.summary;
|
||||||
|
const verdictClass =
|
||||||
|
s.verdict === 'usable' ? 'good' : s.verdict === 'usable_with_filters' ? 'gold' : 'risk';
|
||||||
|
|
||||||
|
document.getElementById('kpiStrip').innerHTML = `
|
||||||
|
<div class="kpi"><div class="label">Строк 2019–2025</div><div class="value">${fmt.int(s.rows)}</div></div>
|
||||||
|
<div class="kpi good"><div class="label">Готовы к анализу</div><div class="value">${fmt.pct(s.analysisReadyPct)}</div><div class="sub">${fmt.int(s.analysisReady)} поле-лет</div></div>
|
||||||
|
<div class="kpi"><div class="label">ok</div><div class="value">${fmt.pct(s.okPct)}</div></div>
|
||||||
|
<div class="kpi gold"><div class="label">caution</div><div class="value">${fmt.pct(s.cautionPct)}</div></div>
|
||||||
|
<div class="kpi risk"><div class="label">exclude</div><div class="value">${fmt.pct(s.excludePct)}</div></div>
|
||||||
|
<div class="kpi"><div class="label">Есть д.в. NPK</div><div class="value">${fmt.pct(s.withDvPct)}</div></div>
|
||||||
|
<div class="kpi"><div class="label">С урожайностью</div><div class="value">${fmt.pct(s.withProdPct)}</div></div>
|
||||||
|
<div class="kpi"><div class="label">Связь с fields</div><div class="value">${fmt.pct(s.linkedPct)}</div></div>
|
||||||
|
`;
|
||||||
|
|
||||||
|
document.getElementById('verdictBox').innerHTML = `
|
||||||
|
<div class="verdict-card ${verdictClass}">
|
||||||
|
<div class="verdict-label">Вердикт</div>
|
||||||
|
<div class="verdict-text">${esc(s.verdictText)}</div>
|
||||||
|
<div class="verdict-sub">Критерий «готова к анализу влияния»: без hard-флагов + урожайность + NPK + одна культура.</div>
|
||||||
|
</div>
|
||||||
|
`;
|
||||||
|
|
||||||
|
makeChart('chartStatus', {
|
||||||
|
type: 'doughnut',
|
||||||
|
data: {
|
||||||
|
labels: ['ok', 'caution', 'exclude'],
|
||||||
|
datasets: [
|
||||||
|
{
|
||||||
|
data: [s.ok, s.caution, s.exclude],
|
||||||
|
backgroundColor: ['#2f6b3a', '#b8892d', '#a33b2a'],
|
||||||
|
borderWidth: 0,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
options: {
|
||||||
|
responsive: true,
|
||||||
|
maintainAspectRatio: false,
|
||||||
|
plugins: { legend: { position: 'bottom' } },
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const topFlags = D.flags.slice(0, 10);
|
||||||
|
makeChart('chartFlags', {
|
||||||
|
type: 'bar',
|
||||||
|
data: {
|
||||||
|
labels: topFlags.map((f) => f.label),
|
||||||
|
datasets: [
|
||||||
|
{
|
||||||
|
label: '% строк',
|
||||||
|
data: topFlags.map((f) => f.pct),
|
||||||
|
backgroundColor: topFlags.map((f) =>
|
||||||
|
f.severity === 'hard' ? '#a33b2a' : f.severity === 'warn' ? '#b8892d' : '#7a9a78'
|
||||||
|
),
|
||||||
|
borderRadius: 6,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
options: {
|
||||||
|
indexAxis: 'y',
|
||||||
|
responsive: true,
|
||||||
|
maintainAspectRatio: false,
|
||||||
|
plugins: { legend: { display: false } },
|
||||||
|
scales: {
|
||||||
|
x: { title: { display: true, text: '%' }, grid: { color: 'rgba(44,36,22,0.06)' } },
|
||||||
|
y: { grid: { display: false }, ticks: { font: { size: 11 } } },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
function histChart(id, bins, color) {
|
||||||
|
makeChart(id, {
|
||||||
|
type: 'bar',
|
||||||
|
data: {
|
||||||
|
labels: bins.map((b) => b.label),
|
||||||
|
datasets: [
|
||||||
|
{
|
||||||
|
data: bins.map((b) => b.n),
|
||||||
|
backgroundColor: color,
|
||||||
|
borderRadius: 6,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
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 }, ticks: { maxRotation: 45, font: { size: 10 } } },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
histChart('chartHistN', D.distributions.n, '#2f6b3a');
|
||||||
|
histChart('chartHistMass', D.distributions.mass, '#4a6fa5');
|
||||||
|
|
||||||
|
makeChart('chartByYear', {
|
||||||
|
type: 'bar',
|
||||||
|
data: {
|
||||||
|
labels: D.byYear.map((r) => r.key),
|
||||||
|
datasets: [
|
||||||
|
{ label: 'ok', data: D.byYear.map((r) => r.okPct), backgroundColor: '#2f6b3a', stack: 's' },
|
||||||
|
{
|
||||||
|
label: 'caution',
|
||||||
|
data: D.byYear.map((r) => r.cautionPct),
|
||||||
|
backgroundColor: '#b8892d',
|
||||||
|
stack: 's',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'exclude',
|
||||||
|
data: D.byYear.map((r) => r.excludePct),
|
||||||
|
backgroundColor: '#a33b2a',
|
||||||
|
stack: 's',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
options: {
|
||||||
|
responsive: true,
|
||||||
|
maintainAspectRatio: false,
|
||||||
|
plugins: { legend: { position: 'bottom' } },
|
||||||
|
scales: {
|
||||||
|
x: { stacked: true, grid: { display: false } },
|
||||||
|
y: {
|
||||||
|
stacked: true,
|
||||||
|
max: 100,
|
||||||
|
title: { display: true, text: '%' },
|
||||||
|
grid: { color: 'rgba(44,36,22,0.06)' },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const divs = [...D.byDivision].sort((a, b) => b.excludePct - a.excludePct);
|
||||||
|
makeChart('chartByDiv', {
|
||||||
|
type: 'bar',
|
||||||
|
data: {
|
||||||
|
labels: divs.map((d) => d.key.replace(/^Дивизион\s+/, '')),
|
||||||
|
datasets: [
|
||||||
|
{
|
||||||
|
label: 'exclude %',
|
||||||
|
data: divs.map((d) => d.excludePct),
|
||||||
|
backgroundColor: '#a33b2a',
|
||||||
|
borderRadius: 6,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
options: {
|
||||||
|
indexAxis: 'y',
|
||||||
|
responsive: true,
|
||||||
|
maintainAspectRatio: false,
|
||||||
|
plugins: { legend: { display: false } },
|
||||||
|
scales: {
|
||||||
|
x: { title: { display: true, text: '%' }, grid: { color: 'rgba(44,36,22,0.06)' } },
|
||||||
|
y: { grid: { display: false } },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const q = D.quantiles;
|
||||||
|
document.querySelector('#tblQuant tbody').innerHTML = [
|
||||||
|
['N, кг/га', q.n],
|
||||||
|
['P₂O₅, кг/га', q.p],
|
||||||
|
['K₂O, кг/га', q.k],
|
||||||
|
['Масса, кг/га', q.mass],
|
||||||
|
]
|
||||||
|
.map(
|
||||||
|
([name, v]) => `<tr>
|
||||||
|
<td>${name}</td>
|
||||||
|
<td>${fmt.num(v.p50, 0)}</td>
|
||||||
|
<td>${fmt.num(v.p90, 0)}</td>
|
||||||
|
<td>${fmt.num(v.p99, 0)}</td>
|
||||||
|
<td>${fmt.num(v.max, 0)}</td>
|
||||||
|
</tr>`
|
||||||
|
)
|
||||||
|
.join('');
|
||||||
|
|
||||||
|
const sevRu = { hard: 'hard', warn: 'warn', info: 'info' };
|
||||||
|
const anRu = {
|
||||||
|
exclude: 'исключить',
|
||||||
|
caution: 'осторожно',
|
||||||
|
partial: 'частично',
|
||||||
|
ok: 'ok',
|
||||||
|
};
|
||||||
|
document.querySelector('#tblFlags tbody').innerHTML = D.flags
|
||||||
|
.map(
|
||||||
|
(f) => `<tr>
|
||||||
|
<td>${esc(f.label)}<div class="sub-cell">${esc(f.id)}</div></td>
|
||||||
|
<td>${fmt.int(f.n)}</td>
|
||||||
|
<td>${fmt.pct(f.pct)}</td>
|
||||||
|
<td><span class="tag ${f.severity}">${sevRu[f.severity] || f.severity}</span></td>
|
||||||
|
<td>${anRu[f.analysis] || f.analysis}</td>
|
||||||
|
</tr>`
|
||||||
|
)
|
||||||
|
.join('');
|
||||||
|
|
||||||
|
const crops = [...D.byCrop].sort((a, b) => b.excludePct - a.excludePct).slice(0, 20);
|
||||||
|
document.querySelector('#tblCrop tbody').innerHTML = crops
|
||||||
|
.map(
|
||||||
|
(r) => `<tr>
|
||||||
|
<td>${esc(r.key)}</td>
|
||||||
|
<td>${fmt.int(r.n)}</td>
|
||||||
|
<td>${fmt.pct(r.okPct)}</td>
|
||||||
|
<td>${fmt.pct(r.cautionPct)}</td>
|
||||||
|
<td>${fmt.pct(r.excludePct)}</td>
|
||||||
|
</tr>`
|
||||||
|
)
|
||||||
|
.join('');
|
||||||
|
|
||||||
|
document.getElementById('exMeta').textContent =
|
||||||
|
`Показаны ${D.examples.length} худших поле-лет (из строк с флагами)`;
|
||||||
|
document.querySelector('#tblExamples tbody').innerHTML = D.examples
|
||||||
|
.map((r) => {
|
||||||
|
const flagLabels = (r.flags || [])
|
||||||
|
.map((id) => D.flagMeta[id]?.label || id)
|
||||||
|
.join('; ');
|
||||||
|
return `<tr>
|
||||||
|
<td>${esc(r.field)}</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.massKgHa, 0)}</td>
|
||||||
|
<td>${r.acts ?? '—'} / ${r.actsDv ?? '—'}</td>
|
||||||
|
<td>${fmt.num(r.productivity, 1)}</td>
|
||||||
|
<td><span class="tag ${r.status === 'exclude' ? 'hard' : r.status === 'caution' ? 'warn' : 'info'}">${esc(r.status)}</span></td>
|
||||||
|
<td class="flags-cell">${esc(flagLabels)}</td>
|
||||||
|
</tr>`;
|
||||||
|
})
|
||||||
|
.join('');
|
||||||
|
|
||||||
|
const notes = [...(D.meta.notes || [])];
|
||||||
|
notes.push(D.meta.limitsNote);
|
||||||
|
notes.push(
|
||||||
|
`Пороги массы: soft ${D.thresholds.massSoft} / hard ${D.thresholds.massHard} кг/га; органика soft ${D.thresholds.manureSoft} / hard ${D.thresholds.manureHard}.`
|
||||||
|
);
|
||||||
|
const wheat = D.limits['Пшеница озимая'];
|
||||||
|
if (wheat) {
|
||||||
|
notes.push(
|
||||||
|
`Пример потолков пшеницы озимой: N soft ${wheat.nSoft} / hard ${wheat.nHard}; P ${wheat.pSoft}/${wheat.pHard}; K ${wheat.kSoft}/${wheat.kHard} кг/га.`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
document.getElementById('notesList').innerHTML = notes
|
||||||
|
.map((n) => `<li>${esc(n)}</li>`)
|
||||||
|
.join('');
|
||||||
|
|
||||||
|
document.getElementById('footMeta').textContent =
|
||||||
|
`Сгенерировано ${new Date(D.meta.generatedAt).toLocaleString('ru-RU')} · строк ${fmt.int(D.meta.rows)}`;
|
||||||
|
})();
|
||||||
@@ -0,0 +1,193 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="ru">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8" />
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||||
|
<title>Качество данных по удобрениям</title>
|
||||||
|
<link rel="preconnect" href="https://fonts.googleapis.com" />
|
||||||
|
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
|
||||||
|
<link href="https://fonts.googleapis.com/css2?family=Manrope:wght@400;500;600;700;800&family=Fraunces:opsz,wght@9..144,500;9..144,700&display=swap" rel="stylesheet" />
|
||||||
|
<link rel="stylesheet" href="styles.css" />
|
||||||
|
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.8/dist/chart.umd.min.js"></script>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div class="bg-orb bg-orb-a" aria-hidden="true"></div>
|
||||||
|
<div class="bg-orb bg-orb-b" aria-hidden="true"></div>
|
||||||
|
|
||||||
|
<nav class="site-nav" aria-label="Разделы анализа">
|
||||||
|
<a href="index.html">Портфель полей</a>
|
||||||
|
<a href="dates.html">Даты сева и уборки</a>
|
||||||
|
<a href="predecessor.html">Предшественник</a>
|
||||||
|
<a href="fertilizers.html">Удобрения</a>
|
||||||
|
<a class="active" href="fertilizer-quality.html">Качество удобрений</a>
|
||||||
|
</nav>
|
||||||
|
|
||||||
|
<header class="page-head">
|
||||||
|
<p class="eyebrow">Аудит данных · акты списания</p>
|
||||||
|
<h1>Можно ли использовать данные по удобрениям?</h1>
|
||||||
|
<p>
|
||||||
|
Выбросы доз NPK, пропуски д.в., неадекватные массы и покрытие по годам/культурам —
|
||||||
|
до факторного анализа влияния на урожайность.
|
||||||
|
</p>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<main>
|
||||||
|
<section class="heat-meta" id="kpiStrip"></section>
|
||||||
|
<section class="verdict" id="verdictBox"></section>
|
||||||
|
|
||||||
|
<section class="grid-2" style="margin-top:14px">
|
||||||
|
<article class="panel">
|
||||||
|
<header class="panel-h">
|
||||||
|
<h2>Статус строк</h2>
|
||||||
|
<p>ok / осторожно / исключить</p>
|
||||||
|
</header>
|
||||||
|
<div class="chart-box md"><canvas id="chartStatus"></canvas></div>
|
||||||
|
</article>
|
||||||
|
<article class="panel">
|
||||||
|
<header class="panel-h">
|
||||||
|
<h2>Частые флаги</h2>
|
||||||
|
<p>Доля строк с нарушением</p>
|
||||||
|
</header>
|
||||||
|
<div class="chart-box md"><canvas id="chartFlags"></canvas></div>
|
||||||
|
</article>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="grid-2" style="margin-top:14px">
|
||||||
|
<article class="panel">
|
||||||
|
<header class="panel-h">
|
||||||
|
<h2>Распределение N, кг/га</h2>
|
||||||
|
<p>Гистограмма сезонных доз азота</p>
|
||||||
|
</header>
|
||||||
|
<div class="chart-box md"><canvas id="chartHistN"></canvas></div>
|
||||||
|
</article>
|
||||||
|
<article class="panel">
|
||||||
|
<header class="panel-h">
|
||||||
|
<h2>Распределение массы удобрений</h2>
|
||||||
|
<p>кг/га по актам (включая органику в сумме)</p>
|
||||||
|
</header>
|
||||||
|
<div class="chart-box md"><canvas id="chartHistMass"></canvas></div>
|
||||||
|
</article>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="grid-2" style="margin-top:14px">
|
||||||
|
<article class="panel">
|
||||||
|
<header class="panel-h">
|
||||||
|
<h2>Качество по годам</h2>
|
||||||
|
<p>Доля exclude / caution / ok</p>
|
||||||
|
</header>
|
||||||
|
<div class="chart-box md"><canvas id="chartByYear"></canvas></div>
|
||||||
|
</article>
|
||||||
|
<article class="panel">
|
||||||
|
<header class="panel-h">
|
||||||
|
<h2>Качество по дивизионам</h2>
|
||||||
|
<p>Доля строк к исключению</p>
|
||||||
|
</header>
|
||||||
|
<div class="chart-box md"><canvas id="chartByDiv"></canvas></div>
|
||||||
|
</article>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="panel" style="margin-top:14px">
|
||||||
|
<header class="panel-h">
|
||||||
|
<h2>Квантили NPK и массы</h2>
|
||||||
|
<p>p50 / p90 / p99 / max — где начинаются хвосты</p>
|
||||||
|
</header>
|
||||||
|
<div class="table-wrap">
|
||||||
|
<table id="tblQuant">
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th>Показатель</th>
|
||||||
|
<th>p50</th>
|
||||||
|
<th>p90</th>
|
||||||
|
<th>p99</th>
|
||||||
|
<th>max</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody></tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="panel" style="margin-top:14px">
|
||||||
|
<header class="panel-h">
|
||||||
|
<h2>Флаги и правило для анализа</h2>
|
||||||
|
<p>hard → exclude, warn → caution</p>
|
||||||
|
</header>
|
||||||
|
<div class="table-wrap">
|
||||||
|
<table id="tblFlags">
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th>Флаг</th>
|
||||||
|
<th>Строк</th>
|
||||||
|
<th>%</th>
|
||||||
|
<th>Тяжесть</th>
|
||||||
|
<th>Для анализа влияния</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody></tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="panel" style="margin-top:14px">
|
||||||
|
<header class="panel-h">
|
||||||
|
<h2>Топ культур по доле exclude</h2>
|
||||||
|
<p>Где данные хуже всего</p>
|
||||||
|
</header>
|
||||||
|
<div class="table-wrap" style="max-height: 360px">
|
||||||
|
<table id="tblCrop">
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th>Культура</th>
|
||||||
|
<th>Строк</th>
|
||||||
|
<th>ok %</th>
|
||||||
|
<th>caution %</th>
|
||||||
|
<th>exclude %</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody></tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="panel" style="margin-top:14px">
|
||||||
|
<header class="panel-h">
|
||||||
|
<h2>Примеры выбросов</h2>
|
||||||
|
<p id="exMeta">Худшие поле-годы по сумме флагов</p>
|
||||||
|
</header>
|
||||||
|
<div class="table-wrap" style="max-height: 480px">
|
||||||
|
<table id="tblExamples">
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th>Поле</th>
|
||||||
|
<th>Год</th>
|
||||||
|
<th>Культура</th>
|
||||||
|
<th>N</th>
|
||||||
|
<th>P</th>
|
||||||
|
<th>K</th>
|
||||||
|
<th>Масса</th>
|
||||||
|
<th>Акты</th>
|
||||||
|
<th>ц/га</th>
|
||||||
|
<th>Статус</th>
|
||||||
|
<th>Флаги</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody></tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="panel muted" style="margin-top:14px">
|
||||||
|
<header class="panel-h"><h2>Правила потолков</h2></header>
|
||||||
|
<ul class="notes-list" id="notesList"></ul>
|
||||||
|
</section>
|
||||||
|
</main>
|
||||||
|
|
||||||
|
<footer class="foot">
|
||||||
|
<p>Перегенерация: <code>npm run dashboard:fert-quality</code></p>
|
||||||
|
<p id="footMeta"></p>
|
||||||
|
</footer>
|
||||||
|
|
||||||
|
<script src="data/fertilizer-quality-data.js"></script>
|
||||||
|
<script src="fertilizer-quality-app.js"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -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();
|
||||||
|
})();
|
||||||
@@ -0,0 +1,154 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="ru">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8" />
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||||
|
<title>Внесение удобрений — влияние на урожайность</title>
|
||||||
|
<link rel="preconnect" href="https://fonts.googleapis.com" />
|
||||||
|
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
|
||||||
|
<link href="https://fonts.googleapis.com/css2?family=Manrope:wght@400;500;600;700;800&family=Fraunces:opsz,wght@9..144,500;9..144,700&display=swap" rel="stylesheet" />
|
||||||
|
<link rel="stylesheet" href="styles.css" />
|
||||||
|
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.8/dist/chart.umd.min.js"></script>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div class="bg-orb bg-orb-a" aria-hidden="true"></div>
|
||||||
|
<div class="bg-orb bg-orb-b" aria-hidden="true"></div>
|
||||||
|
|
||||||
|
<nav class="site-nav" aria-label="Разделы анализа">
|
||||||
|
<a href="index.html">Портфель полей</a>
|
||||||
|
<a href="dates.html">Даты сева и уборки</a>
|
||||||
|
<a href="predecessor.html">Предшественник</a>
|
||||||
|
<a class="active" href="fertilizers.html">Удобрения</a>
|
||||||
|
<a href="fertilizer-quality.html">Качество удобрений</a>
|
||||||
|
</nav>
|
||||||
|
|
||||||
|
<header class="page-head">
|
||||||
|
<p class="eyebrow">Факторный анализ · акты списания</p>
|
||||||
|
<h1>Внесение удобрений и урожайность</h1>
|
||||||
|
<p>
|
||||||
|
Dose–response по N/P₂O₅/K₂O (кг д.в./га), баланс «внесено − вынос», органика.
|
||||||
|
Культуры на графиках не смешиваются — выбирайте одну или несколько отдельно.
|
||||||
|
</p>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<nav class="filters dense" aria-label="Фильтры">
|
||||||
|
<details class="ms" id="msDivision">
|
||||||
|
<summary><span data-label>Дивизион</span></summary>
|
||||||
|
<div class="ms-panel" data-panel></div>
|
||||||
|
</details>
|
||||||
|
<details class="ms" id="msUnit">
|
||||||
|
<summary><span data-label>Подразделение</span></summary>
|
||||||
|
<div class="ms-panel" data-panel></div>
|
||||||
|
</details>
|
||||||
|
<details class="ms" id="msYear">
|
||||||
|
<summary><span data-label>Год</span></summary>
|
||||||
|
<div class="ms-panel" data-panel></div>
|
||||||
|
</details>
|
||||||
|
<details class="ms" id="msCrop">
|
||||||
|
<summary><span data-label>Культура</span></summary>
|
||||||
|
<div class="ms-panel" data-panel></div>
|
||||||
|
</details>
|
||||||
|
<details class="ms" id="msYieldCat">
|
||||||
|
<summary><span data-label>Категория урожайности</span></summary>
|
||||||
|
<div class="ms-panel" data-panel></div>
|
||||||
|
</details>
|
||||||
|
<details class="ms" id="msStabCat">
|
||||||
|
<summary><span data-label>Стабильность</span></summary>
|
||||||
|
<div class="ms-panel" data-panel></div>
|
||||||
|
</details>
|
||||||
|
<label class="chk-inline"><input type="checkbox" id="chkProdOnly" checked /> Только с урожайностью</label>
|
||||||
|
<label class="chk-inline"><input type="checkbox" id="chkFocusOnly" checked /> Фокусные культуры</label>
|
||||||
|
<button type="button" class="ghost" id="btnApply">Применить</button>
|
||||||
|
<button type="button" class="ghost" id="btnReset">Сбросить</button>
|
||||||
|
</nav>
|
||||||
|
|
||||||
|
<main>
|
||||||
|
<section class="heat-meta" id="kpiStrip"></section>
|
||||||
|
|
||||||
|
<section class="grid-2">
|
||||||
|
<article class="panel">
|
||||||
|
<header class="panel-h">
|
||||||
|
<h2>Dose–response: азот → урожайность</h2>
|
||||||
|
<p>Бины по N кг/га; точка — медиана ц/га, размер — число поле-лет</p>
|
||||||
|
</header>
|
||||||
|
<div class="chart-box lg"><canvas id="chartDoseN"></canvas></div>
|
||||||
|
</article>
|
||||||
|
<article class="panel">
|
||||||
|
<header class="panel-h">
|
||||||
|
<h2>Баланс N (внесено − вынос)</h2>
|
||||||
|
<p>Ориентир выноса по культуре; отрицательный = вынос больше внесения</p>
|
||||||
|
</header>
|
||||||
|
<div class="chart-box lg"><canvas id="chartBalance"></canvas></div>
|
||||||
|
</article>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="grid-2" style="margin-top:14px">
|
||||||
|
<article class="panel">
|
||||||
|
<header class="panel-h">
|
||||||
|
<h2>NPK в выборке</h2>
|
||||||
|
<p>Медианы действующих веществ, кг/га</p>
|
||||||
|
</header>
|
||||||
|
<div class="chart-box md"><canvas id="chartNpk"></canvas></div>
|
||||||
|
</article>
|
||||||
|
<article class="panel">
|
||||||
|
<header class="panel-h">
|
||||||
|
<h2>Heatmap: бин N × категория поля</h2>
|
||||||
|
<p>Цвет — медиана урожайности (ц/га)</p>
|
||||||
|
</header>
|
||||||
|
<div id="heatNCat"></div>
|
||||||
|
</article>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="panel" style="margin-top:14px">
|
||||||
|
<header class="panel-h">
|
||||||
|
<h2>Органика (навоз и ППЖ)</h2>
|
||||||
|
<p id="manureMeta">Поля с внесением органики vs без</p>
|
||||||
|
</header>
|
||||||
|
<div class="chart-box md"><canvas id="chartManure"></canvas></div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="panel" style="margin-top:14px">
|
||||||
|
<header class="panel-h">
|
||||||
|
<h2>Данные выборки</h2>
|
||||||
|
<p id="sampleMeta">Поле-годы с актами списания удобрений</p>
|
||||||
|
</header>
|
||||||
|
<div class="table-wrap" style="max-height: 480px">
|
||||||
|
<table id="tblSample">
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th>Поле</th>
|
||||||
|
<th>Дивизион</th>
|
||||||
|
<th>Год</th>
|
||||||
|
<th>Культура</th>
|
||||||
|
<th>N</th>
|
||||||
|
<th>P₂O₅</th>
|
||||||
|
<th>K₂O</th>
|
||||||
|
<th>Органика</th>
|
||||||
|
<th>Баланс N</th>
|
||||||
|
<th>ц/га</th>
|
||||||
|
<th>Категория</th>
|
||||||
|
<th>га</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody></tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="panel muted" style="margin-top:14px">
|
||||||
|
<header class="panel-h">
|
||||||
|
<h2>Как читать</h2>
|
||||||
|
</header>
|
||||||
|
<ul class="notes-list" id="notesList"></ul>
|
||||||
|
</section>
|
||||||
|
</main>
|
||||||
|
|
||||||
|
<footer class="foot">
|
||||||
|
<p>Перегенерация: <code>npm run dashboard:fert</code> · загрузка CSV: <code>node load_fertilizer_field.js</code></p>
|
||||||
|
<p id="footMeta"></p>
|
||||||
|
</footer>
|
||||||
|
|
||||||
|
<script src="data/fertilizers-data.js"></script>
|
||||||
|
<script src="fertilizers-app.js"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,286 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="ru">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8" />
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||||
|
<title>Урожайность полей — Агрокомплекс им. Н.И. Ткачева</title>
|
||||||
|
<link rel="preconnect" href="https://fonts.googleapis.com" />
|
||||||
|
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
|
||||||
|
<link href="https://fonts.googleapis.com/css2?family=Manrope:wght@400;500;600;700;800&family=Fraunces:opsz,wght@9..144,500;9..144,700&display=swap" rel="stylesheet" />
|
||||||
|
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.8/dist/chart.umd.min.js"></script>
|
||||||
|
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels@2.2.0/dist/chartjs-plugin-datalabels.min.js"></script>
|
||||||
|
<link rel="stylesheet" href="styles.css" />
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div class="bg-orb bg-orb-a" aria-hidden="true"></div>
|
||||||
|
<div class="bg-orb bg-orb-b" aria-hidden="true"></div>
|
||||||
|
|
||||||
|
<nav class="site-nav" aria-label="Разделы анализа">
|
||||||
|
<a class="active" href="index.html">Портфель полей</a>
|
||||||
|
<a href="dates.html">Даты сева и уборки</a>
|
||||||
|
<a href="predecessor.html">Предшественник</a>
|
||||||
|
<a href="fertilizers.html">Удобрения</a>
|
||||||
|
<a href="fertilizer-quality.html">Качество удобрений</a>
|
||||||
|
</nav>
|
||||||
|
|
||||||
|
<header class="hero">
|
||||||
|
<div class="hero-inner">
|
||||||
|
<p class="eyebrow">Аналитика полевого портфеля · Cropwise</p>
|
||||||
|
<h1>Агрокомплекс<br /><span>им. Н.И. Ткачева</span></h1>
|
||||||
|
<p class="lede">
|
||||||
|
Урожайность, стабильность и структура полей по дивизионам, предприятиям и культурам.
|
||||||
|
Данные: <code>ak_fields</code> + классификация <code>fields_clustered_all</code>.
|
||||||
|
</p>
|
||||||
|
<div class="hero-meta" id="heroMeta"></div>
|
||||||
|
</div>
|
||||||
|
<div class="hero-panel" id="kpiStrip"></div>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<nav class="filters" aria-label="Фильтры дашборда">
|
||||||
|
<label>
|
||||||
|
Дивизион
|
||||||
|
<select id="fltDivision"></select>
|
||||||
|
</label>
|
||||||
|
<label>
|
||||||
|
Культура (тренды)
|
||||||
|
<select id="fltCrop"></select>
|
||||||
|
</label>
|
||||||
|
<button type="button" id="btnReset" class="ghost">Сбросить</button>
|
||||||
|
<span class="filter-hint" id="filterHint"></span>
|
||||||
|
</nav>
|
||||||
|
|
||||||
|
<main>
|
||||||
|
<section class="insights" id="insights"></section>
|
||||||
|
|
||||||
|
<section class="grid-2">
|
||||||
|
<article class="panel">
|
||||||
|
<header class="panel-h">
|
||||||
|
<h2>Портфель: урожайность × стабильность</h2>
|
||||||
|
<p>Доля площади в матрице 3×3 — главный управленческий разрез</p>
|
||||||
|
</header>
|
||||||
|
<div class="matrix" id="matrix"></div>
|
||||||
|
<div class="chart-box lg">
|
||||||
|
<canvas id="chartPortfolio" aria-label="Доля площади по категориям"></canvas>
|
||||||
|
</div>
|
||||||
|
</article>
|
||||||
|
<article class="panel">
|
||||||
|
<header class="panel-h">
|
||||||
|
<h2>Индекс урожайности vs стабильность</h2>
|
||||||
|
<p>Каждая точка — поле (выборка). Правее — урожайнее, выше — нестабильнее</p>
|
||||||
|
</header>
|
||||||
|
<div class="chart-box lg">
|
||||||
|
<canvas id="chartScatter" aria-label="Scatter индекс и стабильность"></canvas>
|
||||||
|
</div>
|
||||||
|
</article>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="panel">
|
||||||
|
<header class="panel-h">
|
||||||
|
<h2>Дивизионы</h2>
|
||||||
|
<p>Площадь, индекс урожайности, доля «звёзд» и зоны риска</p>
|
||||||
|
</header>
|
||||||
|
<div class="grid-2 tight">
|
||||||
|
<div class="chart-box md">
|
||||||
|
<canvas id="chartDivArea" aria-label="Площадь по дивизионам"></canvas>
|
||||||
|
</div>
|
||||||
|
<div class="chart-box md">
|
||||||
|
<canvas id="chartDivIndex" aria-label="Индекс по дивизионам"></canvas>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="table-wrap">
|
||||||
|
<table id="tblDivisions">
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th>Дивизион</th>
|
||||||
|
<th>Поля</th>
|
||||||
|
<th>Площадь, га</th>
|
||||||
|
<th>Индекс</th>
|
||||||
|
<th>Стаб. std</th>
|
||||||
|
<th>Звёзды</th>
|
||||||
|
<th>Риск</th>
|
||||||
|
<th>Высок.</th>
|
||||||
|
<th>Средн.</th>
|
||||||
|
<th>Малоурож.</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody></tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="grid-2">
|
||||||
|
<article class="panel">
|
||||||
|
<header class="panel-h">
|
||||||
|
<h2>Динамика урожайности</h2>
|
||||||
|
<p>Средняя и медиана, ц/га · фильтр по культуре</p>
|
||||||
|
</header>
|
||||||
|
<div class="chart-box md">
|
||||||
|
<canvas id="chartCropTrend" aria-label="Тренд урожайности культуры"></canvas>
|
||||||
|
</div>
|
||||||
|
</article>
|
||||||
|
<article class="panel">
|
||||||
|
<header class="panel-h">
|
||||||
|
<h2>Структура посевов</h2>
|
||||||
|
<p>Топ культур по площади за выбранный горизонт</p>
|
||||||
|
</header>
|
||||||
|
<div class="chart-box md">
|
||||||
|
<canvas id="chartCropShare" aria-label="Структура культур"></canvas>
|
||||||
|
</div>
|
||||||
|
</article>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="panel">
|
||||||
|
<header class="panel-h">
|
||||||
|
<h2>Озимая пшеница — флагман</h2>
|
||||||
|
<p>Урожайность по дивизионам и годам, ц/га</p>
|
||||||
|
</header>
|
||||||
|
<div class="chart-box lg">
|
||||||
|
<canvas id="chartWheat" aria-label="Пшеница по дивизионам"></canvas>
|
||||||
|
</div>
|
||||||
|
<div class="grid-2">
|
||||||
|
<div>
|
||||||
|
<h3 class="subh">Лидеры предприятий (медиана, 3 года)</h3>
|
||||||
|
<div class="table-wrap compact">
|
||||||
|
<table id="tblWheatTop">
|
||||||
|
<thead><tr><th>#</th><th>Предприятие</th><th>Дивизион</th><th>Мед.</th><th>Ср.</th><th>Поля</th></tr></thead>
|
||||||
|
<tbody></tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<h3 class="subh">Отстающие предприятия</h3>
|
||||||
|
<div class="table-wrap compact">
|
||||||
|
<table id="tblWheatBottom">
|
||||||
|
<thead><tr><th>#</th><th>Предприятие</th><th>Дивизион</th><th>Мед.</th><th>Ср.</th><th>Поля</th></tr></thead>
|
||||||
|
<tbody></tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="grid-2">
|
||||||
|
<article class="panel">
|
||||||
|
<header class="panel-h">
|
||||||
|
<h2>Урожайность культур по дивизионам</h2>
|
||||||
|
<p>Медиана ц/га за период (выбранная культура)</p>
|
||||||
|
</header>
|
||||||
|
<div class="chart-box md">
|
||||||
|
<canvas id="chartDivCrop" aria-label="Культура по дивизионам"></canvas>
|
||||||
|
</div>
|
||||||
|
</article>
|
||||||
|
<article class="panel">
|
||||||
|
<header class="panel-h">
|
||||||
|
<h2>Лет в обороте и качество поля</h2>
|
||||||
|
<p>Как индекс и доля высокоурожайных зависят от истории</p>
|
||||||
|
</header>
|
||||||
|
<div class="chart-box md">
|
||||||
|
<canvas id="chartRotation" aria-label="Годы в обороте"></canvas>
|
||||||
|
</div>
|
||||||
|
</article>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="grid-2">
|
||||||
|
<article class="panel">
|
||||||
|
<header class="panel-h">
|
||||||
|
<h2>Распределение индекса</h2>
|
||||||
|
<p>1.0 ≈ норма дивизиона</p>
|
||||||
|
</header>
|
||||||
|
<div class="chart-box sm">
|
||||||
|
<canvas id="chartHist" aria-label="Гистограмма индекса"></canvas>
|
||||||
|
</div>
|
||||||
|
</article>
|
||||||
|
<article class="panel">
|
||||||
|
<header class="panel-h">
|
||||||
|
<h2>Размер полей</h2>
|
||||||
|
<p>Количество полей по площади, га</p>
|
||||||
|
</header>
|
||||||
|
<div class="chart-box sm">
|
||||||
|
<canvas id="chartArea" aria-label="Размер полей"></canvas>
|
||||||
|
</div>
|
||||||
|
</article>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="grid-2">
|
||||||
|
<article class="panel accent-good">
|
||||||
|
<header class="panel-h">
|
||||||
|
<h2>Звёзды портфеля</h2>
|
||||||
|
<p>Высокая урожайность + стабильность — эталонные поля</p>
|
||||||
|
</header>
|
||||||
|
<div class="table-wrap compact">
|
||||||
|
<table id="tblStars">
|
||||||
|
<thead><tr><th>Поле</th><th>Дивизион</th><th>Предприятие</th><th>га</th><th>Индекс</th><th>std</th></tr></thead>
|
||||||
|
<tbody></tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</article>
|
||||||
|
<article class="panel accent-risk">
|
||||||
|
<header class="panel-h">
|
||||||
|
<h2>Зона риска</h2>
|
||||||
|
<p>Низкая урожайность + нестабильность — приоритет диагностики</p>
|
||||||
|
</header>
|
||||||
|
<div class="table-wrap compact">
|
||||||
|
<table id="tblRisks">
|
||||||
|
<thead><tr><th>Поле</th><th>Дивизион</th><th>Предприятие</th><th>га</th><th>Индекс</th><th>std</th></tr></thead>
|
||||||
|
<tbody></tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</article>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="panel">
|
||||||
|
<header class="panel-h">
|
||||||
|
<h2>Подразделения с высокой долей риска</h2>
|
||||||
|
<p>ПО / отделения: где концентрация «малоурожайных + нестабильных» максимальна</p>
|
||||||
|
</header>
|
||||||
|
<div class="chart-box xl">
|
||||||
|
<canvas id="chartUnitsRisk" aria-label="Риск по подразделениям"></canvas>
|
||||||
|
</div>
|
||||||
|
<div class="table-wrap">
|
||||||
|
<table id="tblUnits">
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th>Дивизион</th><th>Подразделение</th><th>Поля</th><th>Площадь</th>
|
||||||
|
<th>Риск-поля</th><th>Доля риска %</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody></tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="panel">
|
||||||
|
<header class="panel-h">
|
||||||
|
<h2>Предприятия по индексу урожайности</h2>
|
||||||
|
<p>Топ и низ рейтинга (минимум 10 полей с классификацией)</p>
|
||||||
|
</header>
|
||||||
|
<div class="grid-2">
|
||||||
|
<div class="chart-box xl">
|
||||||
|
<canvas id="chartEntTop" aria-label="Топ предприятий"></canvas>
|
||||||
|
</div>
|
||||||
|
<div class="chart-box xl">
|
||||||
|
<canvas id="chartEntBottom" aria-label="Низ рейтинга предприятий"></canvas>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="panel muted">
|
||||||
|
<header class="panel-h">
|
||||||
|
<h2>Покрытие данных по годам</h2>
|
||||||
|
<p>Сколько поле-лет имеют культуру и факт урожайности</p>
|
||||||
|
</header>
|
||||||
|
<div class="chart-box sm">
|
||||||
|
<canvas id="chartCoverage" aria-label="Покрытие данных"></canvas>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
</main>
|
||||||
|
|
||||||
|
<footer class="foot">
|
||||||
|
<p>Перегенерация JSON: <code>npm run dashboard:data</code> · синхрон кластеров: <code>npm run dashboard:clusters</code></p>
|
||||||
|
<p id="footMeta"></p>
|
||||||
|
</footer>
|
||||||
|
|
||||||
|
<script src="data/dashboard-data.js"></script>
|
||||||
|
<script src="app.js"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,77 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="ru">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8" />
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||||
|
<title>Влияние предшественника — заглушка</title>
|
||||||
|
<link rel="preconnect" href="https://fonts.googleapis.com" />
|
||||||
|
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
|
||||||
|
<link href="https://fonts.googleapis.com/css2?family=Manrope:wght@400;500;600;700;800&family=Fraunces:opsz,wght@9..144,500;9..144,700&display=swap" rel="stylesheet" />
|
||||||
|
<link rel="stylesheet" href="styles.css" />
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div class="bg-orb bg-orb-a" aria-hidden="true"></div>
|
||||||
|
<div class="bg-orb bg-orb-b" aria-hidden="true"></div>
|
||||||
|
|
||||||
|
<nav class="site-nav" aria-label="Разделы анализа">
|
||||||
|
<a href="index.html">Портфель полей</a>
|
||||||
|
<a href="dates.html">Даты сева и уборки</a>
|
||||||
|
<a class="active" href="predecessor.html">Предшественник</a>
|
||||||
|
<a href="fertilizers.html">Удобрения</a>
|
||||||
|
<a href="fertilizer-quality.html">Качество удобрений</a>
|
||||||
|
</nav>
|
||||||
|
|
||||||
|
<header class="page-head">
|
||||||
|
<p class="eyebrow">Факторный анализ · скоро</p>
|
||||||
|
<h1>Влияние предшественника на урожайность</h1>
|
||||||
|
<p>
|
||||||
|
Черновик будущего дашборда: как культура прошлого года и пауза в севообороте
|
||||||
|
связаны с урожайностью текущей культуры на том же поле.
|
||||||
|
</p>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<main>
|
||||||
|
<section class="stub-card">
|
||||||
|
<h2>Что покажем</h2>
|
||||||
|
<ul>
|
||||||
|
<li><strong>Матрица предшественник → текущая культура</strong>: медиана ц/га и число поле-лет (без смешивания целевых культур на одном графике).</li>
|
||||||
|
<li><strong>Разрез по дивизионам / подразделениям</strong>: где связка «предшественник–культура» даёт прибавку или просадку относительно нормы дивизиона.</li>
|
||||||
|
<li><strong>Повтор культуры</strong>: доля полей с monoculture 2+ лет подряд и дельта урожайности vs лучший предшественник.</li>
|
||||||
|
<li><strong>Срок уборки предшественника</strong>: поздняя уборка свёклы/кукурузы и сдвиг сева озимых — влияние на урожай следующего года.</li>
|
||||||
|
<li><strong>Топ/антитоп пар</strong>: например, пшеница по пару / по подсолнечнику / по сое, с доверительным интервалом медианы.</li>
|
||||||
|
</ul>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="stub-grid">
|
||||||
|
<article class="stub-card">
|
||||||
|
<h2>Данные</h2>
|
||||||
|
<ul>
|
||||||
|
<li>Цепочка <code>history_items</code> по полю: культура<sub>t−1</sub> → культура<sub>t</sub>.</li>
|
||||||
|
<li>Фильтры: дивизион, подразделение, год t, целевая культура, предшественник.</li>
|
||||||
|
<li>Исключения: пар, залежь, АМП — отдельной группой «непродуктивный предшественник».</li>
|
||||||
|
</ul>
|
||||||
|
</article>
|
||||||
|
<article class="stub-card">
|
||||||
|
<h2>Визуализации</h2>
|
||||||
|
<ul>
|
||||||
|
<li>Heatmap предшественник × целевая культура (ц/га).</li>
|
||||||
|
<li>Slope / dumbbell: урожай после лучшего vs худшего предшественника.</li>
|
||||||
|
<li>Таблица поле-лет выборки с парой культур и урожайностью.</li>
|
||||||
|
</ul>
|
||||||
|
</article>
|
||||||
|
<article class="stub-card">
|
||||||
|
<h2>Бизнес-вопросы</h2>
|
||||||
|
<ul>
|
||||||
|
<li>Какие предшественники закреплять в севообороте дивизиона?</li>
|
||||||
|
<li>Где повтор пшеницы / подсолнечника уже «съедает» урожай?</li>
|
||||||
|
<li>Стоит ли менять структуру посевов ради лучшего фона под флагман?</li>
|
||||||
|
</ul>
|
||||||
|
</article>
|
||||||
|
</section>
|
||||||
|
</main>
|
||||||
|
|
||||||
|
<footer class="foot">
|
||||||
|
<p>Страница-заглушка. Реализация — после согласования правил восстановления предшественника из истории поля.</p>
|
||||||
|
</footer>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,751 @@
|
|||||||
|
:root {
|
||||||
|
--soil: #2c2416;
|
||||||
|
--ink: #1a2218;
|
||||||
|
--muted: #5c6b5a;
|
||||||
|
--line: rgba(44, 36, 22, 0.12);
|
||||||
|
--paper: #f3efe4;
|
||||||
|
--panel: rgba(255, 252, 245, 0.92);
|
||||||
|
--leaf: #2f6b3a;
|
||||||
|
--leaf-deep: #1e4d2b;
|
||||||
|
--wheat: #b8892d;
|
||||||
|
--wheat-soft: #e6c87a;
|
||||||
|
--sage: #7a9a78;
|
||||||
|
--risk: #a33b2a;
|
||||||
|
--good: #2f6b3a;
|
||||||
|
--mid: #8a7340;
|
||||||
|
--shadow: 0 18px 50px rgba(30, 40, 20, 0.08);
|
||||||
|
--radius: 18px;
|
||||||
|
--font: "Manrope", system-ui, sans-serif;
|
||||||
|
--display: "Fraunces", Georgia, serif;
|
||||||
|
--page: 1200px;
|
||||||
|
}
|
||||||
|
|
||||||
|
*, *::before, *::after { box-sizing: border-box; }
|
||||||
|
|
||||||
|
html {
|
||||||
|
scroll-behavior: smooth;
|
||||||
|
overflow-x: hidden;
|
||||||
|
max-width: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
body {
|
||||||
|
margin: 0;
|
||||||
|
font-family: var(--font);
|
||||||
|
color: var(--ink);
|
||||||
|
background:
|
||||||
|
radial-gradient(900px 480px at 10% -10%, rgba(184, 137, 45, 0.16), transparent 55%),
|
||||||
|
radial-gradient(700px 420px at 100% 0%, rgba(47, 107, 58, 0.12), transparent 50%),
|
||||||
|
linear-gradient(180deg, #ebe4d4 0%, var(--paper) 28%, #e7efdf 100%);
|
||||||
|
min-height: 100vh;
|
||||||
|
max-width: 100%;
|
||||||
|
overflow-x: hidden;
|
||||||
|
line-height: 1.45;
|
||||||
|
}
|
||||||
|
|
||||||
|
.bg-orb {
|
||||||
|
position: fixed;
|
||||||
|
width: 320px;
|
||||||
|
height: 320px;
|
||||||
|
border-radius: 50%;
|
||||||
|
filter: blur(60px);
|
||||||
|
opacity: 0.28;
|
||||||
|
pointer-events: none;
|
||||||
|
z-index: 0;
|
||||||
|
}
|
||||||
|
.bg-orb-a { top: 18%; left: -140px; background: #c5dbb8; }
|
||||||
|
.bg-orb-b { bottom: 8%; right: -160px; background: #e8d5a3; }
|
||||||
|
|
||||||
|
.site-nav,
|
||||||
|
.hero, .filters, main, .foot, .page-head {
|
||||||
|
position: relative;
|
||||||
|
z-index: 1;
|
||||||
|
width: min(100%, var(--page));
|
||||||
|
margin-left: auto;
|
||||||
|
margin-right: auto;
|
||||||
|
padding-left: 20px;
|
||||||
|
padding-right: 20px;
|
||||||
|
max-width: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Фильтры выше main/KPI, иначе dropdown уходит под плашки */
|
||||||
|
.filters {
|
||||||
|
z-index: 40;
|
||||||
|
}
|
||||||
|
|
||||||
|
.site-nav {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 8px;
|
||||||
|
padding-top: 16px;
|
||||||
|
padding-bottom: 4px;
|
||||||
|
}
|
||||||
|
.site-nav a {
|
||||||
|
text-decoration: none;
|
||||||
|
color: var(--leaf-deep);
|
||||||
|
font-size: 0.84rem;
|
||||||
|
font-weight: 600;
|
||||||
|
padding: 8px 12px;
|
||||||
|
border-radius: 999px;
|
||||||
|
border: 1px solid transparent;
|
||||||
|
background: rgba(255, 252, 245, 0.55);
|
||||||
|
}
|
||||||
|
.site-nav a:hover { border-color: var(--line); background: #fffcf5; }
|
||||||
|
.site-nav a.active {
|
||||||
|
background: var(--leaf-deep);
|
||||||
|
color: #f7f3e8;
|
||||||
|
border-color: var(--leaf-deep);
|
||||||
|
}
|
||||||
|
|
||||||
|
.page-head {
|
||||||
|
padding-top: 18px;
|
||||||
|
padding-bottom: 8px;
|
||||||
|
}
|
||||||
|
.page-head h1 {
|
||||||
|
font-family: var(--display);
|
||||||
|
font-size: clamp(1.6rem, 3.5vw, 2.4rem);
|
||||||
|
color: var(--leaf-deep);
|
||||||
|
margin: 6px 0 10px;
|
||||||
|
letter-spacing: -0.02em;
|
||||||
|
}
|
||||||
|
.page-head p {
|
||||||
|
margin: 0;
|
||||||
|
color: var(--muted);
|
||||||
|
max-width: 70ch;
|
||||||
|
}
|
||||||
|
|
||||||
|
.hero {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: minmax(0, 1.15fr) minmax(0, 1fr);
|
||||||
|
gap: 20px;
|
||||||
|
padding-top: 36px;
|
||||||
|
padding-bottom: 16px;
|
||||||
|
}
|
||||||
|
.hero-inner,
|
||||||
|
.hero-panel,
|
||||||
|
.panel,
|
||||||
|
.grid-2 > *,
|
||||||
|
.insights > *,
|
||||||
|
.filters > * {
|
||||||
|
min-width: 0;
|
||||||
|
max-width: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
.hero-inner h1 {
|
||||||
|
font-family: var(--display);
|
||||||
|
font-weight: 700;
|
||||||
|
font-size: clamp(2rem, 4.5vw, 3.2rem);
|
||||||
|
line-height: 1.05;
|
||||||
|
margin: 8px 0 14px;
|
||||||
|
color: var(--leaf-deep);
|
||||||
|
letter-spacing: -0.02em;
|
||||||
|
overflow-wrap: anywhere;
|
||||||
|
}
|
||||||
|
.hero-inner h1 span {
|
||||||
|
color: var(--wheat);
|
||||||
|
font-weight: 500;
|
||||||
|
}
|
||||||
|
.eyebrow {
|
||||||
|
text-transform: uppercase;
|
||||||
|
letter-spacing: 0.14em;
|
||||||
|
font-size: 0.72rem;
|
||||||
|
font-weight: 700;
|
||||||
|
color: var(--leaf);
|
||||||
|
margin: 0;
|
||||||
|
}
|
||||||
|
.lede {
|
||||||
|
max-width: 52ch;
|
||||||
|
color: var(--muted);
|
||||||
|
font-size: 0.98rem;
|
||||||
|
margin: 0 0 14px;
|
||||||
|
}
|
||||||
|
.lede code, .foot code {
|
||||||
|
font-size: 0.86em;
|
||||||
|
background: rgba(47, 107, 58, 0.08);
|
||||||
|
padding: 0.1em 0.4em;
|
||||||
|
border-radius: 6px;
|
||||||
|
}
|
||||||
|
.hero-meta {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 8px;
|
||||||
|
}
|
||||||
|
.chip {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 6px;
|
||||||
|
padding: 7px 11px;
|
||||||
|
border-radius: 999px;
|
||||||
|
background: rgba(255, 252, 245, 0.75);
|
||||||
|
border: 1px solid var(--line);
|
||||||
|
font-size: 0.82rem;
|
||||||
|
color: var(--muted);
|
||||||
|
max-width: 100%;
|
||||||
|
}
|
||||||
|
.hero-panel {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||||
|
gap: 10px;
|
||||||
|
align-content: start;
|
||||||
|
}
|
||||||
|
.kpi {
|
||||||
|
background: var(--panel);
|
||||||
|
border: 1px solid var(--line);
|
||||||
|
border-radius: var(--radius);
|
||||||
|
padding: 14px 14px;
|
||||||
|
box-shadow: var(--shadow);
|
||||||
|
animation: rise 0.55s ease both;
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
.kpi:nth-child(2) { animation-delay: 0.04s; }
|
||||||
|
.kpi:nth-child(3) { animation-delay: 0.08s; }
|
||||||
|
.kpi:nth-child(4) { animation-delay: 0.12s; }
|
||||||
|
.kpi:nth-child(5) { animation-delay: 0.16s; }
|
||||||
|
.kpi:nth-child(6) { animation-delay: 0.2s; }
|
||||||
|
.kpi .label { font-size: 0.74rem; color: var(--muted); font-weight: 600; }
|
||||||
|
.kpi .value {
|
||||||
|
font-family: var(--display);
|
||||||
|
font-size: clamp(1.35rem, 2.4vw, 1.75rem);
|
||||||
|
font-weight: 700;
|
||||||
|
color: var(--leaf-deep);
|
||||||
|
margin-top: 4px;
|
||||||
|
letter-spacing: -0.02em;
|
||||||
|
}
|
||||||
|
.kpi .sub { font-size: 0.74rem; color: var(--sage); margin-top: 2px; }
|
||||||
|
.kpi.risk .value { color: var(--risk); }
|
||||||
|
.kpi.good .value { color: var(--good); }
|
||||||
|
.kpi.gold .value { color: var(--wheat); }
|
||||||
|
|
||||||
|
@keyframes rise {
|
||||||
|
from { opacity: 0; transform: translateY(10px); }
|
||||||
|
to { opacity: 1; transform: none; }
|
||||||
|
}
|
||||||
|
|
||||||
|
.filters {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 12px;
|
||||||
|
align-items: end;
|
||||||
|
margin-bottom: 8px;
|
||||||
|
}
|
||||||
|
.filters label {
|
||||||
|
display: grid;
|
||||||
|
gap: 6px;
|
||||||
|
font-size: 0.72rem;
|
||||||
|
font-weight: 700;
|
||||||
|
color: var(--muted);
|
||||||
|
text-transform: uppercase;
|
||||||
|
letter-spacing: 0.06em;
|
||||||
|
flex: 1 1 200px;
|
||||||
|
max-width: 320px;
|
||||||
|
}
|
||||||
|
.filters select {
|
||||||
|
width: 100%;
|
||||||
|
min-width: 0;
|
||||||
|
padding: 10px 12px;
|
||||||
|
border-radius: 12px;
|
||||||
|
border: 1px solid var(--line);
|
||||||
|
background: #fffcf5;
|
||||||
|
font-family: var(--font);
|
||||||
|
font-size: 0.92rem;
|
||||||
|
color: var(--ink);
|
||||||
|
}
|
||||||
|
.ghost {
|
||||||
|
border: 1px solid var(--line);
|
||||||
|
background: transparent;
|
||||||
|
border-radius: 12px;
|
||||||
|
padding: 10px 14px;
|
||||||
|
font-family: var(--font);
|
||||||
|
font-weight: 600;
|
||||||
|
cursor: pointer;
|
||||||
|
color: var(--leaf-deep);
|
||||||
|
}
|
||||||
|
.ghost:hover { background: rgba(47, 107, 58, 0.08); }
|
||||||
|
.filter-hint {
|
||||||
|
color: var(--muted);
|
||||||
|
font-size: 0.85rem;
|
||||||
|
flex: 1 1 160px;
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
main {
|
||||||
|
padding-top: 8px;
|
||||||
|
padding-bottom: 48px;
|
||||||
|
display: grid;
|
||||||
|
gap: 16px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.insights {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: repeat(auto-fit, minmax(min(100%, 220px), 1fr));
|
||||||
|
gap: 10px;
|
||||||
|
}
|
||||||
|
.insight {
|
||||||
|
background: linear-gradient(145deg, rgba(47, 107, 58, 0.1), rgba(184, 137, 45, 0.12));
|
||||||
|
border: 1px solid var(--line);
|
||||||
|
border-radius: var(--radius);
|
||||||
|
padding: 14px 15px;
|
||||||
|
overflow-wrap: anywhere;
|
||||||
|
}
|
||||||
|
.insight h3 {
|
||||||
|
margin: 0 0 6px;
|
||||||
|
font-size: 0.92rem;
|
||||||
|
color: var(--leaf-deep);
|
||||||
|
}
|
||||||
|
.insight p { margin: 0; color: var(--muted); font-size: 0.86rem; }
|
||||||
|
|
||||||
|
.panel {
|
||||||
|
background: var(--panel);
|
||||||
|
border: 1px solid var(--line);
|
||||||
|
border-radius: calc(var(--radius) + 2px);
|
||||||
|
padding: 18px 16px 14px;
|
||||||
|
box-shadow: var(--shadow);
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
.panel.muted { background: rgba(255, 252, 245, 0.7); }
|
||||||
|
.panel.accent-good { border-color: rgba(47, 107, 58, 0.28); }
|
||||||
|
.panel.accent-risk { border-color: rgba(163, 59, 42, 0.28); }
|
||||||
|
.panel-h { margin-bottom: 12px; }
|
||||||
|
.panel-h h2 {
|
||||||
|
margin: 0;
|
||||||
|
font-family: var(--display);
|
||||||
|
font-size: clamp(1.15rem, 2.2vw, 1.35rem);
|
||||||
|
color: var(--leaf-deep);
|
||||||
|
letter-spacing: -0.01em;
|
||||||
|
}
|
||||||
|
.panel-h p { margin: 4px 0 0; color: var(--muted); font-size: 0.88rem; }
|
||||||
|
.subh {
|
||||||
|
margin: 14px 0 8px;
|
||||||
|
font-size: 0.92rem;
|
||||||
|
color: var(--soil);
|
||||||
|
}
|
||||||
|
|
||||||
|
.grid-2 {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||||
|
gap: 16px;
|
||||||
|
}
|
||||||
|
.grid-2.tight { gap: 10px; }
|
||||||
|
|
||||||
|
/* Chart.js must live in a sized box — otherwise canvases explode */
|
||||||
|
.chart-box {
|
||||||
|
position: relative;
|
||||||
|
width: 100%;
|
||||||
|
max-width: 100%;
|
||||||
|
height: 280px;
|
||||||
|
margin: 0;
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
.chart-box.sm { height: 200px; }
|
||||||
|
.chart-box.md { height: 260px; }
|
||||||
|
.chart-box.lg { height: 340px; }
|
||||||
|
.chart-box.xl { height: 420px; }
|
||||||
|
.chart-box canvas {
|
||||||
|
display: block;
|
||||||
|
width: 100% !important;
|
||||||
|
height: 100% !important;
|
||||||
|
max-width: 100% !important;
|
||||||
|
max-height: 100% !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
.matrix {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: minmax(72px, 0.7fr) repeat(3, minmax(0, 1fr));
|
||||||
|
gap: 6px;
|
||||||
|
margin-bottom: 12px;
|
||||||
|
width: 100%;
|
||||||
|
}
|
||||||
|
.matrix .corner,
|
||||||
|
.matrix .colh,
|
||||||
|
.matrix .rowh {
|
||||||
|
font-size: 0.68rem;
|
||||||
|
font-weight: 700;
|
||||||
|
color: var(--muted);
|
||||||
|
text-transform: uppercase;
|
||||||
|
letter-spacing: 0.03em;
|
||||||
|
display: flex;
|
||||||
|
align-items: end;
|
||||||
|
justify-content: center;
|
||||||
|
padding-bottom: 2px;
|
||||||
|
text-align: center;
|
||||||
|
line-height: 1.2;
|
||||||
|
overflow-wrap: anywhere;
|
||||||
|
}
|
||||||
|
.matrix .rowh {
|
||||||
|
align-items: center;
|
||||||
|
justify-content: flex-end;
|
||||||
|
text-align: right;
|
||||||
|
padding-right: 4px;
|
||||||
|
}
|
||||||
|
.mcell {
|
||||||
|
border-radius: 12px;
|
||||||
|
padding: 10px 8px;
|
||||||
|
min-height: 72px;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 4px;
|
||||||
|
overflow: hidden;
|
||||||
|
transition: transform 0.2s ease, box-shadow 0.2s ease;
|
||||||
|
}
|
||||||
|
.mcell:hover { transform: translateY(-1px); box-shadow: var(--shadow); }
|
||||||
|
.mcell .m-title {
|
||||||
|
font-size: 0.68rem;
|
||||||
|
font-weight: 700;
|
||||||
|
opacity: 0.85;
|
||||||
|
line-height: 1.25;
|
||||||
|
overflow-wrap: anywhere;
|
||||||
|
}
|
||||||
|
.mcell .m-val {
|
||||||
|
font-family: var(--display);
|
||||||
|
font-size: clamp(1.05rem, 2vw, 1.25rem);
|
||||||
|
font-weight: 700;
|
||||||
|
}
|
||||||
|
.mcell .m-sub {
|
||||||
|
font-size: 0.68rem;
|
||||||
|
opacity: 0.8;
|
||||||
|
line-height: 1.25;
|
||||||
|
overflow-wrap: anywhere;
|
||||||
|
}
|
||||||
|
.mcell.high-stable { background: rgba(47, 107, 58, 0.22); }
|
||||||
|
.mcell.high-unstable { background: rgba(47, 107, 58, 0.12); }
|
||||||
|
.mcell.high-na { background: rgba(47, 107, 58, 0.08); }
|
||||||
|
.mcell.mid-stable { background: rgba(184, 137, 45, 0.18); }
|
||||||
|
.mcell.mid-unstable { background: rgba(184, 137, 45, 0.12); }
|
||||||
|
.mcell.mid-na { background: rgba(184, 137, 45, 0.08); }
|
||||||
|
.mcell.low-stable { background: rgba(163, 59, 42, 0.12); }
|
||||||
|
.mcell.low-unstable { background: rgba(163, 59, 42, 0.22); }
|
||||||
|
.mcell.low-na { background: rgba(163, 59, 42, 0.08); }
|
||||||
|
|
||||||
|
.table-wrap {
|
||||||
|
overflow: auto;
|
||||||
|
margin-top: 10px;
|
||||||
|
border-radius: 12px;
|
||||||
|
border: 1px solid var(--line);
|
||||||
|
max-width: 100%;
|
||||||
|
-webkit-overflow-scrolling: touch;
|
||||||
|
}
|
||||||
|
.table-wrap.compact { max-height: 320px; }
|
||||||
|
table {
|
||||||
|
width: 100%;
|
||||||
|
border-collapse: collapse;
|
||||||
|
font-size: 0.82rem;
|
||||||
|
min-width: 520px;
|
||||||
|
}
|
||||||
|
th, td {
|
||||||
|
padding: 8px 9px;
|
||||||
|
text-align: left;
|
||||||
|
border-bottom: 1px solid var(--line);
|
||||||
|
white-space: nowrap;
|
||||||
|
max-width: 220px;
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
}
|
||||||
|
th {
|
||||||
|
position: sticky;
|
||||||
|
top: 0;
|
||||||
|
background: #f7f3e8;
|
||||||
|
font-size: 0.68rem;
|
||||||
|
text-transform: uppercase;
|
||||||
|
letter-spacing: 0.04em;
|
||||||
|
color: var(--muted);
|
||||||
|
z-index: 1;
|
||||||
|
}
|
||||||
|
tbody tr:hover { background: rgba(47, 107, 58, 0.05); }
|
||||||
|
td.num { font-variant-numeric: tabular-nums; text-align: right; }
|
||||||
|
.badge {
|
||||||
|
display: inline-block;
|
||||||
|
padding: 2px 8px;
|
||||||
|
border-radius: 999px;
|
||||||
|
font-size: 0.72rem;
|
||||||
|
font-weight: 700;
|
||||||
|
}
|
||||||
|
.badge.good { background: rgba(47, 107, 58, 0.15); color: var(--good); }
|
||||||
|
.badge.risk { background: rgba(163, 59, 42, 0.15); color: var(--risk); }
|
||||||
|
|
||||||
|
.foot {
|
||||||
|
padding-bottom: 36px;
|
||||||
|
color: var(--muted);
|
||||||
|
font-size: 0.82rem;
|
||||||
|
overflow-wrap: anywhere;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (max-width: 900px) {
|
||||||
|
.hero,
|
||||||
|
.grid-2 { grid-template-columns: minmax(0, 1fr); }
|
||||||
|
.filters label { max-width: none; flex-basis: 100%; }
|
||||||
|
.chart-box { height: 240px; }
|
||||||
|
.chart-box.sm { height: 180px; }
|
||||||
|
.chart-box.md { height: 220px; }
|
||||||
|
.chart-box.lg { height: 280px; }
|
||||||
|
.chart-box.xl { height: 320px; }
|
||||||
|
.matrix {
|
||||||
|
grid-template-columns: minmax(56px, 0.55fr) repeat(3, minmax(0, 1fr));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Multi-select filters */
|
||||||
|
.filters.dense {
|
||||||
|
align-items: start;
|
||||||
|
gap: 10px;
|
||||||
|
}
|
||||||
|
.ms {
|
||||||
|
position: relative;
|
||||||
|
flex: 1 1 180px;
|
||||||
|
max-width: 240px;
|
||||||
|
min-width: 0;
|
||||||
|
z-index: 1;
|
||||||
|
}
|
||||||
|
.ms[open] {
|
||||||
|
z-index: 50;
|
||||||
|
}
|
||||||
|
.ms > summary {
|
||||||
|
list-style: none;
|
||||||
|
cursor: pointer;
|
||||||
|
padding: 10px 12px;
|
||||||
|
border-radius: 12px;
|
||||||
|
border: 1px solid var(--line);
|
||||||
|
background: #fffcf5;
|
||||||
|
font-size: 0.88rem;
|
||||||
|
font-weight: 600;
|
||||||
|
color: var(--ink);
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 8px;
|
||||||
|
align-items: center;
|
||||||
|
}
|
||||||
|
.ms > summary::-webkit-details-marker { display: none; }
|
||||||
|
.ms > summary::after { content: "▾"; color: var(--muted); font-size: 0.75rem; }
|
||||||
|
.ms[open] > summary { border-color: rgba(47, 107, 58, 0.35); }
|
||||||
|
.ms-panel {
|
||||||
|
position: absolute;
|
||||||
|
z-index: 60;
|
||||||
|
top: calc(100% + 4px);
|
||||||
|
left: 0;
|
||||||
|
right: 0;
|
||||||
|
max-height: 260px;
|
||||||
|
overflow: auto;
|
||||||
|
background: #fffcf5;
|
||||||
|
border: 1px solid var(--line);
|
||||||
|
border-radius: 12px;
|
||||||
|
box-shadow: var(--shadow);
|
||||||
|
padding: 8px;
|
||||||
|
}
|
||||||
|
.ms-panel label {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 8px;
|
||||||
|
padding: 6px 6px;
|
||||||
|
font-size: 0.82rem;
|
||||||
|
text-transform: none;
|
||||||
|
letter-spacing: 0;
|
||||||
|
font-weight: 500;
|
||||||
|
color: var(--ink);
|
||||||
|
max-width: none;
|
||||||
|
}
|
||||||
|
.ms-panel label:hover { background: rgba(47, 107, 58, 0.06); border-radius: 8px; }
|
||||||
|
.ms-actions {
|
||||||
|
display: flex;
|
||||||
|
gap: 8px;
|
||||||
|
padding: 4px 6px 8px;
|
||||||
|
border-bottom: 1px solid var(--line);
|
||||||
|
margin-bottom: 4px;
|
||||||
|
}
|
||||||
|
.ms-actions button {
|
||||||
|
border: 0;
|
||||||
|
background: rgba(47, 107, 58, 0.1);
|
||||||
|
color: var(--leaf-deep);
|
||||||
|
border-radius: 8px;
|
||||||
|
padding: 4px 8px;
|
||||||
|
font-size: 0.72rem;
|
||||||
|
font-weight: 700;
|
||||||
|
cursor: pointer;
|
||||||
|
font-family: var(--font);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Heatmap */
|
||||||
|
.heat-wrap {
|
||||||
|
overflow: auto;
|
||||||
|
max-width: 100%;
|
||||||
|
border: 1px solid var(--line);
|
||||||
|
border-radius: 14px;
|
||||||
|
background: #fffcf5;
|
||||||
|
}
|
||||||
|
.heat-grid {
|
||||||
|
display: grid;
|
||||||
|
gap: 2px;
|
||||||
|
padding: 12px;
|
||||||
|
width: max-content;
|
||||||
|
min-width: 100%;
|
||||||
|
}
|
||||||
|
.heat-corner {
|
||||||
|
font-size: 0.68rem;
|
||||||
|
color: var(--muted);
|
||||||
|
font-weight: 700;
|
||||||
|
align-self: end;
|
||||||
|
padding-bottom: 4px;
|
||||||
|
}
|
||||||
|
.heat-x, .heat-y {
|
||||||
|
font-size: 0.68rem;
|
||||||
|
color: var(--muted);
|
||||||
|
font-weight: 700;
|
||||||
|
text-align: center;
|
||||||
|
line-height: 1.1;
|
||||||
|
}
|
||||||
|
.heat-y {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: flex-end;
|
||||||
|
padding-right: 6px;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
.heat-cell {
|
||||||
|
width: 34px;
|
||||||
|
height: 34px;
|
||||||
|
border-radius: 7px;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
font-size: 0.62rem;
|
||||||
|
font-weight: 700;
|
||||||
|
color: rgba(26, 34, 24, 0.85);
|
||||||
|
cursor: default;
|
||||||
|
}
|
||||||
|
.heat-cell.empty { background: rgba(44, 36, 22, 0.04); color: transparent; }
|
||||||
|
.heat-legend {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 10px;
|
||||||
|
margin-top: 10px;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
font-size: 0.8rem;
|
||||||
|
color: var(--muted);
|
||||||
|
}
|
||||||
|
.heat-legend .bar {
|
||||||
|
width: 160px;
|
||||||
|
height: 10px;
|
||||||
|
border-radius: 999px;
|
||||||
|
background: linear-gradient(90deg, #f0e4c4, #c4a35a, #2f6b3a);
|
||||||
|
}
|
||||||
|
.heat-meta {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: repeat(auto-fit, minmax(140px, 1fr));
|
||||||
|
gap: 10px;
|
||||||
|
margin-bottom: 12px;
|
||||||
|
}
|
||||||
|
.crop-block { margin-bottom: 18px; }
|
||||||
|
.crop-block h3 {
|
||||||
|
margin: 0 0 8px;
|
||||||
|
font-family: var(--display);
|
||||||
|
color: var(--leaf-deep);
|
||||||
|
font-size: 1.15rem;
|
||||||
|
}
|
||||||
|
.warn {
|
||||||
|
padding: 12px 14px;
|
||||||
|
border-radius: 12px;
|
||||||
|
background: rgba(184, 137, 45, 0.12);
|
||||||
|
border: 1px solid rgba(184, 137, 45, 0.28);
|
||||||
|
color: var(--soil);
|
||||||
|
font-size: 0.9rem;
|
||||||
|
}
|
||||||
|
.chk-inline {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 6px;
|
||||||
|
font-size: 0.84rem;
|
||||||
|
color: var(--muted);
|
||||||
|
font-weight: 600;
|
||||||
|
padding: 6px 4px;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
.chk-inline input { accent-color: var(--leaf); }
|
||||||
|
.notes-list {
|
||||||
|
margin: 0;
|
||||||
|
padding-left: 1.15rem;
|
||||||
|
color: var(--muted);
|
||||||
|
font-size: 0.9rem;
|
||||||
|
}
|
||||||
|
.notes-list li { margin: 6px 0; }
|
||||||
|
|
||||||
|
.verdict { margin-bottom: 4px; }
|
||||||
|
.verdict-card {
|
||||||
|
background: var(--panel);
|
||||||
|
border: 1px solid var(--line);
|
||||||
|
border-radius: 18px;
|
||||||
|
padding: 18px 20px;
|
||||||
|
box-shadow: var(--shadow);
|
||||||
|
}
|
||||||
|
.verdict-card.good { border-color: rgba(47, 107, 58, 0.35); }
|
||||||
|
.verdict-card.gold { border-color: rgba(184, 137, 45, 0.4); }
|
||||||
|
.verdict-card.risk { border-color: rgba(163, 59, 42, 0.35); }
|
||||||
|
.verdict-label {
|
||||||
|
font-size: 0.75rem;
|
||||||
|
font-weight: 700;
|
||||||
|
letter-spacing: 0.04em;
|
||||||
|
text-transform: uppercase;
|
||||||
|
color: var(--muted);
|
||||||
|
}
|
||||||
|
.verdict-text {
|
||||||
|
margin-top: 6px;
|
||||||
|
font-family: var(--display);
|
||||||
|
font-size: 1.25rem;
|
||||||
|
color: var(--leaf-deep);
|
||||||
|
line-height: 1.35;
|
||||||
|
}
|
||||||
|
.verdict-card.risk .verdict-text { color: var(--risk); }
|
||||||
|
.verdict-card.gold .verdict-text { color: #8a5a12; }
|
||||||
|
.verdict-sub {
|
||||||
|
margin-top: 8px;
|
||||||
|
font-size: 0.86rem;
|
||||||
|
color: var(--muted);
|
||||||
|
}
|
||||||
|
.tag {
|
||||||
|
display: inline-block;
|
||||||
|
font-size: 0.72rem;
|
||||||
|
font-weight: 700;
|
||||||
|
padding: 2px 8px;
|
||||||
|
border-radius: 999px;
|
||||||
|
background: rgba(122, 154, 120, 0.18);
|
||||||
|
color: var(--leaf-deep);
|
||||||
|
}
|
||||||
|
.tag.hard { background: rgba(163, 59, 42, 0.14); color: var(--risk); }
|
||||||
|
.tag.warn { background: rgba(184, 137, 45, 0.18); color: #8a5a12; }
|
||||||
|
.tag.info { background: rgba(122, 154, 120, 0.16); color: var(--muted); }
|
||||||
|
.sub-cell {
|
||||||
|
font-size: 0.72rem;
|
||||||
|
color: var(--muted);
|
||||||
|
font-weight: 500;
|
||||||
|
}
|
||||||
|
.flags-cell {
|
||||||
|
font-size: 0.8rem;
|
||||||
|
color: var(--muted);
|
||||||
|
max-width: 280px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.stub-card {
|
||||||
|
background: var(--panel);
|
||||||
|
border: 1px solid var(--line);
|
||||||
|
border-radius: 18px;
|
||||||
|
padding: 22px 20px;
|
||||||
|
box-shadow: var(--shadow);
|
||||||
|
}
|
||||||
|
.stub-card h2 {
|
||||||
|
margin: 0 0 10px;
|
||||||
|
font-family: var(--display);
|
||||||
|
color: var(--leaf-deep);
|
||||||
|
}
|
||||||
|
.stub-card ul { margin: 8px 0 0; padding-left: 1.1rem; color: var(--muted); }
|
||||||
|
.stub-card li { margin: 6px 0; }
|
||||||
|
.stub-grid {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: repeat(auto-fit, minmax(min(100%, 260px), 1fr));
|
||||||
|
gap: 14px;
|
||||||
|
margin-top: 14px;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (max-width: 900px) {
|
||||||
|
.ms { max-width: none; flex-basis: 100%; }
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-reduced-motion: reduce) {
|
||||||
|
.kpi, .mcell { animation: none; transition: none; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,109 @@
|
|||||||
|
/**
|
||||||
|
* Копирует fields_clustered_all из fertilizer_project_test в ak_fields
|
||||||
|
* с нормализованными именами колонок. Связь с fields — по field_id / name.
|
||||||
|
*/
|
||||||
|
require('dotenv').config({ path: require('path').join(__dirname, '..', '.env') });
|
||||||
|
const { Client } = require('pg');
|
||||||
|
|
||||||
|
function clientFor(database) {
|
||||||
|
return new Client({
|
||||||
|
host: process.env.PGHOST,
|
||||||
|
port: Number(process.env.PGPORT || 5432),
|
||||||
|
database,
|
||||||
|
user: process.env.PGUSER,
|
||||||
|
password: process.env.PGPASSWORD,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async function main() {
|
||||||
|
const src = clientFor('fertilizer_project_test');
|
||||||
|
const dst = clientFor(process.env.PGDATABASE || 'ak_fields');
|
||||||
|
await src.connect();
|
||||||
|
await dst.connect();
|
||||||
|
|
||||||
|
console.log('Reading fields_clustered_all...');
|
||||||
|
const { rows } = await src.query(`
|
||||||
|
SELECT
|
||||||
|
"ID поля" AS field_id,
|
||||||
|
"Название поля" AS field_name,
|
||||||
|
"Дивизион" AS division,
|
||||||
|
"Площадь поля (га)" AS area_ha,
|
||||||
|
"Лет в обороте" AS years_in_rotation,
|
||||||
|
"Медиана урожайности (индекс)" AS yield_index_median,
|
||||||
|
"Разброс стабильности (std)" AS stability_std,
|
||||||
|
"Категория урожайности (Правила)" AS yield_category_rules,
|
||||||
|
"Категория урожайности (K-Means)" AS yield_category_kmeans,
|
||||||
|
"Категория стабильности" AS stability_category
|
||||||
|
FROM fields_clustered_all
|
||||||
|
`);
|
||||||
|
console.log(` rows: ${rows.length}`);
|
||||||
|
|
||||||
|
await dst.query(`
|
||||||
|
CREATE TABLE IF NOT EXISTS fields_clustered_all (
|
||||||
|
field_id bigint PRIMARY KEY,
|
||||||
|
field_name text,
|
||||||
|
division text,
|
||||||
|
area_ha double precision,
|
||||||
|
years_in_rotation integer,
|
||||||
|
yield_index_median double precision,
|
||||||
|
stability_std double precision,
|
||||||
|
yield_category_rules text,
|
||||||
|
yield_category_kmeans text,
|
||||||
|
stability_category text,
|
||||||
|
synced_at timestamptz DEFAULT now()
|
||||||
|
)
|
||||||
|
`);
|
||||||
|
|
||||||
|
await dst.query('TRUNCATE fields_clustered_all');
|
||||||
|
|
||||||
|
const batchSize = 500;
|
||||||
|
for (let i = 0; i < rows.length; i += batchSize) {
|
||||||
|
const batch = rows.slice(i, i + batchSize);
|
||||||
|
const values = [];
|
||||||
|
const params = [];
|
||||||
|
let p = 1;
|
||||||
|
for (const r of batch) {
|
||||||
|
values.push(
|
||||||
|
`($${p++},$${p++},$${p++},$${p++},$${p++},$${p++},$${p++},$${p++},$${p++},$${p++})`
|
||||||
|
);
|
||||||
|
params.push(
|
||||||
|
r.field_id,
|
||||||
|
r.field_name,
|
||||||
|
r.division,
|
||||||
|
r.area_ha,
|
||||||
|
r.years_in_rotation,
|
||||||
|
r.yield_index_median,
|
||||||
|
r.stability_std,
|
||||||
|
r.yield_category_rules,
|
||||||
|
r.yield_category_kmeans,
|
||||||
|
r.stability_category
|
||||||
|
);
|
||||||
|
}
|
||||||
|
await dst.query(
|
||||||
|
`INSERT INTO fields_clustered_all (
|
||||||
|
field_id, field_name, division, area_ha, years_in_rotation,
|
||||||
|
yield_index_median, stability_std, yield_category_rules,
|
||||||
|
yield_category_kmeans, stability_category
|
||||||
|
) VALUES ${values.join(',')}`,
|
||||||
|
params
|
||||||
|
);
|
||||||
|
process.stdout.write(` inserted ${Math.min(i + batchSize, rows.length)}/${rows.length}\r`);
|
||||||
|
}
|
||||||
|
console.log('\nDone. Verifying...');
|
||||||
|
const check = await dst.query(`
|
||||||
|
SELECT
|
||||||
|
COUNT(*) AS clustered,
|
||||||
|
COUNT(*) FILTER (WHERE EXISTS (SELECT 1 FROM fields f WHERE f.id = fields_clustered_all.field_id)) AS matched_by_id,
|
||||||
|
COUNT(*) FILTER (WHERE EXISTS (SELECT 1 FROM fields f WHERE f.name = fields_clustered_all.field_name)) AS matched_by_name
|
||||||
|
FROM fields_clustered_all
|
||||||
|
`);
|
||||||
|
console.table(check.rows);
|
||||||
|
|
||||||
|
await src.end();
|
||||||
|
await dst.end();
|
||||||
|
}
|
||||||
|
|
||||||
|
main().catch((e) => {
|
||||||
|
console.error(e);
|
||||||
|
process.exit(1);
|
||||||
|
});
|
||||||
File diff suppressed because it is too large
Load Diff
+3669
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,219 @@
|
|||||||
|
const axios = require('axios');
|
||||||
|
const fs = require('fs');
|
||||||
|
const path = require('path');
|
||||||
|
|
||||||
|
// --- КОНФИГУРАЦИЯ ---
|
||||||
|
const API_BASE_URL = 'https://operations.cropwise.com/api/v3';
|
||||||
|
const API_TOKEN = '7oA9B7_ZJ4gE1qw4cqzH'; // Замените на ваш токен
|
||||||
|
const SEASON_YEAR = 2025; // Укажите нужный год
|
||||||
|
|
||||||
|
// Создаем клиент с заголовком авторизации
|
||||||
|
const client = axios.create({
|
||||||
|
baseURL: API_BASE_URL,
|
||||||
|
headers: {
|
||||||
|
'X-User-Api-Token': API_TOKEN,
|
||||||
|
'Accept': 'application/json',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
// --- ВСПОМОГАТЕЛЬНЫЕ ФУНКЦИИ ---
|
||||||
|
|
||||||
|
// Функция для получения всех страниц ресурса
|
||||||
|
async function fetchAllPages(endpoint, queryParams = {}) {
|
||||||
|
let allData = [];
|
||||||
|
let fromId = 0;
|
||||||
|
const limit = 100; // Максимальный лимит
|
||||||
|
let hasMore = true;
|
||||||
|
|
||||||
|
console.log(`Fetching all pages for ${endpoint}...`);
|
||||||
|
|
||||||
|
while (hasMore) {
|
||||||
|
try {
|
||||||
|
const response = await client.get(endpoint, {
|
||||||
|
params: {
|
||||||
|
...queryParams,
|
||||||
|
limit: limit,
|
||||||
|
from_id: fromId,
|
||||||
|
sort_by: 'id_asc'
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const { data, meta } = response.data;
|
||||||
|
|
||||||
|
if (data && data.length > 0) {
|
||||||
|
allData = allData.concat(data);
|
||||||
|
console.log(` Fetched ${data.length} records. Total so far: ${allData.length}`);
|
||||||
|
// Обновляем from_id для следующей страницы
|
||||||
|
fromId = meta.response.last_record_id;
|
||||||
|
// Проверяем, есть ли еще записи
|
||||||
|
hasMore = data.length === limit && meta.response.obtained_records === limit;
|
||||||
|
} else {
|
||||||
|
hasMore = false;
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error(`Error fetching ${endpoint}:`, error.response?.data || error.message);
|
||||||
|
hasMore = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log(` Finished fetching. Total records: ${allData.length}`);
|
||||||
|
return allData;
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- ОСНОВНАЯ ФУНКЦИЯ ---
|
||||||
|
|
||||||
|
async function generateFieldsReport() {
|
||||||
|
console.log(`Starting report generation for season ${SEASON_YEAR}...`);
|
||||||
|
|
||||||
|
try {
|
||||||
|
// 1. Получить все поля (fields)
|
||||||
|
const fields = await fetchAllPages('/fields');
|
||||||
|
console.log('fields.length', fields.length);
|
||||||
|
if (fields.length === 0) {
|
||||||
|
console.log('No fields found.');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. Получить все группы полей (field_groups) для кэширования
|
||||||
|
const fieldGroups = await fetchAllPages('/field_groups');
|
||||||
|
console.log('fieldGroups.length', fieldGroups.length);
|
||||||
|
|
||||||
|
const fieldGroupsJsonPath = path.join(__dirname, 'field_groups.json');
|
||||||
|
fs.writeFileSync(fieldGroupsJsonPath, JSON.stringify(fieldGroups, null, 2), 'utf8');
|
||||||
|
console.log(`field_groups saved to ${fieldGroupsJsonPath}`);
|
||||||
|
|
||||||
|
// Создаем карту для быстрого доступа к группам по ID
|
||||||
|
const fieldGroupsMap = new Map();
|
||||||
|
fieldGroups.forEach(fg => fieldGroupsMap.set(fg.id, fg));
|
||||||
|
|
||||||
|
// 3. Получить все групповые папки (group_folders) для кэширования
|
||||||
|
const groupFolders = await fetchAllPages('/group_folders');
|
||||||
|
console.log('groupFolders.length', groupFolders.length);
|
||||||
|
const groupFoldersMap = new Map();
|
||||||
|
groupFolders.forEach(gf => groupFoldersMap.set(gf.id, gf));
|
||||||
|
|
||||||
|
// 4. Кэш для культур (crops)
|
||||||
|
const cropCache = new Map();
|
||||||
|
|
||||||
|
// Функция для получения имени культуры
|
||||||
|
async function getCropName(cropId) {
|
||||||
|
if (!cropId) return 'N/A';
|
||||||
|
if (cropCache.has(cropId)) {
|
||||||
|
return cropCache.get(cropId);
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const response = await client.get(`/crops/${cropId}`);
|
||||||
|
const cropName = response.data.data.name || 'N/A';
|
||||||
|
cropCache.set(cropId, cropName);
|
||||||
|
return cropName;
|
||||||
|
} catch (error) {
|
||||||
|
console.error(`Error fetching crop ${cropId}:`, error.message);
|
||||||
|
return 'N/A';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Функция для построения иерархии зоны (папка -> группа)
|
||||||
|
function buildZoneHierarchy(fieldGroup) {
|
||||||
|
if (!fieldGroup) return 'No Group';
|
||||||
|
|
||||||
|
const parts = [];
|
||||||
|
let current = fieldGroup;
|
||||||
|
|
||||||
|
// Сначала добавляем имя самой группы
|
||||||
|
parts.push(current.name);
|
||||||
|
|
||||||
|
// Поднимаемся по родительским папкам
|
||||||
|
let parentId = current.group_folder_id;
|
||||||
|
while (parentId) {
|
||||||
|
const parentFolder = groupFoldersMap.get(parentId);
|
||||||
|
if (parentFolder) {
|
||||||
|
parts.push(parentFolder.name);
|
||||||
|
parentId = parentFolder.parent_id; // Поднимаемся выше
|
||||||
|
} else {
|
||||||
|
// Если папка не найдена, выходим из цикла
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Переворачиваем массив, чтобы иерархия шла от верхнего уровня к нижнему
|
||||||
|
return parts.reverse().join(' -> ');
|
||||||
|
}
|
||||||
|
|
||||||
|
// 5. Собираем данные по каждому полю
|
||||||
|
console.log('\nProcessing fields and history items...');
|
||||||
|
const report = [];
|
||||||
|
|
||||||
|
for (const field of fields) {
|
||||||
|
const fieldId = field.id;
|
||||||
|
|
||||||
|
// Получаем историю поля для указанного сезона
|
||||||
|
const historyItems = await fetchAllPages('/history_items', {
|
||||||
|
field_id: fieldId,
|
||||||
|
year: SEASON_YEAR,
|
||||||
|
active: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
let historyItem = historyItems.find(item => item.year === SEASON_YEAR);
|
||||||
|
|
||||||
|
// Если активной истории нет, пробуем найти любую для этого года
|
||||||
|
if (!historyItem && historyItems.length > 0) {
|
||||||
|
historyItem = historyItems[0];
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!historyItem) {
|
||||||
|
console.log(` No history item found for field ${fieldId} (${field.name}) in season ${SEASON_YEAR}. Skipping.`);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
const cropName = await getCropName(historyItem.crop_id);
|
||||||
|
|
||||||
|
// Получаем информацию о группе поля
|
||||||
|
const fieldGroup = fieldGroupsMap.get(field.field_group_id);
|
||||||
|
const zoneHierarchy = buildZoneHierarchy(fieldGroup);
|
||||||
|
|
||||||
|
// Собираем данные в единую строку для отчета
|
||||||
|
report.push({
|
||||||
|
'Зона (иерархия)': zoneHierarchy,
|
||||||
|
'ID Поля': fieldId,
|
||||||
|
'Имя поля': field.name || 'N/A',
|
||||||
|
'Сезон': historyItem.year || 'N/A',
|
||||||
|
'Культура': cropName,
|
||||||
|
'Гибрид/сорт': historyItem.variety || 'N/A',
|
||||||
|
'Площадь (га)': field.calculated_area || field.tillable_area || 'N/A',
|
||||||
|
'Урожайность (ц/га)': historyItem.productivity ? Number(historyItem.productivity).toFixed(2) : 'N/A',
|
||||||
|
'Валовый сбор (т)': historyItem.harvested_weight ? Number(historyItem.harvested_weight).toFixed(2) : 'N/A',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- ВЫВОД РЕЗУЛЬТАТОВ В CSV ---
|
||||||
|
|
||||||
|
console.log(`\nTotal fields with history for season ${SEASON_YEAR}: ${report.length}`);
|
||||||
|
|
||||||
|
if (report.length === 0) {
|
||||||
|
console.log('Nothing to write.');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const headers = Object.keys(report[0]);
|
||||||
|
const csvRows = [
|
||||||
|
headers.join(','),
|
||||||
|
...report.map(row =>
|
||||||
|
headers.map(header => {
|
||||||
|
const val = row[header] ?? '';
|
||||||
|
return `"${String(val).replace(/"/g, '""')}"`;
|
||||||
|
}).join(',')
|
||||||
|
),
|
||||||
|
];
|
||||||
|
|
||||||
|
const csvPath = path.join(__dirname, `fields_history_${SEASON_YEAR}.csv`);
|
||||||
|
// BOM для корректного открытия кириллицы в Excel
|
||||||
|
fs.writeFileSync(csvPath, `\uFEFF${csvRows.join('\n')}`, 'utf8');
|
||||||
|
console.log(`Report saved to ${csvPath}`);
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
console.error('An error occurred during report generation:', error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Запускаем скрипт
|
||||||
|
generateFieldsReport();
|
||||||
@@ -0,0 +1,287 @@
|
|||||||
|
import requests
|
||||||
|
import time
|
||||||
|
from typing import List, Dict, Any, Optional
|
||||||
|
from collections import defaultdict
|
||||||
|
import csv
|
||||||
|
import sys
|
||||||
|
|
||||||
|
# --- КОНФИГУРАЦИЯ ---
|
||||||
|
API_BASE_URL = 'https://operations.cropwise.com/api/v3'
|
||||||
|
API_TOKEN = 'YOUR_API_TOKEN_HERE' # Замените на ваш токен
|
||||||
|
SEASON_YEAR = 2025 # Укажите нужный год
|
||||||
|
|
||||||
|
# --- HTTP КЛИЕНТ ---
|
||||||
|
session = requests.Session()
|
||||||
|
session.headers.update({
|
||||||
|
'X-User-Api-Token': API_TOKEN,
|
||||||
|
'Accept': 'application/json',
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
})
|
||||||
|
|
||||||
|
# --- ВСПОМОГАТЕЛЬНЫЕ ФУНКЦИИ ---
|
||||||
|
|
||||||
|
def fetch_all_pages(endpoint: str, query_params: Optional[Dict[str, Any]] = None,
|
||||||
|
max_records: Optional[int] = None) -> List[Dict[str, Any]]:
|
||||||
|
"""
|
||||||
|
Получает все страницы ресурса с пагинацией.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
endpoint: URL эндпоинта (например, '/fields')
|
||||||
|
query_params: Дополнительные параметры запроса
|
||||||
|
max_records: Максимальное количество записей для получения (опционально)
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Список всех записей
|
||||||
|
"""
|
||||||
|
all_data = []
|
||||||
|
from_id = 0
|
||||||
|
limit = 100 # Можно увеличить до 1000
|
||||||
|
has_more = True
|
||||||
|
total_fetched = 0
|
||||||
|
|
||||||
|
print(f"Fetching all pages for {endpoint}...")
|
||||||
|
|
||||||
|
params = query_params.copy() if query_params else {}
|
||||||
|
params['limit'] = limit
|
||||||
|
|
||||||
|
while has_more:
|
||||||
|
params['from_id'] = from_id
|
||||||
|
|
||||||
|
try:
|
||||||
|
response = session.get(f"{API_BASE_URL}{endpoint}", params=params)
|
||||||
|
response.raise_for_status()
|
||||||
|
|
||||||
|
result = response.json()
|
||||||
|
data = result.get('data', [])
|
||||||
|
meta = result.get('meta', {})
|
||||||
|
response_meta = meta.get('response', {})
|
||||||
|
|
||||||
|
if data and len(data) > 0:
|
||||||
|
all_data.extend(data)
|
||||||
|
total_fetched += len(data)
|
||||||
|
print(f" Fetched {len(data)} records. Total so far: {total_fetched}")
|
||||||
|
|
||||||
|
# Обновляем from_id для следующей страницы
|
||||||
|
from_id = response_meta.get('last_record_id', from_id)
|
||||||
|
|
||||||
|
# Проверяем, есть ли еще записи
|
||||||
|
obtained_records = response_meta.get('obtained_records', 0)
|
||||||
|
has_more = len(data) == limit and obtained_records == limit
|
||||||
|
|
||||||
|
# Проверяем лимит записей
|
||||||
|
if max_records and total_fetched >= max_records:
|
||||||
|
print(f" Reached max records limit: {max_records}")
|
||||||
|
has_more = False
|
||||||
|
break
|
||||||
|
else:
|
||||||
|
has_more = False
|
||||||
|
|
||||||
|
# Небольшая задержка между запросами для соблюдения rate limit
|
||||||
|
time.sleep(0.5)
|
||||||
|
|
||||||
|
except requests.exceptions.RequestException as e:
|
||||||
|
print(f"Error fetching {endpoint}: {e}")
|
||||||
|
if hasattr(e, 'response') and e.response:
|
||||||
|
print(f" Response: {e.response.text}")
|
||||||
|
has_more = False
|
||||||
|
break
|
||||||
|
|
||||||
|
print(f" Finished fetching. Total records: {total_fetched}")
|
||||||
|
return all_data
|
||||||
|
|
||||||
|
def get_crop_name(crop_id: int, crop_cache: Dict[int, str]) -> str:
|
||||||
|
"""
|
||||||
|
Получает имя культуры по ID с кэшированием.
|
||||||
|
"""
|
||||||
|
if not crop_id:
|
||||||
|
return 'N/A'
|
||||||
|
|
||||||
|
if crop_id in crop_cache:
|
||||||
|
return crop_cache[crop_id]
|
||||||
|
|
||||||
|
try:
|
||||||
|
response = session.get(f"{API_BASE_URL}/crops/{crop_id}")
|
||||||
|
response.raise_for_status()
|
||||||
|
crop_name = response.json().get('data', {}).get('name', 'N/A')
|
||||||
|
crop_cache[crop_id] = crop_name
|
||||||
|
return crop_name
|
||||||
|
except requests.exceptions.RequestException as e:
|
||||||
|
print(f"Error fetching crop {crop_id}: {e}")
|
||||||
|
return 'N/A'
|
||||||
|
|
||||||
|
def build_zone_hierarchy(field_group: Optional[Dict], group_folders_map: Dict[int, Dict]) -> str:
|
||||||
|
"""
|
||||||
|
Строит иерархию зоны от верхнего уровня к нижнему.
|
||||||
|
"""
|
||||||
|
if not field_group:
|
||||||
|
return 'No Group'
|
||||||
|
|
||||||
|
parts = []
|
||||||
|
current = field_group
|
||||||
|
|
||||||
|
# Добавляем имя группы
|
||||||
|
parts.append(current.get('name', 'Unnamed Group'))
|
||||||
|
|
||||||
|
# Поднимаемся по родительским папкам
|
||||||
|
parent_id = current.get('group_folder_id')
|
||||||
|
while parent_id:
|
||||||
|
parent_folder = group_folders_map.get(parent_id)
|
||||||
|
if parent_folder:
|
||||||
|
parts.append(parent_folder.get('name', 'Unnamed Folder'))
|
||||||
|
parent_id = parent_folder.get('parent_id')
|
||||||
|
else:
|
||||||
|
break
|
||||||
|
|
||||||
|
# Переворачиваем для иерархии от верхнего уровня
|
||||||
|
return ' -> '.join(reversed(parts))
|
||||||
|
|
||||||
|
def get_history_item_for_field(field_id: int, fields_history: Dict[int, List[Dict]]) -> Optional[Dict]:
|
||||||
|
"""
|
||||||
|
Получает активную историю для поля за указанный сезон.
|
||||||
|
"""
|
||||||
|
history_items = fields_history.get(field_id, [])
|
||||||
|
|
||||||
|
# Ищем активную запись за нужный год
|
||||||
|
for item in history_items:
|
||||||
|
if item.get('year') == SEASON_YEAR and item.get('active'):
|
||||||
|
return item
|
||||||
|
|
||||||
|
# Если активной нет, берем первую запись за нужный год
|
||||||
|
for item in history_items:
|
||||||
|
if item.get('year') == SEASON_YEAR:
|
||||||
|
return item
|
||||||
|
|
||||||
|
# Если записей за нужный год нет, берем первую активную
|
||||||
|
for item in history_items:
|
||||||
|
if item.get('active'):
|
||||||
|
return item
|
||||||
|
|
||||||
|
# Если ничего не найдено
|
||||||
|
return None
|
||||||
|
|
||||||
|
# --- ОСНОВНАЯ ФУНКЦИЯ ---
|
||||||
|
|
||||||
|
def generate_fields_report():
|
||||||
|
print(f"Starting report generation for season {SEASON_YEAR}...")
|
||||||
|
print("=" * 60)
|
||||||
|
|
||||||
|
try:
|
||||||
|
# 1. Получаем все поля
|
||||||
|
fields = fetch_all_pages('/fields')
|
||||||
|
if not fields:
|
||||||
|
print("No fields found.")
|
||||||
|
return
|
||||||
|
|
||||||
|
field_ids = [field['id'] for field in fields]
|
||||||
|
|
||||||
|
# 2. Получаем все группы полей
|
||||||
|
field_groups = fetch_all_pages('/field_groups')
|
||||||
|
field_groups_map = {fg['id']: fg for fg in field_groups}
|
||||||
|
|
||||||
|
# 3. Получаем все групповые папки
|
||||||
|
group_folders = fetch_all_pages('/group_folders')
|
||||||
|
group_folders_map = {gf['id']: gf for gf in group_folders}
|
||||||
|
|
||||||
|
# 4. Получаем историю для всех полей
|
||||||
|
print(f"\nFetching history items for {len(field_ids)} fields...")
|
||||||
|
fields_history = defaultdict(list)
|
||||||
|
|
||||||
|
for i, field_id in enumerate(field_ids, 1):
|
||||||
|
print(f" Fetching history for field {i}/{len(field_ids)} (ID: {field_id})")
|
||||||
|
history_items = fetch_all_pages('/history_items', {
|
||||||
|
'field_id': field_id,
|
||||||
|
'year': SEASON_YEAR,
|
||||||
|
}, max_records=10) # Обычно для поля не более 10 записей истории
|
||||||
|
fields_history[field_id].extend(history_items)
|
||||||
|
time.sleep(0.3) # Задержка между запросами
|
||||||
|
|
||||||
|
# 5. Кэш для культур
|
||||||
|
crop_cache = {}
|
||||||
|
|
||||||
|
# 6. Собираем отчет
|
||||||
|
print("\n" + "=" * 60)
|
||||||
|
print("Generating report...")
|
||||||
|
|
||||||
|
report = []
|
||||||
|
|
||||||
|
for field in fields:
|
||||||
|
field_id = field['id']
|
||||||
|
history_item = get_history_item_for_field(field_id, fields_history)
|
||||||
|
|
||||||
|
if not history_item:
|
||||||
|
print(f" No history found for field {field_id} ({field.get('name', 'N/A')})")
|
||||||
|
continue
|
||||||
|
|
||||||
|
crop_name = get_crop_name(history_item.get('crop_id'), crop_cache)
|
||||||
|
|
||||||
|
# Информация о группе
|
||||||
|
field_group = field_groups_map.get(field.get('field_group_id'))
|
||||||
|
zone_hierarchy = build_zone_hierarchy(field_group, group_folders_map)
|
||||||
|
|
||||||
|
# Собираем данные
|
||||||
|
report.append({
|
||||||
|
'Зона (иерархия)': zone_hierarchy,
|
||||||
|
'ID Поля': field_id,
|
||||||
|
'Имя поля': field.get('name', 'N/A'),
|
||||||
|
'Сезон': history_item.get('year', 'N/A'),
|
||||||
|
'Культура': crop_name,
|
||||||
|
'Гибрид/сорт': history_item.get('variety', 'N/A'),
|
||||||
|
'Площадь (га)': field.get('calculated_area') or field.get('tillable_area') or 'N/A',
|
||||||
|
'Урожайность (ц/га)': f"{history_item.get('productivity', 0):.2f}" if history_item.get('productivity') else 'N/A',
|
||||||
|
'Валовый сбор (т)': f"{history_item.get('harvested_weight', 0):.2f}" if history_item.get('harvested_weight') else 'N/A',
|
||||||
|
})
|
||||||
|
|
||||||
|
# --- ВЫВОД РЕЗУЛЬТАТОВ ---
|
||||||
|
|
||||||
|
print("\n" + "=" * 60)
|
||||||
|
print("REPORT")
|
||||||
|
print("=" * 60)
|
||||||
|
print(f"Total fields with history for season {SEASON_YEAR}: {len(report)}")
|
||||||
|
print("-" * 60)
|
||||||
|
|
||||||
|
# Вывод в табличном формате
|
||||||
|
if report:
|
||||||
|
# Определяем максимальную ширину колонок
|
||||||
|
col_widths = {}
|
||||||
|
for key in report[0].keys():
|
||||||
|
col_widths[key] = max(len(str(key)), max(len(str(row.get(key, ''))) for row in report)) + 2
|
||||||
|
|
||||||
|
# Выводим заголовки
|
||||||
|
header = " | ".join(f"{key:{col_widths[key]}}" for key in report[0].keys())
|
||||||
|
print(header)
|
||||||
|
print("-" * len(header))
|
||||||
|
|
||||||
|
# Выводим строки
|
||||||
|
for row in report:
|
||||||
|
values = []
|
||||||
|
for key, width in col_widths.items():
|
||||||
|
val = str(row.get(key, ''))
|
||||||
|
# Ограничиваем длину для читаемости
|
||||||
|
if len(val) > 50:
|
||||||
|
val = val[:47] + "..."
|
||||||
|
values.append(f"{val:{width}}")
|
||||||
|
print(" | ".join(values))
|
||||||
|
|
||||||
|
# Вывод в CSV формате
|
||||||
|
print("\n" + "=" * 60)
|
||||||
|
print("CSV FORMAT (Copy this to Excel/Google Sheets)")
|
||||||
|
print("=" * 60)
|
||||||
|
if report:
|
||||||
|
# Определяем поля для CSV
|
||||||
|
fieldnames = report[0].keys()
|
||||||
|
writer = csv.DictWriter(sys.stdout, fieldnames=fieldnames, delimiter=';', quotechar='"', quoting=csv.QUOTE_MINIMAL)
|
||||||
|
writer.writeheader()
|
||||||
|
for row in report:
|
||||||
|
# Убираем проблемы с кодировкой для вывода в консоль
|
||||||
|
csv_row = {k: str(v).replace('\n', ' ').strip() for k, v in row.items()}
|
||||||
|
writer.writerow(csv_row)
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
print(f"An error occurred during report generation: {e}")
|
||||||
|
import traceback
|
||||||
|
traceback.print_exc()
|
||||||
|
|
||||||
|
# --- ЗАПУСК ---
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
generate_fields_report()
|
||||||
@@ -0,0 +1,99 @@
|
|||||||
|
Зона (иерархия),ID Поля,Имя поля,Сезон,Культура,Гибрид/сорт,Площадь (га),Урожайность (ц/га),Валовый сбор (т)
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Север -> пр. ""Большевик"" -> пр. ""Большевик"" ПО№5","2142","23-28-КНЛВ-057","2025","Пшеница озимая","Таня, ЭС","133.22804","10.49","139.48"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Север -> пр. ""Большевик"" -> пр. ""Большевик"" ПО№5","2144","23-28-КНЛВ-058","2025","Пшеница озимая","Алексеич, ЭС","86.41144","6.63","57.00"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Север -> пр. ""Большевик"" -> пр. ""Большевик"" ПО№5","2149","23-28-КНЛВ-032","2025","Пшеница озимая","Алексеич, ЭС","87.29314","9.91","86.18"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Север -> пр. ""Большевик"" -> пр. ""Большевик"" ПО№5","2294","23-28-КНЛВ-034","2025","Пшеница озимая","Алексеич, ЭС","36.55571","10.61","39.26"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОСП ""Кавказ"" -> ОСП ""Кавказ"" - ПО2","6238","23-16-СТЕП-009","2025","Кукуруза на зерно","N/A","29.73444","36.71","110.12"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОСП ""Кавказ"" -> ОСП ""Кавказ"" - ПО1","6247","23-16-КУРГ-045","2025","Кукуруза на зерно","N/A","126.90135","51.51","654.16"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОСП ""Кавказ"" -> ОСП ""Кавказ"" - ПО4 (Михайловская)","6294","23-16-МХЛВ-051","2025","Кукуруза на зерно","ДКС 4178","118.01267","N/A","N/A"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОСП ""Кавказ"" -> ОСП ""Кавказ"" - ПО4 (Михайловская)","6297","23-16-МХЛВ-049","2025","Кукуруза на зерно","ДКС 4178","41.30088","N/A","N/A"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОСП ""Кавказ"" -> ОСП ""Кавказ"" - ПО4 (Михайловская)","6326","23-16-МХЛВ-041","2025","Кукуруза на зерно","ДКС 4178","148.85599","N/A","N/A"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОСП ""Кавказ"" -> ОСП ""Кавказ"" - ПО2","6346","23-16-КУРГ-081","2025","Кукуруза на зерно","КЛ7408УМ, КЛ7202МВ","64.62628","N/A","N/A"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОСП ""Кавказ"" -> ОСП ""Кавказ"" - ПО5 (Северный)","6373","23-16-ППАВ-042/уч.2","2025","Кукуруза на зерно","Адэвей","63.55141","N/A","N/A"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Центр -> пр. ""Рассвет"" -> Предприятие ""Рассвет"" ПО 3","7045","23-05-КРУП-089","2025","Кукуруза на зерно","ДКС 4014, КСС 2290, КСС 5291","90.9213","26.35","239.83"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Центр -> пр. ""Рассвет"" -> Предприятие ""Рассвет"" ПО 3","7131","23-05-КРУП-098","2025","Кукуруза на зерно","КСС 2290","90.52703","35.54","323.43"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Центр -> пр. ""Рассвет"" -> Предприятие ""Рассвет"" ПО 3","7140","23-05-КРУП-072","2025","Кукуруза на зерно","КСС 2290","85.32178","29.61","251.68"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Север -> пр. ""Кущевское"" -> ООО ""Октябрь"" -> ПО2 Новосергиевское","11145","23-14-НСРГ-004","2025","Кукуруза на силос и зеленый корм","N/A","73.35477","87.69","640.16"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Север -> пр. ""Кущевское"" -> ООО ""Октябрь"" -> ПО2 Новосергиевское","11152","23-14-НСРГ-018","2025","Горох яровой","Мадонна РС2","89.01653","9.82","87.42"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Север -> пр. ""Кущевское"" -> ООО ""Октябрь"" -> ПО2 Новосергиевское","11153","23-14-НСРГ-022","2025","Горох яровой","Мадонна РС2","90.74663","9.41","85.62"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Север -> пр. ""Кущевское"" -> ООО ""Октябрь"" -> ПО2 Новосергиевское","11171","23-14-НСРГ-006","2025","Горох яровой","Мадонна РС2","116.66194","7.66","89.58"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион РИС -> пр. ""Чебургольское"" -> пр. ""Чебургольское"" -ПО5","11665","23-13-СНЖС-063","2025","Соя","СК Риана","51.15512","13.22","67.40"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион РИС -> пр. ""Чебургольское"" -> пр. ""Чебургольское"" -ПО5","11670","23-13-СНЖС-069","2025","Соя","Вилана","152.31181","11.32","172.00"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12359","26-03-ДИВН-114","2025","Пар","N/A","75.8142","N/A","N/A"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12360","26-03-ДИВН-127","2025","Пшеница озимая","Таня, РС1","78.00789","64.68","504.53"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12361","26-03-ДИВН-129","2025","Пшеница озимая","Таня, РС1","77.36838","53.28","410.29"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12362","26-03-ДИВН-087","2025","Пшеница озимая","Таня, ЭС","77.15332","56.62","435.94"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12363","26-03-ДИВН-093","2025","Пшеница озимая","Таня, ЭС","76.99691","58.53","450.71"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12364","26-03-ДИВН-078","2025","Пар","N/A","128.32389","N/A","N/A"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12365","26-03-ДИВН-136","2025","Пар","N/A","96.89791","N/A","N/A"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12366","26-03-ДИВН-063","2025","Пшеница озимая","Еланчик, РС1","207.73833","55.95","1163.68"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12367","26-03-ДИВН-042","2025","Пар","N/A","89.54959","N/A","N/A"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12368","26-03-ДИВН-052","2025","Пшеница озимая","Еланчик, ЭС","91.14874","52.60","478.68"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12369","26-03-ДИВН-055","2025","Пшеница озимая","Еланчик, ЭС","108.69511","51.23","558.36"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12370","26-03-ДИВН-029","2025","Пшеница озимая","Еланчик, РС1","80.71644","58.20","471.43"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12371","26-03-ДИВН-004","2025","Пар","N/A","75.70805","N/A","N/A"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12372","26-03-ДИВН-012","2025","Пар","N/A","76.81277","N/A","N/A"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12373","26-03-ДИВН-023","2025","Пар","N/A","75.8251","N/A","N/A"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12374","26-03-ДИВН-031","2025","Пшеница озимая","Еланчик, РС1","79.73259","70.41","563.28"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12375","26-03-ДИВН-030","2025","Пшеница озимая","Еланчик, РС1","78.9072","62.53","493.96"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12376","26-03-ДИВН-022","2025","Пар","N/A","76.30411","N/A","N/A"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12377","26-03-ДИВН-018","2025","Пар","N/A","74.65977","N/A","N/A"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12378","26-03-ДИВН-016","2025","Пар","N/A","75.77333","N/A","N/A"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12379","26-03-ДИВН-015","2025","Пар","N/A","61.35622","N/A","N/A"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12380","26-03-ДИВН-001","2025","Пар","N/A","68.01438","N/A","N/A"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12381","26-03-ДИВН-002","2025","Пар","N/A","75.54678","N/A","N/A"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12382","26-03-ДИВН-003","2025","Пар","N/A","77.98019","N/A","N/A"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12383","26-03-ДИВН-005","2025","Пар","N/A","74.27875","N/A","N/A"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12384","26-03-ДИВН-044","2025","Пар","N/A","92.99898","N/A","N/A"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12385","26-03-ДИВН-043","2025","Пар","N/A","98.87678","N/A","N/A"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12386","26-03-ДИВН-046","2025","Пшеница озимая","Еланчик, РС1, Таня, ОС","91.59816","57.06","524.98"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12387","26-03-ДИВН-049","2025","Пшеница озимая","Еланчик, ЭС","90.15868","59.55","535.96"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12388","26-03-ДИВН-050","2025","Пшеница озимая","Еланчик, ЭС","91.08992","55.94","509.04"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12389","26-03-ДИВН-051","2025","Пшеница озимая","Еланчик, ЭС","88.2841","58.09","511.20"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12390","26-03-ДИВН-056","2025","Пшеница озимая","Еланчик, ЭС","75.05107","51.55","386.65"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12391","26-03-ДИВН-054","2025","Пшеница озимая","Еланчик, ЭС","88.24606","56.20","494.57"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12392","26-03-ДИВН-053","2025","Пшеница озимая","Еланчик, ЭС","89.76869","57.12","514.10"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12393","26-03-ДИВН-091","2025","Пшеница озимая","Таня, ЭС","78.52942","60.07","474.52"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12394","26-03-ДИВН-090","2025","Пшеница озимая","Таня, ЭС","77.16892","61.51","473.62"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12395","26-03-ДИВН-089","2025","Пшеница озимая","Таня, ЭС","76.80507","56.85","437.78"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12396","26-03-ДИВН-088","2025","Пшеница озимая","Таня, ЭС","76.76631","59.54","458.48"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12397","26-03-ДИВН-086","2025","Пшеница озимая","Таня, ЭС","75.91765","63.29","481.00"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12398","26-03-ДИВН-103","2025","Пар","N/A","74.61086","N/A","N/A"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12399","26-03-ДИВН-102","2025","Пар","N/A","75.83412","N/A","N/A"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12400","26-03-ДИВН-101","2025","Пар","N/A","75.15119","N/A","N/A"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12401","26-03-ДИВН-100","2025","Пар","N/A","74.45783","N/A","N/A"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12402","26-03-ДИВН-098","2025","Пар","N/A","67.64906","N/A","N/A"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12403","26-03-ДИВН-097","2025","Пшеница озимая","Таня, ЭС","77.30325","63.83","491.50"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12404","26-03-ДИВН-096","2025","Пшеница озимая","Таня, ЭС","75.76796","64.10","487.15"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12405","26-03-ДИВН-095","2025","Пшеница озимая","Таня, ЭС","77.29626","60.87","468.67"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12406","26-03-ДИВН-094","2025","Пшеница озимая","Таня, ЭС","77.00115","58.48","450.28"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12407","26-03-ДИВН-092","2025","Пшеница озимая","Таня, ЭС","76.66763","56.92","438.28"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12408","26-03-ДИВН-110","2025","Пар","N/A","77.53622","N/A","N/A"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12409","26-03-ДИВН-111","2025","Пар","N/A","75.23374","N/A","N/A"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12410","26-03-ДИВН-112","2025","Пар","N/A","75.37482","N/A","N/A"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12411","26-03-ДИВН-113","2025","Пар","N/A","75.3835","N/A","N/A"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12412","26-03-ДИВН-115","2025","Пар","N/A","74.99895","N/A","N/A"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12413","26-03-ДИВН-116","2025","Пар","N/A","74.91313","N/A","N/A"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12414","26-03-ДИВН-117","2025","Пар","N/A","75.50088","N/A","N/A"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12415","26-03-ДИВН-118","2025","Пар","N/A","73.92469","N/A","N/A"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12416","26-03-ДИВН-119","2025","Пар","N/A","75.86783","N/A","N/A"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12417","26-03-ДИВН-120","2025","Пар","N/A","74.91037","N/A","N/A"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12418","26-03-ДИВН-121","2025","Пар","N/A","74.27384","N/A","N/A"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12419","26-03-ДИВН-123","2025","Пшеница озимая","Таня, РС1","74.14226","57.73","427.23"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12420","26-03-ДИВН-122","2025","Пшеница озимая","Таня, РС1","74.64285","57.68","432.61"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12421","26-03-ДИВН-124","2025","Пшеница озимая","Таня, РС1","73.34628","56.85","415.02"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12422","26-03-ДИВН-125","2025","Пшеница озимая","Таня, РС1","73.81899","54.16","400.75"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12423","26-03-ДИВН-126","2025","Пшеница озимая","Таня, РС1","73.29094","59.01","430.78"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12424","26-03-ДИВН-128","2025","Пшеница озимая","Таня, РС1","75.8592","53.36","405.56"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12425","26-03-ДИВН-130","2025","Пшеница озимая","Таня, РС1","74.83604","53.67","402.55"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12426","26-03-ДИВН-131","2025","Пшеница озимая","Таня, РС1","77.62159","53.60","418.06"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12427","26-03-ДИВН-133","2025","Пшеница озимая","Таня, РС1","72.08088","52.01","374.47"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12428","26-03-ДИВН-132","2025","Пшеница озимая","Таня, РС1","76.20338","50.19","381.45"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12429","26-03-ДИВН-072","2025","Пшеница озимая","Победа 75 РС-1","248.61377","N/A","N/A"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12430","26-03-ДИВН-013","2025","Пар","N/A","75.86074","N/A","N/A"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12431","26-03-ДИВН-014","2025","Пар","N/A","73.91504","N/A","N/A"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12432","26-03-ДИВН-033","2025","Пшеница озимая","Еланчик, РС1","65.04404","68.49","445.21"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12433","26-03-ДИВН-032","2025","Пшеница озимая","Еланчик, РС1","73.57399","67.88","502.32"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12434","26-03-ДИВН-039","2025","Пшеница озимая","Еланчик, РС1","67.63178","54.15","368.24"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12435","26-03-ДИВН-038","2025","Пшеница озимая","Еланчик, РС1","69.16333","50.94","351.52"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12436","26-03-ДИВН-041","2025","Пар","N/A","89.30344","N/A","N/A"
|
||||||
|
@@ -0,0 +1,598 @@
|
|||||||
|
require('dotenv').config();
|
||||||
|
const axios = require('axios');
|
||||||
|
const { Client, Pool } = require('pg');
|
||||||
|
|
||||||
|
const API_BASE_URL = process.env.API_BASE_URL || 'https://operations.cropwise.com/api/v3';
|
||||||
|
const API_TOKEN = process.env.API_TOKEN;
|
||||||
|
const GROUP_FOLDER_ROOT_ID = Number(process.env.GROUP_FOLDER_ROOT_ID || 27);
|
||||||
|
const CONCURRENCY = Number(process.env.CONCURRENCY || 5);
|
||||||
|
const FORCE_REFRESH = ['1', 'true', 'yes'].includes(
|
||||||
|
String(process.env.FORCE_REFRESH || '').toLowerCase()
|
||||||
|
);
|
||||||
|
// If set (ISO date), re-fetch fields whose 2026 history updated_at is missing or older
|
||||||
|
const REFRESH_IF_BEFORE = process.env.REFRESH_IF_BEFORE || '';
|
||||||
|
|
||||||
|
const PG = {
|
||||||
|
host: process.env.PGHOST || '10.8.0.23',
|
||||||
|
port: Number(process.env.PGPORT || 5432),
|
||||||
|
database: process.env.PGDATABASE || 'ak_fields',
|
||||||
|
user: process.env.PGUSER || 'postgres',
|
||||||
|
password: process.env.PGPASSWORD || 'postgres',
|
||||||
|
};
|
||||||
|
|
||||||
|
if (!API_TOKEN) {
|
||||||
|
console.error('API_TOKEN is missing in .env');
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
const client = axios.create({
|
||||||
|
baseURL: API_BASE_URL,
|
||||||
|
headers: {
|
||||||
|
'X-User-Api-Token': API_TOKEN,
|
||||||
|
Accept: 'application/json',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
async function fetchAllPages(endpoint, queryParams = {}, { quiet = false } = {}) {
|
||||||
|
let allData = [];
|
||||||
|
let fromId = 0;
|
||||||
|
const limit = 100;
|
||||||
|
let hasMore = true;
|
||||||
|
|
||||||
|
if (!quiet) console.log(`Fetching all pages for ${endpoint}...`);
|
||||||
|
|
||||||
|
while (hasMore) {
|
||||||
|
try {
|
||||||
|
const response = await client.get(endpoint, {
|
||||||
|
params: {
|
||||||
|
...queryParams,
|
||||||
|
limit,
|
||||||
|
from_id: fromId,
|
||||||
|
sort_by: 'id_asc',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const { data, meta } = response.data;
|
||||||
|
|
||||||
|
if (data && data.length > 0) {
|
||||||
|
allData = allData.concat(data);
|
||||||
|
if (!quiet) {
|
||||||
|
console.log(` Fetched ${data.length} records. Total so far: ${allData.length}`);
|
||||||
|
}
|
||||||
|
fromId = meta.response.last_record_id;
|
||||||
|
hasMore = data.length === limit && meta.response.obtained_records === limit;
|
||||||
|
} else {
|
||||||
|
hasMore = false;
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error(`Error fetching ${endpoint}:`, error.response?.data || error.message);
|
||||||
|
hasMore = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!quiet) console.log(` Finished fetching. Total records: ${allData.length}`);
|
||||||
|
return allData;
|
||||||
|
}
|
||||||
|
|
||||||
|
function collectFolderSubtree(groupFolders, rootId) {
|
||||||
|
const childrenByParent = new Map();
|
||||||
|
for (const folder of groupFolders) {
|
||||||
|
const parentKey = folder.parent_id == null ? null : folder.parent_id;
|
||||||
|
if (!childrenByParent.has(parentKey)) childrenByParent.set(parentKey, []);
|
||||||
|
childrenByParent.get(parentKey).push(folder);
|
||||||
|
}
|
||||||
|
|
||||||
|
const ids = new Set();
|
||||||
|
const queue = [rootId];
|
||||||
|
while (queue.length > 0) {
|
||||||
|
const id = queue.shift();
|
||||||
|
if (ids.has(id)) continue;
|
||||||
|
ids.add(id);
|
||||||
|
const children = childrenByParent.get(id) || [];
|
||||||
|
for (const child of children) queue.push(child.id);
|
||||||
|
}
|
||||||
|
return ids;
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildZoneHierarchy(fieldGroup, groupFoldersMap) {
|
||||||
|
if (!fieldGroup) return 'No Group';
|
||||||
|
|
||||||
|
const parts = [];
|
||||||
|
let current = fieldGroup;
|
||||||
|
parts.push(current.name);
|
||||||
|
|
||||||
|
let parentId = current.group_folder_id;
|
||||||
|
while (parentId) {
|
||||||
|
const parentFolder = groupFoldersMap.get(parentId);
|
||||||
|
if (parentFolder) {
|
||||||
|
parts.push(parentFolder.name);
|
||||||
|
parentId = parentFolder.parent_id;
|
||||||
|
} else {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return parts.reverse().join(' -> ');
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseJsonField(value) {
|
||||||
|
if (value == null || value === '') return null;
|
||||||
|
if (typeof value === 'object') return value;
|
||||||
|
try {
|
||||||
|
return JSON.parse(value);
|
||||||
|
} catch {
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function ensureDatabase() {
|
||||||
|
const admin = new Client({
|
||||||
|
host: PG.host,
|
||||||
|
port: PG.port,
|
||||||
|
user: PG.user,
|
||||||
|
password: PG.password,
|
||||||
|
database: 'postgres',
|
||||||
|
});
|
||||||
|
|
||||||
|
await admin.connect();
|
||||||
|
try {
|
||||||
|
const { rows } = await admin.query(
|
||||||
|
'SELECT 1 FROM pg_database WHERE datname = $1',
|
||||||
|
[PG.database]
|
||||||
|
);
|
||||||
|
if (rows.length === 0) {
|
||||||
|
console.log(`Creating database ${PG.database}...`);
|
||||||
|
await admin.query(`CREATE DATABASE ${PG.database}`);
|
||||||
|
console.log(`Database ${PG.database} created.`);
|
||||||
|
} else {
|
||||||
|
console.log(`Database ${PG.database} already exists.`);
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
await admin.end();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function ensureTables(db) {
|
||||||
|
await db.query(`
|
||||||
|
CREATE TABLE IF NOT EXISTS crops (
|
||||||
|
id BIGINT PRIMARY KEY,
|
||||||
|
name TEXT,
|
||||||
|
short_name TEXT,
|
||||||
|
standard_name TEXT,
|
||||||
|
color TEXT,
|
||||||
|
crop_type TEXT,
|
||||||
|
crop_group_id BIGINT,
|
||||||
|
plant_id BIGINT,
|
||||||
|
harvestable BOOLEAN,
|
||||||
|
additional_info JSONB,
|
||||||
|
external_id TEXT,
|
||||||
|
created_at TIMESTAMPTZ,
|
||||||
|
updated_at TIMESTAMPTZ,
|
||||||
|
raw JSONB
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS group_folders (
|
||||||
|
id BIGINT PRIMARY KEY,
|
||||||
|
parent_id BIGINT,
|
||||||
|
name TEXT,
|
||||||
|
hidden BOOLEAN,
|
||||||
|
created_at TIMESTAMPTZ,
|
||||||
|
updated_at TIMESTAMPTZ,
|
||||||
|
external_id TEXT
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS field_groups (
|
||||||
|
id BIGINT PRIMARY KEY,
|
||||||
|
group_folder_id BIGINT,
|
||||||
|
name TEXT,
|
||||||
|
description TEXT,
|
||||||
|
administrative_area_name TEXT,
|
||||||
|
subadministrative_area_name TEXT,
|
||||||
|
locality TEXT,
|
||||||
|
hidden BOOLEAN,
|
||||||
|
external_id TEXT,
|
||||||
|
created_at TIMESTAMPTZ,
|
||||||
|
updated_at TIMESTAMPTZ,
|
||||||
|
idempotency_key TEXT,
|
||||||
|
legal_entity TEXT,
|
||||||
|
machine_task_default_duration DOUBLE PRECISION,
|
||||||
|
accounting_period_closing_date DATE,
|
||||||
|
machine_task_default_start_time TEXT,
|
||||||
|
time_zone TEXT
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS fields (
|
||||||
|
id BIGINT PRIMARY KEY,
|
||||||
|
field_group_id BIGINT,
|
||||||
|
name TEXT,
|
||||||
|
additional_name TEXT,
|
||||||
|
description TEXT,
|
||||||
|
moisture_zone TEXT,
|
||||||
|
shape_simplified_geojson JSONB,
|
||||||
|
current_shape_id BIGINT,
|
||||||
|
calculated_area DOUBLE PRECISION,
|
||||||
|
legal_area DOUBLE PRECISION,
|
||||||
|
tillable_area DOUBLE PRECISION,
|
||||||
|
administrative_area_name TEXT,
|
||||||
|
subadministrative_area_name TEXT,
|
||||||
|
region_id BIGINT,
|
||||||
|
country_id BIGINT,
|
||||||
|
district_id BIGINT,
|
||||||
|
locality TEXT,
|
||||||
|
field_type TEXT,
|
||||||
|
parent_id BIGINT,
|
||||||
|
lat DOUBLE PRECISION,
|
||||||
|
long DOUBLE PRECISION,
|
||||||
|
additional_info JSONB,
|
||||||
|
external_id TEXT,
|
||||||
|
public_registry_key TEXT,
|
||||||
|
created_at TIMESTAMPTZ,
|
||||||
|
updated_at TIMESTAMPTZ,
|
||||||
|
x_custom_nomer_polya_v_efgis_zsn TEXT,
|
||||||
|
zone_hierarchy TEXT,
|
||||||
|
history_items JSONB
|
||||||
|
);
|
||||||
|
`);
|
||||||
|
console.log('Tables ensured.');
|
||||||
|
}
|
||||||
|
|
||||||
|
async function upsertCrops(db, crops) {
|
||||||
|
const sql = `
|
||||||
|
INSERT INTO crops (
|
||||||
|
id, name, short_name, standard_name, color, crop_type, crop_group_id,
|
||||||
|
plant_id, harvestable, additional_info, external_id, created_at, updated_at, raw
|
||||||
|
) VALUES (
|
||||||
|
$1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14
|
||||||
|
)
|
||||||
|
ON CONFLICT (id) DO UPDATE SET
|
||||||
|
name = EXCLUDED.name,
|
||||||
|
short_name = EXCLUDED.short_name,
|
||||||
|
standard_name = EXCLUDED.standard_name,
|
||||||
|
color = EXCLUDED.color,
|
||||||
|
crop_type = EXCLUDED.crop_type,
|
||||||
|
crop_group_id = EXCLUDED.crop_group_id,
|
||||||
|
plant_id = EXCLUDED.plant_id,
|
||||||
|
harvestable = EXCLUDED.harvestable,
|
||||||
|
additional_info = EXCLUDED.additional_info,
|
||||||
|
external_id = EXCLUDED.external_id,
|
||||||
|
created_at = EXCLUDED.created_at,
|
||||||
|
updated_at = EXCLUDED.updated_at,
|
||||||
|
raw = EXCLUDED.raw
|
||||||
|
`;
|
||||||
|
|
||||||
|
for (const c of crops) {
|
||||||
|
await db.query(sql, [
|
||||||
|
c.id,
|
||||||
|
c.name ?? null,
|
||||||
|
c.short_name ?? null,
|
||||||
|
c.standard_name ?? null,
|
||||||
|
c.color ?? null,
|
||||||
|
c.crop_type ?? null,
|
||||||
|
c.crop_group_id ?? null,
|
||||||
|
c.plant_id ?? null,
|
||||||
|
c.harvestable ?? null,
|
||||||
|
parseJsonField(c.additional_info),
|
||||||
|
c.external_id ?? null,
|
||||||
|
c.created_at ?? null,
|
||||||
|
c.updated_at ?? null,
|
||||||
|
c,
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
console.log(`Upserted crops: ${crops.length}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function upsertGroupFolders(db, folders) {
|
||||||
|
const sql = `
|
||||||
|
INSERT INTO group_folders (id, parent_id, name, hidden, created_at, updated_at, external_id)
|
||||||
|
VALUES ($1,$2,$3,$4,$5,$6,$7)
|
||||||
|
ON CONFLICT (id) DO UPDATE SET
|
||||||
|
parent_id = EXCLUDED.parent_id,
|
||||||
|
name = EXCLUDED.name,
|
||||||
|
hidden = EXCLUDED.hidden,
|
||||||
|
created_at = EXCLUDED.created_at,
|
||||||
|
updated_at = EXCLUDED.updated_at,
|
||||||
|
external_id = EXCLUDED.external_id
|
||||||
|
`;
|
||||||
|
|
||||||
|
for (const f of folders) {
|
||||||
|
await db.query(sql, [
|
||||||
|
f.id,
|
||||||
|
f.parent_id ?? null,
|
||||||
|
f.name ?? null,
|
||||||
|
f.hidden ?? null,
|
||||||
|
f.created_at ?? null,
|
||||||
|
f.updated_at ?? null,
|
||||||
|
f.external_id ?? null,
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
console.log(`Upserted group_folders: ${folders.length}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function upsertFieldGroups(db, groups) {
|
||||||
|
const sql = `
|
||||||
|
INSERT INTO field_groups (
|
||||||
|
id, group_folder_id, name, description, administrative_area_name,
|
||||||
|
subadministrative_area_name, locality, hidden, external_id, created_at, updated_at,
|
||||||
|
idempotency_key, legal_entity, machine_task_default_duration,
|
||||||
|
accounting_period_closing_date, machine_task_default_start_time, time_zone
|
||||||
|
) VALUES (
|
||||||
|
$1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16,$17
|
||||||
|
)
|
||||||
|
ON CONFLICT (id) DO UPDATE SET
|
||||||
|
group_folder_id = EXCLUDED.group_folder_id,
|
||||||
|
name = EXCLUDED.name,
|
||||||
|
description = EXCLUDED.description,
|
||||||
|
administrative_area_name = EXCLUDED.administrative_area_name,
|
||||||
|
subadministrative_area_name = EXCLUDED.subadministrative_area_name,
|
||||||
|
locality = EXCLUDED.locality,
|
||||||
|
hidden = EXCLUDED.hidden,
|
||||||
|
external_id = EXCLUDED.external_id,
|
||||||
|
created_at = EXCLUDED.created_at,
|
||||||
|
updated_at = EXCLUDED.updated_at,
|
||||||
|
idempotency_key = EXCLUDED.idempotency_key,
|
||||||
|
legal_entity = EXCLUDED.legal_entity,
|
||||||
|
machine_task_default_duration = EXCLUDED.machine_task_default_duration,
|
||||||
|
accounting_period_closing_date = EXCLUDED.accounting_period_closing_date,
|
||||||
|
machine_task_default_start_time = EXCLUDED.machine_task_default_start_time,
|
||||||
|
time_zone = EXCLUDED.time_zone
|
||||||
|
`;
|
||||||
|
|
||||||
|
for (const g of groups) {
|
||||||
|
await db.query(sql, [
|
||||||
|
g.id,
|
||||||
|
g.group_folder_id ?? null,
|
||||||
|
g.name ?? null,
|
||||||
|
g.description ?? null,
|
||||||
|
g.administrative_area_name ?? null,
|
||||||
|
g.subadministrative_area_name ?? null,
|
||||||
|
g.locality ?? null,
|
||||||
|
g.hidden ?? null,
|
||||||
|
g.external_id ?? null,
|
||||||
|
g.created_at ?? null,
|
||||||
|
g.updated_at ?? null,
|
||||||
|
g.idempotency_key ?? null,
|
||||||
|
g.legal_entity ?? null,
|
||||||
|
g.machine_task_default_duration ?? null,
|
||||||
|
g.accounting_period_closing_date || null,
|
||||||
|
g.machine_task_default_start_time ?? null,
|
||||||
|
g.time_zone ?? null,
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
console.log(`Upserted field_groups: ${groups.length}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function upsertField(db, field, zoneHierarchy, historyItems) {
|
||||||
|
const sql = `
|
||||||
|
INSERT INTO fields (
|
||||||
|
id, field_group_id, name, additional_name, description, moisture_zone,
|
||||||
|
shape_simplified_geojson, current_shape_id, calculated_area, legal_area, tillable_area,
|
||||||
|
administrative_area_name, subadministrative_area_name, region_id, country_id, district_id,
|
||||||
|
locality, field_type, parent_id, lat, long, additional_info, external_id,
|
||||||
|
public_registry_key, created_at, updated_at, x_custom_nomer_polya_v_efgis_zsn,
|
||||||
|
zone_hierarchy, history_items
|
||||||
|
) VALUES (
|
||||||
|
$1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16,$17,$18,$19,$20,
|
||||||
|
$21,$22,$23,$24,$25,$26,$27,$28,$29
|
||||||
|
)
|
||||||
|
ON CONFLICT (id) DO UPDATE SET
|
||||||
|
field_group_id = EXCLUDED.field_group_id,
|
||||||
|
name = EXCLUDED.name,
|
||||||
|
additional_name = EXCLUDED.additional_name,
|
||||||
|
description = EXCLUDED.description,
|
||||||
|
moisture_zone = EXCLUDED.moisture_zone,
|
||||||
|
shape_simplified_geojson = EXCLUDED.shape_simplified_geojson,
|
||||||
|
current_shape_id = EXCLUDED.current_shape_id,
|
||||||
|
calculated_area = EXCLUDED.calculated_area,
|
||||||
|
legal_area = EXCLUDED.legal_area,
|
||||||
|
tillable_area = EXCLUDED.tillable_area,
|
||||||
|
administrative_area_name = EXCLUDED.administrative_area_name,
|
||||||
|
subadministrative_area_name = EXCLUDED.subadministrative_area_name,
|
||||||
|
region_id = EXCLUDED.region_id,
|
||||||
|
country_id = EXCLUDED.country_id,
|
||||||
|
district_id = EXCLUDED.district_id,
|
||||||
|
locality = EXCLUDED.locality,
|
||||||
|
field_type = EXCLUDED.field_type,
|
||||||
|
parent_id = EXCLUDED.parent_id,
|
||||||
|
lat = EXCLUDED.lat,
|
||||||
|
long = EXCLUDED.long,
|
||||||
|
additional_info = EXCLUDED.additional_info,
|
||||||
|
external_id = EXCLUDED.external_id,
|
||||||
|
public_registry_key = EXCLUDED.public_registry_key,
|
||||||
|
created_at = EXCLUDED.created_at,
|
||||||
|
updated_at = EXCLUDED.updated_at,
|
||||||
|
x_custom_nomer_polya_v_efgis_zsn = EXCLUDED.x_custom_nomer_polya_v_efgis_zsn,
|
||||||
|
zone_hierarchy = EXCLUDED.zone_hierarchy,
|
||||||
|
history_items = EXCLUDED.history_items
|
||||||
|
`;
|
||||||
|
|
||||||
|
const params = [
|
||||||
|
field.id,
|
||||||
|
field.field_group_id ?? null,
|
||||||
|
field.name ?? null,
|
||||||
|
field.additional_name ?? null,
|
||||||
|
field.description ?? null,
|
||||||
|
field.moisture_zone ?? null,
|
||||||
|
parseJsonField(field.shape_simplified_geojson),
|
||||||
|
field.current_shape_id ?? null,
|
||||||
|
field.calculated_area ?? null,
|
||||||
|
field.legal_area ?? null,
|
||||||
|
field.tillable_area ?? null,
|
||||||
|
field.administrative_area_name ?? null,
|
||||||
|
field.subadministrative_area_name ?? null,
|
||||||
|
field.region_id ?? null,
|
||||||
|
field.country_id ?? null,
|
||||||
|
field.district_id ?? null,
|
||||||
|
field.locality ?? null,
|
||||||
|
field.field_type ?? null,
|
||||||
|
field.parent_id ?? null,
|
||||||
|
field.lat ?? null,
|
||||||
|
field.long ?? null,
|
||||||
|
parseJsonField(field.additional_info),
|
||||||
|
field.external_id ?? null,
|
||||||
|
field.public_registry_key ?? null,
|
||||||
|
field.created_at ?? null,
|
||||||
|
field.updated_at ?? null,
|
||||||
|
field.x_custom_nomer_polya_v_efgis_zsn ?? null,
|
||||||
|
zoneHierarchy,
|
||||||
|
JSON.stringify(historyItems || []),
|
||||||
|
];
|
||||||
|
|
||||||
|
let lastErr;
|
||||||
|
for (let attempt = 1; attempt <= 3; attempt++) {
|
||||||
|
try {
|
||||||
|
await db.query(sql, params);
|
||||||
|
return;
|
||||||
|
} catch (err) {
|
||||||
|
lastErr = err;
|
||||||
|
const msg = err.message || '';
|
||||||
|
const retryable =
|
||||||
|
/terminat|too many clients|ECONNRESET|ECONNREFUSED|timeout|53300|57P01/i.test(
|
||||||
|
msg
|
||||||
|
) || err.code === '53300';
|
||||||
|
if (!retryable || attempt === 3) throw err;
|
||||||
|
await new Promise((r) => setTimeout(r, attempt * 1000));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
throw lastErr;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function mapPool(items, concurrency, worker) {
|
||||||
|
let index = 0;
|
||||||
|
let done = 0;
|
||||||
|
const total = items.length;
|
||||||
|
const errors = [];
|
||||||
|
|
||||||
|
async function runOne() {
|
||||||
|
while (index < total) {
|
||||||
|
const current = index;
|
||||||
|
index += 1;
|
||||||
|
const item = items[current];
|
||||||
|
try {
|
||||||
|
await worker(item, current);
|
||||||
|
} catch (err) {
|
||||||
|
errors.push({ id: item?.id, error: err.message || String(err) });
|
||||||
|
console.error(` Error on item ${item?.id}:`, err.message || err);
|
||||||
|
} finally {
|
||||||
|
done += 1;
|
||||||
|
if (done % 50 === 0 || done === total) {
|
||||||
|
console.log(` Fields progress: ${done}/${total}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const workers = Array.from({ length: Math.min(concurrency, total) }, () => runOne());
|
||||||
|
await Promise.all(workers);
|
||||||
|
return errors;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function sync() {
|
||||||
|
console.log(
|
||||||
|
`Starting sync for GROUP_FOLDER_ROOT_ID=${GROUP_FOLDER_ROOT_ID}, CONCURRENCY=${CONCURRENCY}...`
|
||||||
|
);
|
||||||
|
|
||||||
|
await ensureDatabase();
|
||||||
|
|
||||||
|
const pool = new Pool({
|
||||||
|
host: PG.host,
|
||||||
|
port: PG.port,
|
||||||
|
user: PG.user,
|
||||||
|
password: PG.password,
|
||||||
|
database: PG.database,
|
||||||
|
max: CONCURRENCY,
|
||||||
|
idleTimeoutMillis: 10000,
|
||||||
|
connectionTimeoutMillis: 15000,
|
||||||
|
allowExitOnIdle: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
try {
|
||||||
|
await ensureTables(pool);
|
||||||
|
|
||||||
|
const [crops, groupFolders, fieldGroups, fields] = await Promise.all([
|
||||||
|
fetchAllPages('/crops'),
|
||||||
|
fetchAllPages('/group_folders'),
|
||||||
|
fetchAllPages('/field_groups'),
|
||||||
|
fetchAllPages('/fields'),
|
||||||
|
]);
|
||||||
|
|
||||||
|
const folderIds = collectFolderSubtree(groupFolders, GROUP_FOLDER_ROOT_ID);
|
||||||
|
if (!folderIds.has(GROUP_FOLDER_ROOT_ID)) {
|
||||||
|
console.warn(`Root folder ${GROUP_FOLDER_ROOT_ID} not found in API response.`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const filteredFolders = groupFolders.filter((f) => folderIds.has(f.id));
|
||||||
|
const filteredGroups = fieldGroups.filter((g) => folderIds.has(g.group_folder_id));
|
||||||
|
const allowedGroupIds = new Set(filteredGroups.map((g) => g.id));
|
||||||
|
const filteredFields = fields.filter((f) => allowedGroupIds.has(f.field_group_id));
|
||||||
|
|
||||||
|
console.log(`group_folders: ${groupFolders.length} -> ${filteredFolders.length}`);
|
||||||
|
console.log(`field_groups: ${fieldGroups.length} -> ${filteredGroups.length}`);
|
||||||
|
console.log(`fields: ${fields.length} -> ${filteredFields.length}`);
|
||||||
|
|
||||||
|
await upsertCrops(pool, crops);
|
||||||
|
await upsertGroupFolders(pool, filteredFolders);
|
||||||
|
await upsertFieldGroups(pool, filteredGroups);
|
||||||
|
|
||||||
|
const groupFoldersMap = new Map(groupFolders.map((gf) => [gf.id, gf]));
|
||||||
|
const fieldGroupsMap = new Map(fieldGroups.map((fg) => [fg.id, fg]));
|
||||||
|
|
||||||
|
let fieldsToProcess = filteredFields;
|
||||||
|
if (FORCE_REFRESH) {
|
||||||
|
console.log(
|
||||||
|
`\nFORCE_REFRESH=1 — reloading history for all ${fieldsToProcess.length} filtered fields...`
|
||||||
|
);
|
||||||
|
} else if (REFRESH_IF_BEFORE) {
|
||||||
|
const { rows: freshRows } = await pool.query(
|
||||||
|
`
|
||||||
|
SELECT id FROM fields
|
||||||
|
WHERE history_items IS NOT NULL
|
||||||
|
AND EXISTS (
|
||||||
|
SELECT 1 FROM jsonb_array_elements(history_items) h
|
||||||
|
WHERE (h->>'year')::int = 2026
|
||||||
|
AND (h->>'updated_at')::timestamptz >= $1::timestamptz
|
||||||
|
)
|
||||||
|
`,
|
||||||
|
[REFRESH_IF_BEFORE]
|
||||||
|
);
|
||||||
|
const freshIds = new Set(freshRows.map((r) => Number(r.id)));
|
||||||
|
fieldsToProcess = filteredFields.filter((f) => !freshIds.has(f.id));
|
||||||
|
console.log(
|
||||||
|
`\nREFRESH_IF_BEFORE=${REFRESH_IF_BEFORE}: ${fieldsToProcess.length} to refresh` +
|
||||||
|
` (${freshIds.size} already fresh)...`
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
const { rows: existingRows } = await pool.query(
|
||||||
|
`SELECT id FROM fields WHERE history_items IS NOT NULL`
|
||||||
|
);
|
||||||
|
const existingIds = new Set(existingRows.map((r) => Number(r.id)));
|
||||||
|
fieldsToProcess = filteredFields.filter((f) => !existingIds.has(f.id));
|
||||||
|
console.log(
|
||||||
|
`\nProcessing fields and history_items: ${fieldsToProcess.length} to load` +
|
||||||
|
` (${existingIds.size} already in DB, resume)...`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const errors = await mapPool(fieldsToProcess, CONCURRENCY, async (field) => {
|
||||||
|
const historyItems = await fetchAllPages(
|
||||||
|
'/history_items',
|
||||||
|
{ field_id: field.id },
|
||||||
|
{ quiet: true }
|
||||||
|
);
|
||||||
|
const fieldGroup = fieldGroupsMap.get(field.field_group_id);
|
||||||
|
const zoneHierarchy = buildZoneHierarchy(fieldGroup, groupFoldersMap);
|
||||||
|
await upsertField(pool, field, zoneHierarchy, historyItems);
|
||||||
|
});
|
||||||
|
|
||||||
|
console.log(`\nSync complete. Fields upserted this run: ${fieldsToProcess.length - errors.length}`);
|
||||||
|
if (errors.length) {
|
||||||
|
console.log(`Errors: ${errors.length}`);
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
await pool.end();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
sync().catch((err) => {
|
||||||
|
console.error('Sync failed:', err);
|
||||||
|
process.exit(1);
|
||||||
|
});
|
||||||
+350
@@ -0,0 +1,350 @@
|
|||||||
|
const axios = require('axios');
|
||||||
|
const fs = require('fs');
|
||||||
|
const path = require('path');
|
||||||
|
|
||||||
|
class CropwiseAPI {
|
||||||
|
constructor(apiToken, baseUrl = 'https://operations.cropwise.com/api') {
|
||||||
|
this.apiToken = apiToken;
|
||||||
|
this.baseUrl = baseUrl;
|
||||||
|
this.client = axios.create({
|
||||||
|
baseURL: baseUrl,
|
||||||
|
headers: {
|
||||||
|
'X-User-Api-Token': apiToken,
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
'Accept-Encoding': 'gzip',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Получение полей группы с пагинацией (до 10 страниц по 100 записей)
|
||||||
|
*/
|
||||||
|
async getFields({ field_group_id, limit = 100 } = {}) {
|
||||||
|
const maxPages = 10;
|
||||||
|
const allFields = [];
|
||||||
|
let fromId;
|
||||||
|
|
||||||
|
try {
|
||||||
|
for (let page = 0; page < maxPages; page++) {
|
||||||
|
const requestParams = {
|
||||||
|
field_group_id,
|
||||||
|
limit,
|
||||||
|
...(fromId !== undefined && { from_id: fromId }),
|
||||||
|
};
|
||||||
|
const response = await this.client.get('/v3/fields', { params: requestParams });
|
||||||
|
const { data, meta } = response.data;
|
||||||
|
|
||||||
|
if (!data?.length) break;
|
||||||
|
|
||||||
|
allFields.push(...data);
|
||||||
|
|
||||||
|
const obtainedRecords = meta?.response?.obtained_records ?? data.length;
|
||||||
|
const responseLimit = meta?.response?.limit ?? limit;
|
||||||
|
if (obtainedRecords < responseLimit) break;
|
||||||
|
|
||||||
|
const lastRecordId = meta?.response?.last_record_id;
|
||||||
|
if (lastRecordId === undefined) break;
|
||||||
|
|
||||||
|
fromId = lastRecordId;
|
||||||
|
}
|
||||||
|
|
||||||
|
return allFields;
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Ошибка получения полей:', error.response?.data || error.message);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Получение групп полей
|
||||||
|
*/
|
||||||
|
async getFieldGroups(params = {}) {
|
||||||
|
try {
|
||||||
|
const response = await this.client.get('/v3/field_groups', { params });
|
||||||
|
return response.data.data;
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Ошибка получения групп полей:', error.response?.data || error.message);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Получение погодных данных для FieldGroup (v3a - с детальными данными)
|
||||||
|
*/
|
||||||
|
async getWeatherHistory(fieldGroupId, fromTime, toTime) {
|
||||||
|
try {
|
||||||
|
const response = await this.client.get('/v3/weather_history_items', {
|
||||||
|
params: {
|
||||||
|
// weather_historyable_type: 'FieldGroup',
|
||||||
|
// weather_historyable_id: fieldGroupId,
|
||||||
|
field_group_id: fieldGroupId,
|
||||||
|
...(fromTime && { from_time: fromTime }),
|
||||||
|
...(toTime && { to_time: toTime }),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
return response.data.data;
|
||||||
|
} catch (error) {
|
||||||
|
console.error(`Ошибка получения погоды для FieldGroup ${fieldGroupId}. fromTime: ${fromTime}, toTime: ${toTime}:`,
|
||||||
|
error.response?.data || error.message);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Получение погодных данных в формате v3c (с данными по дням)
|
||||||
|
*/
|
||||||
|
async getWeatherHistoryV3c(fieldGroupId, year) {
|
||||||
|
try {
|
||||||
|
const response = await this.client.get('/v3c/weather_history_items', {
|
||||||
|
params: {
|
||||||
|
weather_historyable_type: 'FieldGroup',
|
||||||
|
weather_historyable_id: fieldGroupId,
|
||||||
|
year: year,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
return response.data.data;
|
||||||
|
} catch (error) {
|
||||||
|
console.error(`Ошибка получения погоды для FieldGroup ${fieldGroupId}:`,
|
||||||
|
error.response?.data || error.message);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Получение данных о температуре и осадках по дням для всех полей
|
||||||
|
*/
|
||||||
|
async getDailyWeatherForAllFields(options = {}) {
|
||||||
|
const {
|
||||||
|
fromTime,
|
||||||
|
toTime,
|
||||||
|
year,
|
||||||
|
limit = 1000
|
||||||
|
} = options;
|
||||||
|
const results = {
|
||||||
|
fieldGroups: {},
|
||||||
|
myGroupsIds: [],
|
||||||
|
weatherData: {},
|
||||||
|
fields: {},
|
||||||
|
};
|
||||||
|
// 1. Получаем группы полей для определения привязки
|
||||||
|
console.log('📡 Получение групп полей...');
|
||||||
|
const fieldGroups = await this.getFieldGroups({ limit: 1000 });
|
||||||
|
const fieldGroupsMap = {};
|
||||||
|
fieldGroups.forEach(fg => {
|
||||||
|
fieldGroupsMap[fg.id] = fg;
|
||||||
|
});
|
||||||
|
results.fieldGroups = fieldGroupsMap;
|
||||||
|
console.log(`✅ Найдено групп полей: ${fieldGroups.length}`);
|
||||||
|
|
||||||
|
const myGroupsIds = [1, 49, 50, 51, 52, 53, 54, 55, 86, 87];
|
||||||
|
// const myGroupsIds = [1];
|
||||||
|
results.myGroupsIds = myGroupsIds;
|
||||||
|
|
||||||
|
let yearFieldsWeatherData = [];
|
||||||
|
for (const groupId of myGroupsIds) {
|
||||||
|
|
||||||
|
// 1. получить погоду за год для группы
|
||||||
|
const weatherData = await this.getWeatherHistoryV3c(groupId, year);
|
||||||
|
const parsedWeatherData = this.parseV3cData(weatherData);
|
||||||
|
const fromDate = `${year}-06-01`;
|
||||||
|
const toDate = `${year}-09-01`;
|
||||||
|
results.weatherData[groupId] = parsedWeatherData.filter(w => (w.date >= fromDate && w.date <= toDate));
|
||||||
|
console.log(`✅ Найдено погоды в группе ${groupId}: ${results.weatherData[groupId].length}`);
|
||||||
|
// 2. получить поля в группе
|
||||||
|
const fields = await this.getFields({ field_group_id: groupId });
|
||||||
|
console.log(`✅ Найдено полей в группе ${groupId}: ${fields.length}`, fields[10]);
|
||||||
|
results.fields[groupId] = fields;
|
||||||
|
//2.1 записать поля в файл
|
||||||
|
const fieldsPath = path.join(__dirname, `fields_data_${groupId}.csv`);
|
||||||
|
const fieldsHeader = 'field_group_name;group_id;field_name;field_id';
|
||||||
|
const fieldsRows = results.fields[groupId].map(f => `${fieldGroupsMap[groupId].name};${groupId};${f.name};${f.id}`).join('\n');
|
||||||
|
// fs.writeFileSync(fieldsPath, `${fieldsHeader}\n${fieldsRows}`, 'utf8');
|
||||||
|
console.log(`✅ Поля сохранены в файл ${fieldsPath}`);
|
||||||
|
// 3. сохранить погоду в файл
|
||||||
|
const csvPath = path.join(__dirname, `weather_data_${groupId}.csv`);
|
||||||
|
const weatherHeader = 'field_group_name;group_id;date;temperature_mean;temperature_min;temperature_max;precipitation;snow;wind_speed;humidity';
|
||||||
|
const weatherRows = results.weatherData[groupId].map(w => `${fieldGroupsMap[groupId].name};${groupId};${w.date};${w.temperature_mean};${w.temperature_min};${w.temperature_max};${w.precipitation};${w.snow};${w.wind_speed};${w.humidity}`).join('\n');
|
||||||
|
// fs.writeFileSync(csvPath, `${weatherHeader}\n${weatherRows}`, 'utf8');
|
||||||
|
console.log(`✅ Погода сохранена в файл ${csvPath}`);
|
||||||
|
|
||||||
|
// 4. собрать статистику за год по каждому полю (погода группы × поля)
|
||||||
|
const groupName = fieldGroupsMap[groupId]?.name ?? '';
|
||||||
|
for (const f of fields) {
|
||||||
|
for (const w of results.weatherData[groupId]) {
|
||||||
|
yearFieldsWeatherData.push({
|
||||||
|
field_group_name: groupName,
|
||||||
|
group_id: groupId,
|
||||||
|
field_name: f.name ?? '',
|
||||||
|
field_id: f.id ?? '',
|
||||||
|
date: w.date ?? '',
|
||||||
|
temperature_mean: w.temperature_mean ?? '',
|
||||||
|
temperature_min: w.temperature_min ?? '',
|
||||||
|
temperature_max: w.temperature_max ?? '',
|
||||||
|
precipitation: w.precipitation ?? '',
|
||||||
|
snow: w.snow ?? '',
|
||||||
|
wind_speed: w.wind_speed ?? '',
|
||||||
|
humidity: w.humidity ?? '',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 5. сохранить объединенную статистику за год по всем полям
|
||||||
|
const yearFieldsPath = path.join(__dirname, `year_fields_weather_data_${year}.csv`);
|
||||||
|
const yearFieldsHeader = 'группа;id гуппы;поле;id поля;дата;temperature_mean;temperature_min;temperature_max;precipitation;snow;wind_speed;humidity';
|
||||||
|
const yearFieldsRows = yearFieldsWeatherData
|
||||||
|
.map(r => `${r.field_group_name};${r.group_id};${r.field_name};${r.field_id};${r.date};${r.temperature_mean};${r.temperature_min};${r.temperature_max};${r.precipitation};${r.snow};${r.wind_speed};${r.humidity}`)
|
||||||
|
.join('\n');
|
||||||
|
fs.writeFileSync(yearFieldsPath, `${yearFieldsHeader}\n${yearFieldsRows}`, 'utf8');
|
||||||
|
console.log(`✅ Годовая статистика по полям сохранена в файл ${yearFieldsPath}`);
|
||||||
|
|
||||||
|
return results;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Парсинг данных в формате v3c
|
||||||
|
*/
|
||||||
|
parseV3cData(value) {
|
||||||
|
const dailyData = [];
|
||||||
|
const yearData = value[0].value;
|
||||||
|
for (const day of Object.keys(yearData)) {
|
||||||
|
const item = yearData[day];
|
||||||
|
dailyData.push({
|
||||||
|
date: day,
|
||||||
|
temperature_mean: item.temperature_mean || '',
|
||||||
|
temperature_min: item.temperature_min || '',
|
||||||
|
temperature_max: item.temperature_max || '',
|
||||||
|
precipitation: item.precipitation || '',
|
||||||
|
snow: item.snow || '',
|
||||||
|
wind_speed: item.wind_speed || '',
|
||||||
|
humidity: item.relative_humidity || '',
|
||||||
|
precipitation: item.precipitation || '',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
// Сортируем по дате
|
||||||
|
dailyData.sort((a, b) => a.date.localeCompare(b.date));
|
||||||
|
return dailyData;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Парсинг данных в формате v3a
|
||||||
|
*/
|
||||||
|
parseV3aData(value) {
|
||||||
|
return value.map(item => ({
|
||||||
|
date: item[0],
|
||||||
|
temperature: {
|
||||||
|
mean: item[1] !== undefined ? item[1] : null,
|
||||||
|
min: item[2] !== undefined ? item[2] : null,
|
||||||
|
max: item[3] !== undefined ? item[3] : null,
|
||||||
|
},
|
||||||
|
precipitation: item[4] !== undefined ? item[4] : null,
|
||||||
|
snow: item[5] !== undefined ? item[5] : null,
|
||||||
|
wind_speed: item[6] !== undefined ? item[6] : null,
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Получение данных о температуре и осадках по дням для конкретного поля
|
||||||
|
*/
|
||||||
|
async getDailyWeatherForField(fieldId, options = {}) {
|
||||||
|
const { fromTime, toTime, year } = options;
|
||||||
|
|
||||||
|
// Получаем информацию о поле
|
||||||
|
try {
|
||||||
|
const response = await this.client.get(`/v3/fields/${fieldId}`);
|
||||||
|
const field = response.data.data;
|
||||||
|
|
||||||
|
if (!field.field_group_id) {
|
||||||
|
console.warn(`⚠️ Поле ${fieldId} не привязано к FieldGroup`);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
let weatherData = null;
|
||||||
|
const fieldGroupId = field.field_group_id;
|
||||||
|
|
||||||
|
if (year) {
|
||||||
|
const rawData = await this.getWeatherHistoryV3c(fieldGroupId, year);
|
||||||
|
if (rawData && rawData.length > 0) {
|
||||||
|
weatherData = rawData[0];
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
const rawData = await this.getWeatherHistory(fieldGroupId, fromTime, toTime);
|
||||||
|
if (rawData && rawData.length > 0) {
|
||||||
|
weatherData = rawData[0];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!weatherData) {
|
||||||
|
return {
|
||||||
|
field_id: fieldId,
|
||||||
|
field_name: field.name,
|
||||||
|
field_group_id: fieldGroupId,
|
||||||
|
weather: null,
|
||||||
|
message: 'Данные не найдены',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
let dailyData = null;
|
||||||
|
if (weatherData.value && typeof weatherData.value === 'object' && !Array.isArray(weatherData.value)) {
|
||||||
|
dailyData = this.parseV3cData(weatherData.value);
|
||||||
|
} else if (weatherData.value && Array.isArray(weatherData.value)) {
|
||||||
|
dailyData = this.parseV3aData(weatherData.value);
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
field_id: fieldId,
|
||||||
|
field_name: field.name,
|
||||||
|
field_group_id: fieldGroupId,
|
||||||
|
weather: dailyData,
|
||||||
|
weather_year: weatherData.year || year,
|
||||||
|
};
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
console.error(`Ошибка получения данных для поля ${fieldId}:`, error.message);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ============================================================
|
||||||
|
// ИСПОЛЬЗОВАНИЕ
|
||||||
|
// ============================================================
|
||||||
|
|
||||||
|
async function main() {
|
||||||
|
// Инициализация API клиента
|
||||||
|
const api = new CropwiseAPI('7oA9B7_ZJ4gE1qw4cqzH');
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Вариант 1: Получить данные по всем полям за указанный год
|
||||||
|
console.log('🚀 Запуск получения погодных данных...\n');
|
||||||
|
|
||||||
|
const allFieldsData = await api.getDailyWeatherForAllFields({
|
||||||
|
year: 2022
|
||||||
|
});
|
||||||
|
|
||||||
|
// console.dir(allFieldsData, { depth: null });
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
console.error('❌ Ошибка:', error.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Запуск
|
||||||
|
main();
|
||||||
|
|
||||||
|
// ============================================================
|
||||||
|
// ДОПОЛНИТЕЛЬНЫЙ МЕТОД ДЛЯ ПОЛУЧЕНИЯ ДАННЫХ ПО ПОЛЮ
|
||||||
|
// ============================================================
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Упрощенная функция для получения погодных данных по полю
|
||||||
|
* @param {string} apiToken - API токен
|
||||||
|
* @param {number} fieldId - ID поля
|
||||||
|
* @param {number} year - Год
|
||||||
|
*/
|
||||||
|
async function getWeatherForField(apiToken, fieldId, year = new Date().getFullYear()) {
|
||||||
|
const api = new CropwiseAPI(apiToken);
|
||||||
|
return api.getDailyWeatherForField(fieldId, { year });
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { CropwiseAPI, getWeatherForField };
|
||||||
@@ -0,0 +1,133 @@
|
|||||||
|
Зона (иерархия),ID Поля,Имя поля,Сезон,Культура,Гибрид/сорт,Площадь (га),Урожайность (ц/га),Валовый сбор (т)
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Север -> пр. ""Большевик"" -> пр. ""Большевик"" ПО№5","2142","23-28-КНЛВ-057","2025","Пшеница озимая","Таня, ЭС","133.22804","10.49","139.48"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Север -> пр. ""Большевик"" -> пр. ""Большевик"" ПО№5","2144","23-28-КНЛВ-058","2025","Пшеница озимая","Алексеич, ЭС","86.41144","6.63","57.00"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Север -> пр. ""Большевик"" -> пр. ""Большевик"" ПО№5","2149","23-28-КНЛВ-032","2025","Пшеница озимая","Алексеич, ЭС","87.29314","9.91","86.18"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Север -> пр. ""Большевик"" -> пр. ""Большевик"" ПО№5","2294","23-28-КНЛВ-034","2025","Пшеница озимая","Алексеич, ЭС","36.55571","10.61","39.26"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОСП ""Кавказ"" -> ОСП ""Кавказ"" - ПО2","6238","23-16-СТЕП-009","2025","Кукуруза на зерно","N/A","29.73444","36.71","110.12"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОСП ""Кавказ"" -> ОСП ""Кавказ"" - ПО1","6247","23-16-КУРГ-045","2025","Кукуруза на зерно","N/A","126.90135","51.51","654.16"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОСП ""Кавказ"" -> ОСП ""Кавказ"" - ПО4 (Михайловская)","6294","23-16-МХЛВ-051","2025","Кукуруза на зерно","ДКС 4178","118.01267","N/A","N/A"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОСП ""Кавказ"" -> ОСП ""Кавказ"" - ПО4 (Михайловская)","6297","23-16-МХЛВ-049","2025","Кукуруза на зерно","ДКС 4178","41.30088","N/A","N/A"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОСП ""Кавказ"" -> ОСП ""Кавказ"" - ПО4 (Михайловская)","6326","23-16-МХЛВ-041","2025","Кукуруза на зерно","ДКС 4178","148.85599","N/A","N/A"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОСП ""Кавказ"" -> ОСП ""Кавказ"" - ПО2","6346","23-16-КУРГ-081","2025","Кукуруза на зерно","КЛ7408УМ, КЛ7202МВ","64.62628","N/A","N/A"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОСП ""Кавказ"" -> ОСП ""Кавказ"" - ПО5 (Северный)","6373","23-16-ППАВ-042/уч.2","2025","Кукуруза на зерно","Адэвей","63.55141","N/A","N/A"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Центр -> пр. ""Рассвет"" -> Предприятие ""Рассвет"" ПО 3","7045","23-05-КРУП-089","2025","Кукуруза на зерно","ДКС 4014, КСС 2290, КСС 5291","90.9213","26.35","239.83"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Центр -> пр. ""Рассвет"" -> Предприятие ""Рассвет"" ПО 3","7131","23-05-КРУП-098","2025","Кукуруза на зерно","КСС 2290","90.52703","35.54","323.43"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Центр -> пр. ""Рассвет"" -> Предприятие ""Рассвет"" ПО 3","7140","23-05-КРУП-072","2025","Кукуруза на зерно","КСС 2290","85.32178","29.61","251.68"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Север -> пр. ""Кущевское"" -> ООО ""Октябрь"" -> ПО2 Новосергиевское","11145","23-14-НСРГ-004","2025","Кукуруза на силос и зеленый корм","N/A","73.35477","87.69","640.16"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Север -> пр. ""Кущевское"" -> ООО ""Октябрь"" -> ПО2 Новосергиевское","11152","23-14-НСРГ-018","2025","Горох яровой","Мадонна РС2","89.01653","9.82","87.42"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Север -> пр. ""Кущевское"" -> ООО ""Октябрь"" -> ПО2 Новосергиевское","11153","23-14-НСРГ-022","2025","Горох яровой","Мадонна РС2","90.74663","9.41","85.62"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Север -> пр. ""Кущевское"" -> ООО ""Октябрь"" -> ПО2 Новосергиевское","11171","23-14-НСРГ-006","2025","Горох яровой","Мадонна РС2","116.66194","7.66","89.58"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион РИС -> пр. ""Чебургольское"" -> пр. ""Чебургольское"" -ПО5","11665","23-13-СНЖС-063","2025","Соя","СК Риана","51.15512","13.22","67.40"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион РИС -> пр. ""Чебургольское"" -> пр. ""Чебургольское"" -ПО5","11670","23-13-СНЖС-069","2025","Соя","Вилана","152.31181","11.32","172.00"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12359","26-03-ДИВН-114","2025","Пар","N/A","75.8142","N/A","N/A"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12360","26-03-ДИВН-127","2025","Пшеница озимая","Таня, РС1","78.00789","64.68","504.53"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12361","26-03-ДИВН-129","2025","Пшеница озимая","Таня, РС1","77.36838","53.28","410.29"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12362","26-03-ДИВН-087","2025","Пшеница озимая","Таня, ЭС","77.15332","56.62","435.94"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12363","26-03-ДИВН-093","2025","Пшеница озимая","Таня, ЭС","76.99691","58.53","450.71"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12364","26-03-ДИВН-078","2025","Пар","N/A","128.32389","N/A","N/A"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12365","26-03-ДИВН-136","2025","Пар","N/A","96.89791","N/A","N/A"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12366","26-03-ДИВН-063","2025","Пшеница озимая","Еланчик, РС1","207.73833","55.95","1163.68"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12367","26-03-ДИВН-042","2025","Пар","N/A","89.54959","N/A","N/A"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12368","26-03-ДИВН-052","2025","Пшеница озимая","Еланчик, ЭС","91.14874","52.60","478.68"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12369","26-03-ДИВН-055","2025","Пшеница озимая","Еланчик, ЭС","108.69511","51.23","558.36"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12370","26-03-ДИВН-029","2025","Пшеница озимая","Еланчик, РС1","80.71644","58.20","471.43"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12371","26-03-ДИВН-004","2025","Пар","N/A","75.70805","N/A","N/A"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12372","26-03-ДИВН-012","2025","Пар","N/A","76.81277","N/A","N/A"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12373","26-03-ДИВН-023","2025","Пар","N/A","75.8251","N/A","N/A"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12374","26-03-ДИВН-031","2025","Пшеница озимая","Еланчик, РС1","79.73259","70.41","563.28"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12375","26-03-ДИВН-030","2025","Пшеница озимая","Еланчик, РС1","78.9072","62.53","493.96"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12376","26-03-ДИВН-022","2025","Пар","N/A","76.30411","N/A","N/A"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12377","26-03-ДИВН-018","2025","Пар","N/A","74.65977","N/A","N/A"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12378","26-03-ДИВН-016","2025","Пар","N/A","75.77333","N/A","N/A"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12379","26-03-ДИВН-015","2025","Пар","N/A","61.35622","N/A","N/A"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12380","26-03-ДИВН-001","2025","Пар","N/A","68.01438","N/A","N/A"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12381","26-03-ДИВН-002","2025","Пар","N/A","75.54678","N/A","N/A"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12382","26-03-ДИВН-003","2025","Пар","N/A","77.98019","N/A","N/A"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12383","26-03-ДИВН-005","2025","Пар","N/A","74.27875","N/A","N/A"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12384","26-03-ДИВН-044","2025","Пар","N/A","92.99898","N/A","N/A"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12385","26-03-ДИВН-043","2025","Пар","N/A","98.87678","N/A","N/A"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12386","26-03-ДИВН-046","2025","Пшеница озимая","Еланчик, РС1, Таня, ОС","91.59816","57.06","524.98"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12387","26-03-ДИВН-049","2025","Пшеница озимая","Еланчик, ЭС","90.15868","59.55","535.96"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12388","26-03-ДИВН-050","2025","Пшеница озимая","Еланчик, ЭС","91.08992","55.94","509.04"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12389","26-03-ДИВН-051","2025","Пшеница озимая","Еланчик, ЭС","88.2841","58.09","511.20"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12390","26-03-ДИВН-056","2025","Пшеница озимая","Еланчик, ЭС","75.05107","51.55","386.65"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12391","26-03-ДИВН-054","2025","Пшеница озимая","Еланчик, ЭС","88.24606","56.20","494.57"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12392","26-03-ДИВН-053","2025","Пшеница озимая","Еланчик, ЭС","89.76869","57.12","514.10"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12393","26-03-ДИВН-091","2025","Пшеница озимая","Таня, ЭС","78.52942","60.07","474.52"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12394","26-03-ДИВН-090","2025","Пшеница озимая","Таня, ЭС","77.16892","61.51","473.62"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12395","26-03-ДИВН-089","2025","Пшеница озимая","Таня, ЭС","76.80507","56.85","437.78"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12396","26-03-ДИВН-088","2025","Пшеница озимая","Таня, ЭС","76.76631","59.54","458.48"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12397","26-03-ДИВН-086","2025","Пшеница озимая","Таня, ЭС","75.91765","63.29","481.00"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12398","26-03-ДИВН-103","2025","Пар","N/A","74.61086","N/A","N/A"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12399","26-03-ДИВН-102","2025","Пар","N/A","75.83412","N/A","N/A"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12400","26-03-ДИВН-101","2025","Пар","N/A","75.15119","N/A","N/A"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12401","26-03-ДИВН-100","2025","Пар","N/A","74.45783","N/A","N/A"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12402","26-03-ДИВН-098","2025","Пар","N/A","67.64906","N/A","N/A"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12403","26-03-ДИВН-097","2025","Пшеница озимая","Таня, ЭС","77.30325","63.83","491.50"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12404","26-03-ДИВН-096","2025","Пшеница озимая","Таня, ЭС","75.76796","64.10","487.15"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12405","26-03-ДИВН-095","2025","Пшеница озимая","Таня, ЭС","77.29626","60.87","468.67"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12406","26-03-ДИВН-094","2025","Пшеница озимая","Таня, ЭС","77.00115","58.48","450.28"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12407","26-03-ДИВН-092","2025","Пшеница озимая","Таня, ЭС","76.66763","56.92","438.28"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12408","26-03-ДИВН-110","2025","Пар","N/A","77.53622","N/A","N/A"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12409","26-03-ДИВН-111","2025","Пар","N/A","75.23374","N/A","N/A"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12410","26-03-ДИВН-112","2025","Пар","N/A","75.37482","N/A","N/A"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12411","26-03-ДИВН-113","2025","Пар","N/A","75.3835","N/A","N/A"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12412","26-03-ДИВН-115","2025","Пар","N/A","74.99895","N/A","N/A"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12413","26-03-ДИВН-116","2025","Пар","N/A","74.91313","N/A","N/A"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12414","26-03-ДИВН-117","2025","Пар","N/A","75.50088","N/A","N/A"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12415","26-03-ДИВН-118","2025","Пар","N/A","73.92469","N/A","N/A"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12416","26-03-ДИВН-119","2025","Пар","N/A","75.86783","N/A","N/A"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12417","26-03-ДИВН-120","2025","Пар","N/A","74.91037","N/A","N/A"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12418","26-03-ДИВН-121","2025","Пар","N/A","74.27384","N/A","N/A"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12419","26-03-ДИВН-123","2025","Пшеница озимая","Таня, РС1","74.14226","57.73","427.23"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12420","26-03-ДИВН-122","2025","Пшеница озимая","Таня, РС1","74.64285","57.68","432.61"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12421","26-03-ДИВН-124","2025","Пшеница озимая","Таня, РС1","73.34628","56.85","415.02"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12422","26-03-ДИВН-125","2025","Пшеница озимая","Таня, РС1","73.81899","54.16","400.75"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12423","26-03-ДИВН-126","2025","Пшеница озимая","Таня, РС1","73.29094","59.01","430.78"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12424","26-03-ДИВН-128","2025","Пшеница озимая","Таня, РС1","75.8592","53.36","405.56"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12425","26-03-ДИВН-130","2025","Пшеница озимая","Таня, РС1","74.83604","53.67","402.55"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12426","26-03-ДИВН-131","2025","Пшеница озимая","Таня, РС1","77.62159","53.60","418.06"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12427","26-03-ДИВН-133","2025","Пшеница озимая","Таня, РС1","72.08088","52.01","374.47"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12428","26-03-ДИВН-132","2025","Пшеница озимая","Таня, РС1","76.20338","50.19","381.45"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12429","26-03-ДИВН-072","2025","Пшеница озимая","Победа 75 РС-1","248.61377","N/A","N/A"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12430","26-03-ДИВН-013","2025","Пар","N/A","75.86074","N/A","N/A"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12431","26-03-ДИВН-014","2025","Пар","N/A","73.91504","N/A","N/A"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12432","26-03-ДИВН-033","2025","Пшеница озимая","Еланчик, РС1","65.04404","68.49","445.21"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12433","26-03-ДИВН-032","2025","Пшеница озимая","Еланчик, РС1","73.57399","67.88","502.32"
|
||||||
|
7","26-03-ДИВН-133","2025","Пшеница озимая","Таня, РС1","72.08088","52.01","374.47"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12428","26-03-ДИВН-132","2025","Пшеница озимая","Таня, РС1","76.20338","50.19","381.45"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12429","26-03-ДИВН-072","2025","Пшеница озимая","Победа 75 РС-1","248.61377","N/A","N/A"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12430","26-03-ДИВН-013","2025","Пар","N/A","75.86074","N/A","N/A"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12431","26-03-ДИВН-014","2025","Пар","N/A","73.91504","N/A","N/A"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12432","26-03-ДИВН-033","2025","Пшеница озимая","Еланчик, РС1","65.04404","68.49","445.21"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12433","26-03-ДИВН-032","2025","Пшеница озимая","Еланчик, РС1","73.57399","67.88","502.32"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12428","26-03-ДИВН-132","2025","Пшеница озимая","Таня, РС1","76.20338","50.19","381.45"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12429","26-03-ДИВН-072","2025","Пшеница озимая","Победа 75 РС-1","248.61377","N/A","N/A"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12430","26-03-ДИВН-013","2025","Пар","N/A","75.86074","N/A","N/A"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12431","26-03-ДИВН-014","2025","Пар","N/A","73.91504","N/A","N/A"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12432","26-03-ДИВН-033","2025","Пшеница озимая","Еланчик, РС1","65.04404","68.49","445.21"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12433","26-03-ДИВН-032","2025","Пшеница озимая","Еланчик, РС1","73.57399","67.88","502.32"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12430","26-03-ДИВН-013","2025","Пар","N/A","75.86074","N/A","N/A"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12431","26-03-ДИВН-014","2025","Пар","N/A","73.91504","N/A","N/A"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12432","26-03-ДИВН-033","2025","Пшеница озимая","Еланчик, РС1","65.04404","68.49","445.21"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12433","26-03-ДИВН-032","2025","Пшеница озимая","Еланчик, РС1","73.57399","67.88","502.32"
|
||||||
|
0","26-03-ДИВН-013","2025","Пар","N/A","75.86074","N/A","N/A"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12431","26-03-ДИВН-014","2025","Пар","N/A","73.91504","N/A","N/A"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12432","26-03-ДИВН-033","2025","Пшеница озимая","Еланчик, РС1","65.04404","68.49","445.21"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12433","26-03-ДИВН-032","2025","Пшеница озимая","Еланчик, РС1","73.57399","67.88","502.32"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12431","26-03-ДИВН-014","2025","Пар","N/A","73.91504","N/A","N/A"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12432","26-03-ДИВН-033","2025","Пшеница озимая","Еланчик, РС1","65.04404","68.49","445.21"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12433","26-03-ДИВН-032","2025","Пшеница озимая","Еланчик, РС1","73.57399","67.88","502.32"
|
||||||
|
1","26-03-ДИВН-014","2025","Пар","N/A","73.91504","N/A","N/A"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12432","26-03-ДИВН-033","2025","Пшеница озимая","Еланчик, РС1","65.04404","68.49","445.21"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12433","26-03-ДИВН-032","2025","Пшеница озимая","Еланчик, РС1","73.57399","67.88","502.32"
|
||||||
|
2","26-03-ДИВН-033","2025","Пшеница озимая","Еланчик, РС1","65.04404","68.49","445.21"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12433","26-03-ДИВН-032","2025","Пшеница озимая","Еланчик, РС1","73.57399","67.88","502.32"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12434","26-03-ДИВН-039","2025","Пшеница озимая","Еланчик, РС1","67.63178","54.15","368.24"
|
||||||
|
3","26-03-ДИВН-032","2025","Пшеница озимая","Еланчик, РС1","73.57399","67.88","502.32"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12434","26-03-ДИВН-039","2025","Пшеница озимая","Еланчик, РС1","67.63178","54.15","368.24"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","1243"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12434","26-03-ДИВН-039","2025","Пшеница озимая","Еланчик, РС1","67.63178","54.15","368.24"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12435","26-03-ДИВН-038","2025","Пшеница озимая","Еланчик, РС1","69.16333","50.94","351.52"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12435","26-03-ДИВН-038","2025","Пшеница озимая","Еланчик, РС1","69.16333","50.94","351.52"
|
||||||
|
5","26-03-ДИВН-038","2025","Пшеница озимая","Еланчик, РС1","69.16333","50.94","351.52"
|
||||||
|
"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","1243"АО фирма ""Агрокомплекс"" им. Н.И.Ткачева -> Дивизион Новокубанский -> ОП ""Айгурский"" -> ПО1 ОП Айгурский","12436","26-03-ДИВН-041","2025","Пар","N/A","89.30344","N/A","N/A"
|
||||||
|
Can't render this file because it contains an unexpected character in line 16 and column 337.
|
@@ -0,0 +1,289 @@
|
|||||||
|
/**
|
||||||
|
* Загрузка data/fertilizer_field_final_utf.csv → ak_fields.fertilizer_field_acts
|
||||||
|
* Связь с fields по имени поля (field_name ↔ fields.name → field_id).
|
||||||
|
*
|
||||||
|
* Запуск: node load_fertilizer_field.js
|
||||||
|
*/
|
||||||
|
require('dotenv').config();
|
||||||
|
const fs = require('fs');
|
||||||
|
const path = require('path');
|
||||||
|
const { Client } = require('pg');
|
||||||
|
|
||||||
|
const CSV_PATH = path.join(
|
||||||
|
__dirname,
|
||||||
|
'data',
|
||||||
|
process.env.FERT_CSV || 'fertilizer_field_final_utf.csv'
|
||||||
|
);
|
||||||
|
const BATCH = Number(process.env.FERT_BATCH || 500);
|
||||||
|
|
||||||
|
function parseNum(s) {
|
||||||
|
if (s == null || s === '') return null;
|
||||||
|
const n = Number(String(s).trim().replace(/\s/g, '').replace(',', '.'));
|
||||||
|
return Number.isFinite(n) ? n : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseIntSafe(s) {
|
||||||
|
const n = parseNum(s);
|
||||||
|
if (n == null) return null;
|
||||||
|
return Math.round(n);
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseCsvLine(line) {
|
||||||
|
const out = [];
|
||||||
|
let cur = '';
|
||||||
|
let inQ = false;
|
||||||
|
for (let i = 0; i < line.length; i++) {
|
||||||
|
const ch = line[i];
|
||||||
|
if (ch === '"') {
|
||||||
|
if (inQ && line[i + 1] === '"') {
|
||||||
|
cur += '"';
|
||||||
|
i++;
|
||||||
|
} else inQ = !inQ;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (ch === ';' && !inQ) {
|
||||||
|
out.push(cur);
|
||||||
|
cur = '';
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
cur += ch;
|
||||||
|
}
|
||||||
|
out.push(cur);
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
function emptyToNull(s) {
|
||||||
|
if (s == null) return null;
|
||||||
|
const t = String(s).trim();
|
||||||
|
return t === '' ? null : t;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function ensureTable(client) {
|
||||||
|
await client.query(`
|
||||||
|
CREATE TABLE IF NOT EXISTS fertilizer_field_acts (
|
||||||
|
id BIGSERIAL PRIMARY KEY,
|
||||||
|
field_name TEXT NOT NULL,
|
||||||
|
field_id BIGINT REFERENCES fields(id) ON DELETE SET NULL,
|
||||||
|
year INTEGER NOT NULL,
|
||||||
|
crop TEXT,
|
||||||
|
nomenclature TEXT,
|
||||||
|
area_ha DOUBLE PRECISION,
|
||||||
|
acts_count INTEGER,
|
||||||
|
acts_with_dv INTEGER,
|
||||||
|
yield_category TEXT,
|
||||||
|
stability_category TEXT,
|
||||||
|
yield_index_min DOUBLE PRECISION,
|
||||||
|
yield_index_max DOUBLE PRECISION,
|
||||||
|
stability_std_min DOUBLE PRECISION,
|
||||||
|
stability_std_max DOUBLE PRECISION,
|
||||||
|
fertilizer_mass_kg_ha DOUBLE PRECISION,
|
||||||
|
manure_kg_ha DOUBLE PRECISION,
|
||||||
|
n_kg_ha DOUBLE PRECISION,
|
||||||
|
p2o5_kg_ha DOUBLE PRECISION,
|
||||||
|
k2o_kg_ha DOUBLE PRECISION,
|
||||||
|
productivity DOUBLE PRECISION,
|
||||||
|
loaded_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||||
|
)
|
||||||
|
`);
|
||||||
|
|
||||||
|
await client.query(`
|
||||||
|
CREATE INDEX IF NOT EXISTS fertilizer_field_acts_field_name_idx
|
||||||
|
ON fertilizer_field_acts (field_name)
|
||||||
|
`);
|
||||||
|
await client.query(`
|
||||||
|
CREATE INDEX IF NOT EXISTS fertilizer_field_acts_field_id_idx
|
||||||
|
ON fertilizer_field_acts (field_id)
|
||||||
|
`);
|
||||||
|
await client.query(`
|
||||||
|
CREATE INDEX IF NOT EXISTS fertilizer_field_acts_year_idx
|
||||||
|
ON fertilizer_field_acts (year)
|
||||||
|
`);
|
||||||
|
await client.query(`
|
||||||
|
CREATE INDEX IF NOT EXISTS fertilizer_field_acts_crop_idx
|
||||||
|
ON fertilizer_field_acts (crop)
|
||||||
|
`);
|
||||||
|
await client.query(`
|
||||||
|
CREATE INDEX IF NOT EXISTS fertilizer_field_acts_year_crop_idx
|
||||||
|
ON fertilizer_field_acts (year, crop)
|
||||||
|
`);
|
||||||
|
|
||||||
|
await client.query(`
|
||||||
|
CREATE OR REPLACE VIEW v_fertilizer_field AS
|
||||||
|
SELECT
|
||||||
|
a.*,
|
||||||
|
NULLIF(trim(both FROM split_part(f.zone_hierarchy, ' -> ', 2)), '') AS division,
|
||||||
|
NULLIF(trim(both FROM split_part(f.zone_hierarchy, ' -> ', 3)), '') AS enterprise,
|
||||||
|
NULLIF(trim(both FROM split_part(f.zone_hierarchy, ' -> ', 4)), '') AS unit,
|
||||||
|
f.calculated_area AS field_area_ha,
|
||||||
|
f.zone_hierarchy,
|
||||||
|
c.yield_category_rules AS cluster_yield_category,
|
||||||
|
c.stability_category AS cluster_stability_category,
|
||||||
|
c.yield_index_median AS cluster_yield_index,
|
||||||
|
c.stability_std AS cluster_stability_std
|
||||||
|
FROM fertilizer_field_acts a
|
||||||
|
LEFT JOIN fields f ON f.id = a.field_id
|
||||||
|
LEFT JOIN fields_clustered_all c ON c.field_id = a.field_id
|
||||||
|
`);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function insertBatch(client, rows) {
|
||||||
|
if (!rows.length) return;
|
||||||
|
const cols = 20;
|
||||||
|
const values = [];
|
||||||
|
const params = [];
|
||||||
|
let p = 1;
|
||||||
|
for (const r of rows) {
|
||||||
|
const placeholders = [];
|
||||||
|
for (let i = 0; i < cols; i++) placeholders.push(`$${p++}`);
|
||||||
|
values.push(`(${placeholders.join(',')})`);
|
||||||
|
params.push(
|
||||||
|
r.field_name,
|
||||||
|
r.year,
|
||||||
|
r.crop,
|
||||||
|
r.nomenclature,
|
||||||
|
r.area_ha,
|
||||||
|
r.acts_count,
|
||||||
|
r.acts_with_dv,
|
||||||
|
r.yield_category,
|
||||||
|
r.stability_category,
|
||||||
|
r.yield_index_min,
|
||||||
|
r.yield_index_max,
|
||||||
|
r.stability_std_min,
|
||||||
|
r.stability_std_max,
|
||||||
|
r.fertilizer_mass_kg_ha,
|
||||||
|
r.manure_kg_ha,
|
||||||
|
r.n_kg_ha,
|
||||||
|
r.p2o5_kg_ha,
|
||||||
|
r.k2o_kg_ha,
|
||||||
|
r.productivity,
|
||||||
|
r.loaded_at
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
await client.query(
|
||||||
|
`
|
||||||
|
INSERT INTO fertilizer_field_acts (
|
||||||
|
field_name, year, crop, nomenclature, area_ha,
|
||||||
|
acts_count, acts_with_dv, yield_category, stability_category,
|
||||||
|
yield_index_min, yield_index_max, stability_std_min, stability_std_max,
|
||||||
|
fertilizer_mass_kg_ha, manure_kg_ha, n_kg_ha, p2o5_kg_ha, k2o_kg_ha,
|
||||||
|
productivity, loaded_at
|
||||||
|
) VALUES ${values.join(',')}
|
||||||
|
`,
|
||||||
|
params
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function main() {
|
||||||
|
if (!fs.existsSync(CSV_PATH)) {
|
||||||
|
console.error('CSV not found:', CSV_PATH);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
const client = new Client({
|
||||||
|
host: process.env.PGHOST,
|
||||||
|
port: Number(process.env.PGPORT || 5432),
|
||||||
|
database: process.env.PGDATABASE || 'ak_fields',
|
||||||
|
user: process.env.PGUSER,
|
||||||
|
password: process.env.PGPASSWORD,
|
||||||
|
});
|
||||||
|
await client.connect();
|
||||||
|
console.log('Connected to', process.env.PGDATABASE, '@', process.env.PGHOST);
|
||||||
|
|
||||||
|
await ensureTable(client);
|
||||||
|
|
||||||
|
console.log('Truncating fertilizer_field_acts...');
|
||||||
|
await client.query('TRUNCATE fertilizer_field_acts RESTART IDENTITY');
|
||||||
|
|
||||||
|
const raw = fs.readFileSync(CSV_PATH, 'utf8');
|
||||||
|
const lines = raw.replace(/^\uFEFF/, '').split(/\r?\n/).filter((l) => l.trim());
|
||||||
|
if (lines.length < 2) {
|
||||||
|
console.error('CSV empty');
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
const header = parseCsvLine(lines[0]);
|
||||||
|
console.log('Header columns:', header.length);
|
||||||
|
console.log('Loading', lines.length - 1, 'rows from', path.basename(CSV_PATH));
|
||||||
|
|
||||||
|
const loadedAt = new Date().toISOString();
|
||||||
|
let batch = [];
|
||||||
|
let inserted = 0;
|
||||||
|
let skipped = 0;
|
||||||
|
|
||||||
|
for (let i = 1; i < lines.length; i++) {
|
||||||
|
const c = parseCsvLine(lines[i]);
|
||||||
|
if (c.length < 19) {
|
||||||
|
skipped += 1;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const fieldName = emptyToNull(c[0]);
|
||||||
|
const year = parseIntSafe(c[1]);
|
||||||
|
if (!fieldName || year == null) {
|
||||||
|
skipped += 1;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
batch.push({
|
||||||
|
field_name: fieldName,
|
||||||
|
year,
|
||||||
|
crop: emptyToNull(c[2]),
|
||||||
|
nomenclature: emptyToNull(c[3]),
|
||||||
|
area_ha: parseNum(c[4]),
|
||||||
|
acts_count: parseIntSafe(c[5]),
|
||||||
|
acts_with_dv: parseIntSafe(c[6]),
|
||||||
|
yield_category: emptyToNull(c[7]),
|
||||||
|
stability_category: emptyToNull(c[8]),
|
||||||
|
yield_index_min: parseNum(c[9]),
|
||||||
|
yield_index_max: parseNum(c[10]),
|
||||||
|
stability_std_min: parseNum(c[11]),
|
||||||
|
stability_std_max: parseNum(c[12]),
|
||||||
|
fertilizer_mass_kg_ha: parseNum(c[13]),
|
||||||
|
manure_kg_ha: parseNum(c[14]),
|
||||||
|
n_kg_ha: parseNum(c[15]),
|
||||||
|
p2o5_kg_ha: parseNum(c[16]),
|
||||||
|
k2o_kg_ha: parseNum(c[17]),
|
||||||
|
productivity: parseNum(c[18]),
|
||||||
|
loaded_at: loadedAt,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (batch.length >= BATCH) {
|
||||||
|
await insertBatch(client, batch);
|
||||||
|
inserted += batch.length;
|
||||||
|
batch = [];
|
||||||
|
if (inserted % 5000 === 0) console.log(' inserted', inserted);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (batch.length) {
|
||||||
|
await insertBatch(client, batch);
|
||||||
|
inserted += batch.length;
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log('Linking field_id by fields.name...');
|
||||||
|
const link = await client.query(`
|
||||||
|
UPDATE fertilizer_field_acts a
|
||||||
|
SET field_id = f.id
|
||||||
|
FROM fields f
|
||||||
|
WHERE a.field_id IS NULL
|
||||||
|
AND f.name = a.field_name
|
||||||
|
`);
|
||||||
|
console.log(' linked rows:', link.rowCount);
|
||||||
|
|
||||||
|
const stats = await client.query(`
|
||||||
|
SELECT
|
||||||
|
COUNT(*)::int AS rows,
|
||||||
|
COUNT(DISTINCT field_name)::int AS fields,
|
||||||
|
COUNT(field_id)::int AS linked_rows,
|
||||||
|
COUNT(DISTINCT field_id)::int AS linked_fields,
|
||||||
|
MIN(year) AS year_min,
|
||||||
|
MAX(year) AS year_max
|
||||||
|
FROM fertilizer_field_acts
|
||||||
|
`);
|
||||||
|
console.log('Done:', stats.rows[0], 'skipped lines:', skipped);
|
||||||
|
await client.end();
|
||||||
|
}
|
||||||
|
|
||||||
|
main().catch((e) => {
|
||||||
|
console.error(e);
|
||||||
|
process.exit(1);
|
||||||
|
});
|
||||||
Generated
+507
@@ -0,0 +1,507 @@
|
|||||||
|
{
|
||||||
|
"name": "cropwise_weather",
|
||||||
|
"version": "1.0.0",
|
||||||
|
"lockfileVersion": 3,
|
||||||
|
"requires": true,
|
||||||
|
"packages": {
|
||||||
|
"": {
|
||||||
|
"name": "cropwise_weather",
|
||||||
|
"version": "1.0.0",
|
||||||
|
"license": "ISC",
|
||||||
|
"dependencies": {
|
||||||
|
"axios": "^1.18.1",
|
||||||
|
"dotenv": "^17.4.2",
|
||||||
|
"pg": "^8.23.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/agent-base": {
|
||||||
|
"version": "6.0.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/agent-base/-/agent-base-6.0.2.tgz",
|
||||||
|
"integrity": "sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"debug": "4"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">= 6.0.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/asynckit": {
|
||||||
|
"version": "0.4.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz",
|
||||||
|
"integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==",
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
|
"node_modules/axios": {
|
||||||
|
"version": "1.18.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/axios/-/axios-1.18.1.tgz",
|
||||||
|
"integrity": "sha512-3nTvFlvpn9Zu/RkHUqtc7/+al4UpRW5az71ap5zccp6e8RAYEzhMTecX8Dz1wWDYrPpUoB1HAQEGEAEvUr7S9g==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"follow-redirects": "^1.16.0",
|
||||||
|
"form-data": "^4.0.5",
|
||||||
|
"https-proxy-agent": "^5.0.1",
|
||||||
|
"proxy-from-env": "^2.1.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/call-bind-apply-helpers": {
|
||||||
|
"version": "1.0.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz",
|
||||||
|
"integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"es-errors": "^1.3.0",
|
||||||
|
"function-bind": "^1.1.2"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">= 0.4"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/combined-stream": {
|
||||||
|
"version": "1.0.8",
|
||||||
|
"resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz",
|
||||||
|
"integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"delayed-stream": "~1.0.0"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">= 0.8"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/debug": {
|
||||||
|
"version": "4.4.3",
|
||||||
|
"resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",
|
||||||
|
"integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"ms": "^2.1.3"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=6.0"
|
||||||
|
},
|
||||||
|
"peerDependenciesMeta": {
|
||||||
|
"supports-color": {
|
||||||
|
"optional": true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/delayed-stream": {
|
||||||
|
"version": "1.0.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz",
|
||||||
|
"integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==",
|
||||||
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=0.4.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/dotenv": {
|
||||||
|
"version": "17.4.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/dotenv/-/dotenv-17.4.2.tgz",
|
||||||
|
"integrity": "sha512-nI4U3TottKAcAD9LLud4Cb7b2QztQMUEfHbvhTH09bqXTxnSie8WnjPALV/WMCrJZ6UV/qHJ6L03OqO3LcdYZw==",
|
||||||
|
"license": "BSD-2-Clause",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=12"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"url": "https://dotenvx.com"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/dunder-proto": {
|
||||||
|
"version": "1.0.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz",
|
||||||
|
"integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"call-bind-apply-helpers": "^1.0.1",
|
||||||
|
"es-errors": "^1.3.0",
|
||||||
|
"gopd": "^1.2.0"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">= 0.4"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/es-define-property": {
|
||||||
|
"version": "1.0.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz",
|
||||||
|
"integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==",
|
||||||
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"node": ">= 0.4"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/es-errors": {
|
||||||
|
"version": "1.3.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz",
|
||||||
|
"integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==",
|
||||||
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"node": ">= 0.4"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/es-object-atoms": {
|
||||||
|
"version": "1.1.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.2.tgz",
|
||||||
|
"integrity": "sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"es-errors": "^1.3.0"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">= 0.4"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/es-set-tostringtag": {
|
||||||
|
"version": "2.1.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/es-set-tostringtag/-/es-set-tostringtag-2.1.0.tgz",
|
||||||
|
"integrity": "sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"es-errors": "^1.3.0",
|
||||||
|
"get-intrinsic": "^1.2.6",
|
||||||
|
"has-tostringtag": "^1.0.2",
|
||||||
|
"hasown": "^2.0.2"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">= 0.4"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/follow-redirects": {
|
||||||
|
"version": "1.16.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.16.0.tgz",
|
||||||
|
"integrity": "sha512-y5rN/uOsadFT/JfYwhxRS5R7Qce+g3zG97+JrtFZlC9klX/W5hD7iiLzScI4nZqUS7DNUdhPgw4xI8W2LuXlUw==",
|
||||||
|
"funding": [
|
||||||
|
{
|
||||||
|
"type": "individual",
|
||||||
|
"url": "https://github.com/sponsors/RubenVerborgh"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=4.0"
|
||||||
|
},
|
||||||
|
"peerDependenciesMeta": {
|
||||||
|
"debug": {
|
||||||
|
"optional": true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/form-data": {
|
||||||
|
"version": "4.0.6",
|
||||||
|
"resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.6.tgz",
|
||||||
|
"integrity": "sha512-vKatAh4SlVfgbv+YtmhiRjhEMJsYpsG1Y2rMQtR+SVSbytsSD1YGzDIcrAJmdFec88u/+VoGmxnl+80gL1tRCQ==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"asynckit": "^0.4.0",
|
||||||
|
"combined-stream": "^1.0.8",
|
||||||
|
"es-set-tostringtag": "^2.1.0",
|
||||||
|
"hasown": "^2.0.4",
|
||||||
|
"mime-types": "^2.1.35"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">= 6"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/function-bind": {
|
||||||
|
"version": "1.1.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz",
|
||||||
|
"integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==",
|
||||||
|
"license": "MIT",
|
||||||
|
"funding": {
|
||||||
|
"url": "https://github.com/sponsors/ljharb"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/get-intrinsic": {
|
||||||
|
"version": "1.3.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz",
|
||||||
|
"integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"call-bind-apply-helpers": "^1.0.2",
|
||||||
|
"es-define-property": "^1.0.1",
|
||||||
|
"es-errors": "^1.3.0",
|
||||||
|
"es-object-atoms": "^1.1.1",
|
||||||
|
"function-bind": "^1.1.2",
|
||||||
|
"get-proto": "^1.0.1",
|
||||||
|
"gopd": "^1.2.0",
|
||||||
|
"has-symbols": "^1.1.0",
|
||||||
|
"hasown": "^2.0.2",
|
||||||
|
"math-intrinsics": "^1.1.0"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">= 0.4"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"url": "https://github.com/sponsors/ljharb"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/get-proto": {
|
||||||
|
"version": "1.0.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz",
|
||||||
|
"integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"dunder-proto": "^1.0.1",
|
||||||
|
"es-object-atoms": "^1.0.0"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">= 0.4"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/gopd": {
|
||||||
|
"version": "1.2.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz",
|
||||||
|
"integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==",
|
||||||
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"node": ">= 0.4"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"url": "https://github.com/sponsors/ljharb"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/has-symbols": {
|
||||||
|
"version": "1.1.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz",
|
||||||
|
"integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==",
|
||||||
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"node": ">= 0.4"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"url": "https://github.com/sponsors/ljharb"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/has-tostringtag": {
|
||||||
|
"version": "1.0.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.2.tgz",
|
||||||
|
"integrity": "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"has-symbols": "^1.0.3"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">= 0.4"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"url": "https://github.com/sponsors/ljharb"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/hasown": {
|
||||||
|
"version": "2.0.4",
|
||||||
|
"resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.4.tgz",
|
||||||
|
"integrity": "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"function-bind": "^1.1.2"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">= 0.4"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/https-proxy-agent": {
|
||||||
|
"version": "5.0.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-5.0.1.tgz",
|
||||||
|
"integrity": "sha512-dFcAjpTQFgoLMzC2VwU+C/CbS7uRL0lWmxDITmqm7C+7F0Odmj6s9l6alZc6AELXhrnggM2CeWSXHGOdX2YtwA==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"agent-base": "6",
|
||||||
|
"debug": "4"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">= 6"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/math-intrinsics": {
|
||||||
|
"version": "1.1.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz",
|
||||||
|
"integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==",
|
||||||
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"node": ">= 0.4"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/mime-db": {
|
||||||
|
"version": "1.52.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz",
|
||||||
|
"integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==",
|
||||||
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"node": ">= 0.6"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/mime-types": {
|
||||||
|
"version": "2.1.35",
|
||||||
|
"resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz",
|
||||||
|
"integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"mime-db": "1.52.0"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">= 0.6"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/ms": {
|
||||||
|
"version": "2.1.3",
|
||||||
|
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
|
||||||
|
"integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
|
"node_modules/pg": {
|
||||||
|
"version": "8.23.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/pg/-/pg-8.23.0.tgz",
|
||||||
|
"integrity": "sha512-Ip2EQCngowJLGOfCwkFhPXU7/ljlhn6Rxlmy4XYfL2Y+vyRM59+8uR2xqRWKdYmbXmxCFOAmKxBuSUCdF34qLg==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"pg-connection-string": "^2.14.0",
|
||||||
|
"pg-pool": "^3.14.0",
|
||||||
|
"pg-protocol": "^1.16.0",
|
||||||
|
"pg-types": "2.2.0",
|
||||||
|
"pgpass": "1.0.5"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">= 16.0.0"
|
||||||
|
},
|
||||||
|
"optionalDependencies": {
|
||||||
|
"pg-cloudflare": "^1.4.0"
|
||||||
|
},
|
||||||
|
"peerDependencies": {
|
||||||
|
"pg-native": ">=3.0.1"
|
||||||
|
},
|
||||||
|
"peerDependenciesMeta": {
|
||||||
|
"pg-native": {
|
||||||
|
"optional": true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/pg-cloudflare": {
|
||||||
|
"version": "1.4.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/pg-cloudflare/-/pg-cloudflare-1.4.0.tgz",
|
||||||
|
"integrity": "sha512-Vo7z/6rrQYxpNRylp4Tlob2elzbh+N/MOQbxFVWCxS7oEx6jF53GTJFxK2WWpKuBRkmiin4Mt+xofFDjx09R0A==",
|
||||||
|
"license": "MIT",
|
||||||
|
"optional": true
|
||||||
|
},
|
||||||
|
"node_modules/pg-connection-string": {
|
||||||
|
"version": "2.14.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/pg-connection-string/-/pg-connection-string-2.14.0.tgz",
|
||||||
|
"integrity": "sha512-XwWDGcLRGCXAR8F/AM5bG7Q+A3Wm2s6QeEjlOKZLlH3UYcguiqCWKyWXVag5TLTIjR7oOJUY8kcADaZgWPyLeg==",
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
|
"node_modules/pg-int8": {
|
||||||
|
"version": "1.0.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/pg-int8/-/pg-int8-1.0.1.tgz",
|
||||||
|
"integrity": "sha512-WCtabS6t3c8SkpDBUlb1kjOs7l66xsGdKpIPZsg4wR+B3+u9UAum2odSsF9tnvxg80h4ZxLWMy4pRjOsFIqQpw==",
|
||||||
|
"license": "ISC",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=4.0.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/pg-pool": {
|
||||||
|
"version": "3.14.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/pg-pool/-/pg-pool-3.14.0.tgz",
|
||||||
|
"integrity": "sha512-gKtPkFdQPU3DksooVLi9LsjZxrsBUZIpa+7aVx+LV5pNh0KzP4Zleud2po+ConrxbuXGBJ6Hfer6hdgpIBpBaw==",
|
||||||
|
"license": "MIT",
|
||||||
|
"peerDependencies": {
|
||||||
|
"pg": ">=8.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/pg-protocol": {
|
||||||
|
"version": "1.16.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/pg-protocol/-/pg-protocol-1.16.0.tgz",
|
||||||
|
"integrity": "sha512-sILXutLVjCLjcDuOmvhX5e2Z4cS5qG/6Bu3VkpFwdf/633ElGLpEh9bgmuI5I4sqKqkifQiGyiCcx1HdtrK7tg==",
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
|
"node_modules/pg-types": {
|
||||||
|
"version": "2.2.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/pg-types/-/pg-types-2.2.0.tgz",
|
||||||
|
"integrity": "sha512-qTAAlrEsl8s4OiEQY69wDvcMIdQN6wdz5ojQiOy6YRMuynxenON0O5oCpJI6lshc6scgAY8qvJ2On/p+CXY0GA==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"pg-int8": "1.0.1",
|
||||||
|
"postgres-array": "~2.0.0",
|
||||||
|
"postgres-bytea": "~1.0.0",
|
||||||
|
"postgres-date": "~1.0.4",
|
||||||
|
"postgres-interval": "^1.1.0"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=4"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/pgpass": {
|
||||||
|
"version": "1.0.5",
|
||||||
|
"resolved": "https://registry.npmjs.org/pgpass/-/pgpass-1.0.5.tgz",
|
||||||
|
"integrity": "sha512-FdW9r/jQZhSeohs1Z3sI1yxFQNFvMcnmfuj4WBMUTxOrAyLMaTcE1aAMBiTlbMNaXvBCQuVi0R7hd8udDSP7ug==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"split2": "^4.1.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/postgres-array": {
|
||||||
|
"version": "2.0.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/postgres-array/-/postgres-array-2.0.0.tgz",
|
||||||
|
"integrity": "sha512-VpZrUqU5A69eQyW2c5CA1jtLecCsN2U/bD6VilrFDWq5+5UIEVO7nazS3TEcHf1zuPYO/sqGvUvW62g86RXZuA==",
|
||||||
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=4"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/postgres-bytea": {
|
||||||
|
"version": "1.0.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/postgres-bytea/-/postgres-bytea-1.0.1.tgz",
|
||||||
|
"integrity": "sha512-5+5HqXnsZPE65IJZSMkZtURARZelel2oXUEO8rH83VS/hxH5vv1uHquPg5wZs8yMAfdv971IU+kcPUczi7NVBQ==",
|
||||||
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=0.10.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/postgres-date": {
|
||||||
|
"version": "1.0.7",
|
||||||
|
"resolved": "https://registry.npmjs.org/postgres-date/-/postgres-date-1.0.7.tgz",
|
||||||
|
"integrity": "sha512-suDmjLVQg78nMK2UZ454hAG+OAW+HQPZ6n++TNDUX+L0+uUlLywnoxJKDou51Zm+zTCjrCl0Nq6J9C5hP9vK/Q==",
|
||||||
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=0.10.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/postgres-interval": {
|
||||||
|
"version": "1.2.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/postgres-interval/-/postgres-interval-1.2.0.tgz",
|
||||||
|
"integrity": "sha512-9ZhXKM/rw350N1ovuWHbGxnGh/SNJ4cnxHiM0rxE4VN41wsg8P8zWn9hv/buK00RP4WvlOyr/RBDiptyxVbkZQ==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"xtend": "^4.0.0"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=0.10.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/proxy-from-env": {
|
||||||
|
"version": "2.1.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-2.1.0.tgz",
|
||||||
|
"integrity": "sha512-cJ+oHTW1VAEa8cJslgmUZrc+sjRKgAKl3Zyse6+PV38hZe/V6Z14TbCuXcan9F9ghlz4QrFr2c92TNF82UkYHA==",
|
||||||
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=10"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/split2": {
|
||||||
|
"version": "4.2.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/split2/-/split2-4.2.0.tgz",
|
||||||
|
"integrity": "sha512-UcjcJOWknrNkF6PLX83qcHM6KHgVKNkV62Y8a5uYDVv9ydGQVwAHMKqHdJje1VTWpljG0WYpCDhrCdAOYH4TWg==",
|
||||||
|
"license": "ISC",
|
||||||
|
"engines": {
|
||||||
|
"node": ">= 10.x"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/xtend": {
|
||||||
|
"version": "4.0.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz",
|
||||||
|
"integrity": "sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==",
|
||||||
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=0.4"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
{
|
||||||
|
"name": "cropwise_weather",
|
||||||
|
"version": "1.0.0",
|
||||||
|
"description": "",
|
||||||
|
"license": "ISC",
|
||||||
|
"author": "",
|
||||||
|
"type": "commonjs",
|
||||||
|
"main": "get_weather.js",
|
||||||
|
"scripts": {
|
||||||
|
"dashboard:clusters": "node dashboard/sync-clusters.js",
|
||||||
|
"dashboard:data": "node dashboard/build-data.js",
|
||||||
|
"dashboard:dates": "node dashboard/build-dates-data.js",
|
||||||
|
"dashboard:fert": "node dashboard/build-fertilizers-data.js",
|
||||||
|
"dashboard:fert-quality": "node dashboard/build-fertilizer-quality-data.js",
|
||||||
|
"fertilizer:load": "node load_fertilizer_field.js",
|
||||||
|
"dashboard:build": "node dashboard/sync-clusters.js && node dashboard/build-data.js && node dashboard/build-dates-data.js && node dashboard/build-fertilizers-data.js && node dashboard/build-fertilizer-quality-data.js",
|
||||||
|
"dashboard": "npx --yes serve dashboard -p 5177"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"axios": "^1.18.1",
|
||||||
|
"dotenv": "^17.4.2",
|
||||||
|
"pg": "^8.23.0"
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user