Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : Vrai-Prix8 * File : scripts/ingest-jdm.mjs9 * Module : scripts10 * Repository : https://git.spboucher.ai/vrai-prix11 * Created : 2026-08-2212 * Last Modified : 2026-10-2013 *14 * Author : Simon-Pierre Boucher15 * Position : Professor of Finance16 * Institution : Université du Québec en Outaouais (UQO)17 * Organization : SP Boucher18 * Website : https://spboucher.ai19 * Git : https://git.spboucher.ai20 *21 * Preferred Contact: contact@spboucher.ai22 * Development : dev@spboucher.ai23 * Support : support@spboucher.ai24 * Security/Admin : admin@spboucher.ai25 *26 * Copyright (c) 202627 * Simon-Pierre Boucher28 * All rights reserved where applicable. This file is governed by the29 * applicable project license, copyright notices and relevant law.30 * Existing third-party rights and notices remain unaffected.31 *32 * License : None specified (no license file in this repository)33 *34 * Do not embed credentials, private keys, access tokens,35 * certificates or confidential personal information.36 *37 * =============================================================================38 * END OF SP BOUCHER SOURCE HEADER39 * =============================================================================40 */4142// Connecteur incrémental « nouvelles ventes » — source api.qub.ca43// (le même feed que le widget « Transactions immobilières » du Journal de44// Montréal, https://www.journaldemontreal.com/argent/immobilier/transactions-immobilieres).45//46// Contrairement au pipeline batch complet (docs/PIPELINE-DONNEES.md, qui vit sur47// le laptop et reconstruit tout le .db), ce connecteur tourne SUR LE NŒUD et48// ajoute uniquement les ventes récentes directement dans data/vraiprix.db :49//50// 1. Récupère un jeton Bearer QUB (scripts/qub-token.mjs, via Scrapfly).51// 2. Liste les ~1478 secteurs de /real-estate-service/v1/locations/all.52// 3. Pour chaque secteur, interroge /v1/map (résultats triés du plus récent53// au plus ancien, plafonnés à `nb_transactions`). Si un secteur sature le54// plafond sans atteindre la date plancher, on subdivise sa bbox (quadtree).55// 4. Mappe chaque vente vers le schéma `transactions`, joint spatialement à56// `units` pour id_provinc / valeur_role, puis INSERT OR IGNORE (dédup par57// id — identique au pipeline batch, la source fournit le même id nanoid).58//59// Les `id` déjà connus sont ignorés : lancer ce script régulièrement (cron/pm2)60// garde la base à jour sans doublon. L'app lit le .db en WAL, les nouvelles61// lignes sont visibles immédiatement, sans redémarrage.62//63// Env : SCRAPFLY_KEY, QUB_EMAIL, QUB_PASSWORD (login), VRAIPRIX_DB (optionnel),64// QUB_TOKEN (jeton Bearer déjà obtenu — p. ex. scripts/qub-token-safari.sh65// depuis le laptop — court-circuite le login Scrapfly).66// Args : --since=YYYY-MM-DD date plancher (défaut : max(date en base) - 45 j)67// --region="Nom" ne traiter que ce(s) secteur(s) (sous-chaîne)68// --dry-run n'écrit rien, affiche seulement le décompte69// --token=JWT idem QUB_TOKEN70// --concurrency=N requêtes /map simultanées (défaut 6)7172import Database from 'better-sqlite3';73import fs from 'node:fs';74import path from 'node:path';75import { fileURLToPath } from 'node:url';76import { getQubToken } from './qub-token.mjs';7778// Charge .env.local (racine du repo) si présent — rend le script autonome sous79// cron/pm2 (SCRAPFLY_KEY, QUB_EMAIL, QUB_PASSWORD, QUB_SESSION, VRAIPRIX_DB).80(function loadEnvLocal() {81 const envPath = path.join(fileURLToPath(new URL('..', import.meta.url)), '.env.local');82 if (!fs.existsSync(envPath)) return;83 for (const line of fs.readFileSync(envPath, 'utf8').split('\n')) {84 const m = line.match(/^\s*([A-Z0-9_]+)\s*=\s*(.*)\s*$/);85 if (m && !(m[1] in process.env)) process.env[m[1]] = m[2].replace(/^["']|["']$/g, '');86 }87})();8889const API = 'https://api.qub.ca/real-estate-service/v1';90const PAGE_CAP = 500; // plafond de /map ; si atteint on subdivise91const HDRS = {92 Origin: 'https://www.journaldemontreal.com',93 Referer: 'https://www.journaldemontreal.com/',94 'User-Agent':95 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0 Safari/537.36',96};9798// ---------- args ----------99const args = Object.fromEntries(100 process.argv.slice(2).map((a) => {101 const m = a.match(/^--([^=]+)(?:=(.*))?$/);102 return m ? [m[1], m[2] ?? true] : [a, true];103 }),104);105const DRY = !!args['dry-run'];106const CONC = Math.max(1, parseInt(args.concurrency || '6', 10));107const REGION = args.region ? String(args.region).toLowerCase() : null;108109// ---------- db ----------110const DB_PATH =111 process.env.VRAIPRIX_DB || path.join(process.cwd(), 'data', 'vraiprix.db');112const db = new Database(DB_PATH);113db.pragma('journal_mode = WAL');114db.pragma('busy_timeout = 15000');115116const sinceArg = typeof args.since === 'string' ? args.since : null;117const maxDate = db.prepare('SELECT MAX(date) d FROM transactions').get().d;118function minusDays(iso, n) {119 const d = new Date(iso + 'T00:00:00Z');120 d.setUTCDate(d.getUTCDate() - n);121 return d.toISOString().slice(0, 10);122}123const SINCE = sinceArg || minusDays(maxDate || '2026-01-01', 45);124125// ---------- helpers ----------126const sleep = (ms) => new Promise((r) => setTimeout(r, ms));127128async function apiGet(url, token, tries = 4) {129 for (let i = 0; i < tries; i++) {130 let res;131 try {132 res = await fetch(url, { headers: { ...HDRS, Authorization: `Bearer ${token}` } });133 } catch (e) {134 if (i === tries - 1) throw e;135 await sleep(500 * (i + 1));136 continue;137 }138 if (res.ok) return res.json();139 if (res.status === 401 || res.status === 403)140 throw Object.assign(new Error(`auth ${res.status}`), { authError: true });141 if (res.status === 429 || res.status >= 500) {142 await sleep(800 * (i + 1));143 continue;144 }145 throw new Error(`HTTP ${res.status} sur ${url}`);146 }147 throw new Error(`échec après ${tries} essais : ${url}`);148}149150async function fetchLocations(token) {151 const list = await apiGet(`${API}/locations/all`, token);152 return list153 .map((l) => {154 // shape.coordinates est un anneau « plat » [[lng,lat],…] chez cette API155 // (parfois imbriqué [[[lng,lat],…]] en GeoJSON standard) — on gère les deux.156 let ring = l.shape?.coordinates || [];157 if (Array.isArray(ring[0]?.[0])) ring = ring[0];158 if (!ring.length || typeof ring[0]?.[0] !== 'number') return null;159 const lngs = ring.map((c) => c[0]);160 const lats = ring.map((c) => c[1]);161 return {162 name: l.name,163 sw_lat: Math.min(...lats),164 ne_lat: Math.max(...lats),165 sw_lng: Math.min(...lngs),166 ne_lng: Math.max(...lngs),167 };168 })169 .filter(Boolean);170}171172// Récupère les ventes d'une bbox, subdivise (quadtree) si le plafond est saturé173// alors que les ventes retournées sont encore >= SINCE (⇒ il en manque).174async function fetchBox(box, token, out, depth = 0) {175 const url =176 `${API}/map?ne_lat=${box.ne_lat}&ne_lng=${box.ne_lng}` +177 `&sw_lat=${box.sw_lat}&sw_lng=${box.sw_lng}&nb_transactions=${PAGE_CAP}&cid=0`;178 const rows = await apiGet(url, token);179 for (const t of rows) if (t.date >= SINCE) out.set(t.id, t);180181 const oldest = rows.length ? rows[rows.length - 1].date : null;182 const saturated = rows.length >= PAGE_CAP && oldest && oldest >= SINCE;183 if (saturated && depth < 6) {184 const mlat = (box.ne_lat + box.sw_lat) / 2;185 const mlng = (box.ne_lng + box.sw_lng) / 2;186 const quads = [187 { sw_lat: box.sw_lat, sw_lng: box.sw_lng, ne_lat: mlat, ne_lng: mlng },188 { sw_lat: box.sw_lat, sw_lng: mlng, ne_lat: mlat, ne_lng: box.ne_lng },189 { sw_lat: mlat, sw_lng: box.sw_lng, ne_lat: box.ne_lat, ne_lng: mlng },190 { sw_lat: mlat, sw_lng: mlng, ne_lat: box.ne_lat, ne_lng: box.ne_lng },191 ];192 for (const q of quads) await fetchBox(q, token, out, depth + 1);193 }194}195196// ---------- spatial join vers units (id_provinc, valeur_role) ----------197const unitsInBox = db.prepare(198 `SELECT id_provinc, lat, lng, valeur_role, type_prop FROM units199 WHERE lat BETWEEN ? AND ? AND lng BETWEEN ? AND ?`,200);201function haversine(aLat, aLng, bLat, bLng) {202 const R = 6371000, toR = Math.PI / 180;203 const dLat = (bLat - aLat) * toR, dLng = (bLng - aLng) * toR;204 const s =205 Math.sin(dLat / 2) ** 2 +206 Math.cos(aLat * toR) * Math.cos(bLat * toR) * Math.sin(dLng / 2) ** 2;207 return 2 * R * Math.asin(Math.sqrt(s));208}209// Rayons d'appariement croissants (~65 m, ~220 m, ~550 m).210const DEGS = [0.0006, 0.002, 0.005];211function matchUnit(lat, lng, propertyType) {212 for (const d of DEGS) {213 const cands = unitsInBox.all(lat - d, lat + d, lng - d, lng + d);214 if (!cands.length) continue;215 let best = null, bestDist = Infinity;216 for (const u of cands) {217 let dist = haversine(lat, lng, u.lat, u.lng);218 if (propertyType && u.type_prop && u.type_prop !== propertyType) dist += 25; // léger biais type219 if (dist < bestDist) { bestDist = dist; best = u; }220 }221 if (best) return best;222 }223 return null;224}225226function toRow(t) {227 const coords = t.geometries?.[0]?.coordinates || [];228 const lng = coords[0], lat = coords[1];229 if (typeof lat !== 'number' || typeof lng !== 'number') return null;230 const ar = t.ar || {};231 const yb = ar.yearBuilt != null ? parseInt(ar.yearBuilt, 10) : null;232 const unit = matchUnit(lat, lng, t.propertyType);233 return {234 id: t.id,235 date: t.date,236 amount: t.amount,237 street: t.address?.street ?? null,238 city: t.address?.city ?? null,239 lat,240 lng,241 property_type: t.propertyType ?? null,242 year_built: Number.isFinite(yb) ? yb : null,243 floor_area: ar.floorArea ?? null,244 building_type: ar.buildingType ?? null,245 id_provinc: unit?.id_provinc ?? null,246 valeur_role: unit?.valeur_role ?? ar.totalArValue ?? null,247 land_area: ar.parcelArea ?? null,248 };249}250251const insert = db.prepare(252 `INSERT OR IGNORE INTO transactions253 (id,date,amount,street,city,lat,lng,property_type,year_built,floor_area,254 building_type,id_provinc,valeur_role,land_area)255 VALUES (@id,@date,@amount,@street,@city,@lat,@lng,@property_type,@year_built,256 @floor_area,@building_type,@id_provinc,@valeur_role,@land_area)`,257);258259// ---------- main ----------260async function main() {261 console.log(`[ingest-jdm] base : ${DB_PATH}`);262 console.log(`[ingest-jdm] date max en base : ${maxDate} → plancher SINCE=${SINCE}`);263 if (DRY) console.log('[ingest-jdm] DRY-RUN : aucune écriture');264265 const external = (typeof args.token === 'string' && args.token) || process.env.QUB_TOKEN || null;266 if (external) console.log('[ingest-jdm] jeton QUB fourni (QUB_TOKEN / --token), login Scrapfly ignoré');267 const token =268 external ||269 (await getQubToken({270 session: process.env.QUB_SESSION || 'qub-vraiprix',271 log: (m) => console.log('[ingest-jdm]', m),272 }));273274 let locations = await fetchLocations(token);275 if (REGION) locations = locations.filter((l) => l.name.toLowerCase().includes(REGION));276 console.log(`[ingest-jdm] secteurs à balayer : ${locations.length}`);277278 // Balayage concurrent par secteur.279 const collected = new Map();280 let done = 0;281 async function worker(queue) {282 for (;;) {283 const box = queue.pop();284 if (!box) return;285 try {286 await fetchBox(box, token, collected);287 } catch (e) {288 if (e.authError) throw e;289 console.warn(`[ingest-jdm] secteur "${box.name}" : ${e.message}`);290 }291 if (++done % 100 === 0)292 console.log(`[ingest-jdm] ${done}/${locations.length} secteurs, ${collected.size} ventes ≥ ${SINCE}`);293 }294 }295 const queue = [...locations];296 await Promise.all(Array.from({ length: CONC }, () => worker(queue)));297 console.log(`[ingest-jdm] ventes candidates (≥ ${SINCE}) : ${collected.size}`);298299 // Mapping + insertion.300 const before = db.prepare('SELECT COUNT(*) n FROM transactions').get().n;301 let inserted = 0, skippedGeo = 0, matched = 0;302 const rows = [];303 for (const t of collected.values()) {304 const r = toRow(t);305 if (!r) { skippedGeo++; continue; }306 if (r.id_provinc) matched++;307 rows.push(r);308 }309310 if (!DRY) {311 const tx = db.transaction((batch) => {312 for (const r of batch) inserted += insert.run(r).changes;313 });314 tx(rows);315 }316317 const after = DRY ? before : db.prepare('SELECT COUNT(*) n FROM transactions').get().n;318 console.log('[ingest-jdm] ---------- résumé ----------');319 console.log(` candidates mappées : ${rows.length}`);320 console.log(` appariées à une unité: ${matched} (${rows.length ? ((matched / rows.length) * 100).toFixed(1) : 0} %)`);321 console.log(` sans géométrie : ${skippedGeo}`);322 console.log(` NOUVELLES insérées : ${DRY ? '(dry-run)' : inserted}`);323 console.log(` transactions totales : ${before} → ${after}`);324 const nd = db.prepare('SELECT MAX(date) d FROM transactions').get().d;325 console.log(` date max en base : ${nd}`);326 db.close();327}328329main().catch((e) => {330 console.error('[ingest-jdm] ERREUR', e);331 db.close();332 process.exit(1);333});334