init
This commit is contained in:
@@ -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);
|
||||
});
|
||||
Reference in New Issue
Block a user