350 lines
13 KiB
JavaScript
350 lines
13 KiB
JavaScript
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 }; |