Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : Vrai-Prix8 * File : scripts/build-stats-v2.mjs9 * Module : scripts10 * Repository : https://git.spboucher.ai/vrai-prix11 * Created : 2026-08-1912 * Last Modified : 2026-08-1913 *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/**43 * scripts/build-stats-v2.mjs — agrégats du tableau de bord statistique.44 * Lit data/vraiprix.db (rôle d'évaluation + corpus de ventes + indice marché)45 * et écrit src/data/stats-v2.json : tout ce que /api/stats/dashboard v2 sert46 * en plus des agrégats historiques de src/data/stats.json.47 * Données 100 % réelles — aucune valeur inventée. À relancer quand la DB change :48 * node scripts/build-stats-v2.mjs49 */50import Database from "better-sqlite3";51import { writeFileSync } from "fs";52import path from "path";5354const db = new Database(path.join(process.cwd(), "data", "vraiprix.db"), { readonly: true });55const out = {};56out.generated = new Date().toISOString();5758/* ---------------- unités (rôle d'évaluation, millésime 2026) ---------------- */59console.time("units");60out.units = db.prepare(`61 SELECT COUNT(*) AS total,62 SUM(lat IS NOT NULL AND lng IS NOT NULL AND lat != 0) AS geoloc,63 SUM(valeur_role IS NOT NULL AND valeur_role > 0) AS with_role,64 SUM(est_2026 IS NOT NULL AND est_2026 > 0) AS with_est2026,65 SUM(annee_construction IS NOT NULL AND annee_construction > 1500) AS with_year,66 SUM(aire_etages_m2 IS NOT NULL AND aire_etages_m2 > 0) AS with_area,67 CAST(AVG(CASE WHEN est_2026 > 0 THEN est_2026 END) AS INTEGER) AS avg_est2026,68 CAST(AVG(CASE WHEN valeur_role > 0 THEN valeur_role END) AS INTEGER) AS avg_role,69 CAST(SUM(CASE WHEN valeur_role > 0 THEN valeur_role ELSE 0 END) AS INTEGER) AS sum_role,70 SUM(COALESCE(nb_logements, 0)) AS logements71 FROM units`).get();72console.timeEnd("units");7374/* ------------- distribution des valeurs estimées 2026 (histogramme) ------------- */75console.time("bins");76const BINS = [77 [0, 100e3, "< 100 k$"], [100e3, 200e3, "100-200 k$"], [200e3, 300e3, "200-300 k$"],78 [300e3, 400e3, "300-400 k$"], [400e3, 500e3, "400-500 k$"], [500e3, 750e3, "500-750 k$"],79 [750e3, 1e6, "750 k-1 M$"], [1e6, 2e6, "1-2 M$"], [2e6, 5e6, "2-5 M$"], [5e6, Infinity, "5 M$ +"],80];81const caseExpr = BINS.map(([lo, hi], i) =>82 hi === Infinity ? `WHEN est_2026 >= ${lo} THEN ${i}` : `WHEN est_2026 >= ${lo} AND est_2026 < ${hi} THEN ${i}`83).join(" ");84const binRows = db.prepare(`85 SELECT CASE ${caseExpr} END AS b, COUNT(*) AS n86 FROM units WHERE est_2026 > 0 GROUP BY b ORDER BY b`).all();87out.valeur_bins = BINS.map(([, , label], i) => ({88 label, value: binRows.find((r) => r.b === i)?.n ?? 0,89}));90console.timeEnd("bins");9192/* ------------- parc par tranche d'année de construction ------------- */93console.time("construction");94const ERAS = [95 [0, 1900, "Avant 1900"], [1900, 1946, "1900-1945"], [1946, 1961, "1946-1960"],96 [1961, 1976, "1961-1975"], [1976, 1991, "1976-1990"], [1991, 2006, "1991-2005"],97 [2006, 2016, "2006-2015"], [2016, 3000, "2016 +"],98];99const eraExpr = ERAS.map(([lo, hi], i) => `WHEN annee_construction >= ${lo} AND annee_construction < ${hi} THEN ${i}`).join(" ");100const eraRows = db.prepare(`101 SELECT CASE ${eraExpr} END AS b, COUNT(*) AS n,102 CAST(SUM(CASE WHEN est_2026 > 0 THEN est_2026 ELSE 0 END) AS INTEGER) AS total,103 CAST(AVG(CASE WHEN est_2026 > 0 THEN est_2026 END) AS INTEGER) AS moyenne104 FROM units WHERE annee_construction > 1500 GROUP BY b ORDER BY b`).all();105out.construction = ERAS.map(([, , label], i) => {106 const r = eraRows.find((x) => x.b === i);107 return { label, n: r?.n ?? 0, total: r?.total ?? 0, moyenne: r?.moyenne ?? null };108});109console.timeEnd("construction");110111/* ---------------- records réels du rôle ---------------- */112console.time("records");113out.rec = {};114out.rec.max_role = db.prepare(`115 SELECT municipalite, valeur_role AS v, cubf_libelle FROM units116 WHERE valeur_role IS NOT NULL ORDER BY valeur_role DESC LIMIT 1`).get();117out.rec.max_est = db.prepare(`118 SELECT municipalite, est_2026 AS v FROM units119 WHERE est_2026 IS NOT NULL ORDER BY est_2026 DESC LIMIT 1`).get();120out.rec.max_terrain = db.prepare(`121 SELECT municipalite, superficie_terrain_m2 AS m2 FROM units122 WHERE superficie_terrain_m2 IS NOT NULL ORDER BY superficie_terrain_m2 DESC LIMIT 1`).get();123out.rec.max_logements = db.prepare(`124 SELECT municipalite, nb_logements AS n FROM units125 WHERE nb_logements IS NOT NULL ORDER BY nb_logements DESC LIMIT 1`).get();126const oldest = db.prepare(`127 SELECT MIN(annee_construction) AS y FROM units WHERE annee_construction > 1600`).get();128out.rec.oldest = {129 y: oldest.y,130 n: db.prepare("SELECT COUNT(*) AS n FROM units WHERE annee_construction = ?").get(oldest.y).n,131};132console.timeEnd("records");133134/* ---------------- transactions (corpus de ventes réelles 2021-2026) ---------------- */135console.time("tx");136const TX_TYPE_FR = { unifamilial: "Unifamiliale", condo: "Condo", plex: "Plex", "indéterminé": "Indéterminé" };137const txTypeKeys = ["unifamilial", "condo", "plex", "indéterminé"];138const monthly = new Map(); // m -> { n, total, amounts[], byType: [4] }139for (const r of db.prepare("SELECT substr(date,1,7) AS m, amount, property_type FROM transactions").iterate()) {140 let e = monthly.get(r.m);141 if (!e) { e = { n: 0, total: 0, amounts: [], byType: [0, 0, 0, 0] }; monthly.set(r.m, e); }142 e.n++; e.total += r.amount; e.amounts.push(r.amount);143 const ti = txTypeKeys.indexOf(r.property_type ?? "indéterminé");144 e.byType[ti === -1 ? 3 : ti]++;145}146const months = [...monthly.keys()].sort();147const median = (a) => { const s = [...a].sort((x, y) => x - y); return s[Math.floor(s.length / 2)]; };148out.tx = {149 monthly: months.map((m) => {150 const e = monthly.get(m);151 return { m, n: e.n, total: Math.round(e.total), median: Math.round(median(e.amounts)) };152 }),153 monthly_by_type: {154 keys: txTypeKeys.map((k) => TX_TYPE_FR[k]),155 points: months.map((m) => ({ t: m, values: monthly.get(m).byType })),156 },157};158// bins des montants de vente159const TXB = [160 [0, 200e3, "< 200 k$"], [200e3, 300e3, "200-300 k$"], [300e3, 400e3, "300-400 k$"],161 [400e3, 500e3, "400-500 k$"], [500e3, 700e3, "500-700 k$"], [700e3, 1e6, "700 k-1 M$"],162 [1e6, 2e6, "1-2 M$"], [2e6, Infinity, "2 M$ +"],163];164const txCase = TXB.map(([lo, hi], i) =>165 hi === Infinity ? `WHEN amount >= ${lo} THEN ${i}` : `WHEN amount >= ${lo} AND amount < ${hi} THEN ${i}`).join(" ");166const txBinRows = db.prepare(`SELECT CASE ${txCase} END AS b, COUNT(*) AS n FROM transactions GROUP BY b`).all();167out.tx.amount_bins = TXB.map(([, , label], i) => ({ label, value: txBinRows.find((r) => r.b === i)?.n ?? 0 }));168// activité quotidienne (26 dernières semaines du corpus) pour le calendrier169const maxDate = db.prepare("SELECT MAX(date) AS d FROM transactions").get().d;170const since = new Date(maxDate + "T12:00:00");171since.setDate(since.getDate() - 26 * 7);172out.tx.daily = db.prepare(`173 SELECT date, COUNT(*) AS n FROM transactions WHERE date >= ? GROUP BY date ORDER BY date`)174 .all(since.toISOString().slice(0, 10)).map((r) => ({ date: r.date, n: r.n }));175out.tx.max_date = maxDate;176out.tx.max = db.prepare("SELECT amount, city, date FROM transactions ORDER BY amount DESC LIMIT 1").get();177const best = out.tx.monthly.reduce((a, b) => (b.n > a.n ? b : a));178out.tx.best_month = { m: best.m, n: best.n };179// top villes par nombre de ventes180out.tx.top_villes = db.prepare(`181 SELECT city, COUNT(*) AS n, CAST(AVG(amount) AS INTEGER) AS moyenne182 FROM transactions WHERE city IS NOT NULL GROUP BY city ORDER BY n DESC LIMIT 20`).all();183console.timeEnd("tx");184185/* ---------------- indice de marché mensuel par type ---------------- */186console.time("market");187const MI_TYPE_FR = { unifamilial: "Unifamiliale", condo: "Condo", plex: "Plex", "indéterminé": "Ensemble" };188const miTypes = db.prepare("SELECT DISTINCT type_prop FROM market_index ORDER BY type_prop").all().map((r) => r.type_prop);189out.market = {190 idx_by_type: miTypes.map((t) => ({191 label: MI_TYPE_FR[t] ?? t,192 points: db.prepare("SELECT month, idx FROM market_index WHERE type_prop = ? ORDER BY month").all(t)193 .map((r) => ({ t: r.month, v: Math.round(r.idx * 1000) / 1000 })),194 })),195 ppm2_by_type: miTypes.filter((t) => t !== "indéterminé").map((t) => ({196 label: MI_TYPE_FR[t] ?? t,197 points: db.prepare("SELECT month, ppm2 FROM market_index WHERE type_prop = ? AND ppm2 IS NOT NULL ORDER BY month").all(t)198 .map((r) => ({ t: r.month, v: Math.round(r.ppm2) })),199 })),200};201console.timeEnd("market");202203writeFileSync(path.join(process.cwd(), "src", "data", "stats-v2.json"), JSON.stringify(out));204console.log("→ src/data/stats-v2.json écrit,", JSON.stringify(out).length, "octets");205