This commit is contained in:
payacom
2026-08-31 20:45:41 +03:30
parent fa9f23c61d
commit 3f416a7a60
367 changed files with 621895 additions and 6443 deletions

57
utils/ensureGeoData.js Normal file
View File

@@ -0,0 +1,57 @@
const fs = require('fs')
const path = require('path')
const { CountryModel, ProvinceModel, CityModel } = require('../models/StateCity')
/**
* Single source of truth for keeping the Country/Province/City reference
* collections in sync with data/geo/{countries,provinces,cities}.json.
* Runs automatically on every backend boot (see boot/mongo.js) — no manual
* script to remember to re-run when the JSON files change. Cheap no-op when
* already in sync (only a countDocuments() + JSON parse), unless force=true.
*/
async function ensureGeoData(force = false) {
const dataDir = path.join(__dirname, '../data/geo')
const countries = JSON.parse(fs.readFileSync(path.join(dataDir, 'countries.json'), 'utf8'))
const provinces = JSON.parse(fs.readFileSync(path.join(dataDir, 'provinces.json'), 'utf8'))
const cities = JSON.parse(fs.readFileSync(path.join(dataDir, 'cities.json'), 'utf8'))
const provincesWithFaCount = provinces.filter((p) => p.name_fa).length
const [countryCount, provinceCount, cityCount, provinceFaCount] = await Promise.all([
CountryModel.countDocuments(),
ProvinceModel.countDocuments(),
CityModel.countDocuments(),
ProvinceModel.countDocuments({ name_fa: { $exists: true, $ne: null } })
])
const inSync =
countryCount === countries.length &&
provinceCount === provinces.length &&
cityCount === cities.length &&
provinceFaCount === provincesWithFaCount
if (!force && inSync) return
console.log(`[boot] Geo reference data out of sync (countries: ${countryCount}/${countries.length}, provinces: ${provinceCount}/${provinces.length}, cities: ${cityCount}/${cities.length}) — reseeding...`)
await CountryModel.deleteMany({})
await ProvinceModel.deleteMany({})
await CityModel.deleteMany({})
await CountryModel.insertMany(countries)
await ProvinceModel.insertMany(
provinces.map((p) => ({ id: p.id, name: p.name, name_fa: p.name_fa, slug: p.slug, country_id: p.country_id }))
)
await CityModel.insertMany(
cities.map((c) => ({
id: c.id,
name: c.name,
name_fa: c.name_fa,
slug: c.slug,
province_id: c.province_id,
country_id: c.country_id
}))
)
console.log(`[boot] Geo reference data reseeded: ${countries.length} countries, ${provinces.length} provinces, ${cities.length} cities.`)
}
module.exports = { ensureGeoData }