158 lines
5.7 KiB
JavaScript
158 lines
5.7 KiB
JavaScript
/**
|
||
* Выгрузка поле-лет с 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);
|
||
});
|