Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : Vrai-Prix8 * File : src/lib/stats-dashboard.ts9 * Module : lib10 * Repository : https://git.spboucher.ai/vrai-prix11 * Created : 2026-08-1712 * 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 * Contrat de /api/stats/dashboard (voir docs/API.md),44 * construit depuis src/data/stats.json (agrégats historiques du rôle) et45 * src/data/stats-v2.json (agrégats enrichis : distributions, transactions46 * mensuelles/quotidiennes, indice de marché — générés par47 * scripts/build-stats-v2.mjs depuis data/vraiprix.db, données 100 % réelles).48 *49 * Particularité Vrai-Prix : le rôle d'évaluation est un INSTANTANÉ (millésime50 * 2026) — `period` est accepté mais non applicable ; les51 * vraies séries temporelles sont les millésimes 2021-2026, le corpus de52 * ventes réelles (mensuel, 2021-01 → 2026-07) et l'indice de marché mensuel.53 * Les delta_pct sont calculés (millésime vs millésime, 12 mois vs 12 mois54 * précédents) et arrondis à 1 décimale — jamais inventés.55 */56import stats from "@/data/stats.json";57import v2 from "@/data/stats-v2.json";58import type { ProvStats } from "@/components/StatsView";5960/** Ventes réelles publiées 2021-01 → 2026-07 (constante du corpus, voir /methodologie). */61export const TRANSACTIONS = 745119;6263export const PERIOD_LABEL = "instantané du rôle 2026";6465export const TYPE_FR: Record<string, string> = {66 unifamilial: "Unifamiliale",67 plex: "Plex (2-5 log.)",68 condo_ou_multi: "Condo / multi",69 chalet: "Chalet",70 maison_mobile: "Maison mobile",71 terrain: "Terrain",72 autre: "Autre",73};7475const money = (v: number) =>76 new Intl.NumberFormat("fr-CA", { style: "currency", currency: "CAD", maximumFractionDigits: 0 }).format(v);77const compact = (v: number) => {78 if (v >= 1e12) return `${(v / 1e12).toLocaleString("fr-CA", { maximumFractionDigits: 2 })} billions $`;79 if (v >= 1e9) return `${(v / 1e9).toLocaleString("fr-CA", { maximumFractionDigits: 1 })} G$`;80 if (v >= 1e6) return `${(v / 1e6).toLocaleString("fr-CA", { maximumFractionDigits: 1 })} M$`;81 return money(v);82};83const pct = (v: number) => `${v >= 0 ? "+" : ""}${v.toLocaleString("fr-CA", { maximumFractionDigits: 1 })} %`;84const r1 = (v: number) => Math.round(v * 10) / 10;85const delta = (cur: number, prev: number): number | null =>86 prev > 0 ? r1((cur / prev - 1) * 100) : null;87const MOIS_FR = ["janv.", "févr.", "mars", "avr.", "mai", "juin", "juill.", "août", "sept.", "oct.", "nov.", "déc."];88const moisLabel = (m: string) => `${MOIS_FR[parseInt(m.slice(5, 7), 10) - 1]} ${m.slice(0, 4)}`;8990/* ---------- types du contrat (SPEC §2) ---------- */91export type Point = { t: string; v: number };92export interface KaKpi {93 id: string; label: string; value: number | string; unit?: string;94 delta_pct?: number | null; direction?: "up" | "down"; spark?: Point[]; help?: string;95}96export interface KaSerie {97 id: string; title: string; unit?: string; kind: "line" | "bar" | "area";98 points: Point[]; compare?: Point[];99}100export interface KaRecord { label: string; value: string; date?: string }101102interface V2Data {103 generated: string;104 units: {105 total: number; geoloc: number; with_role: number; with_est2026: number;106 with_year: number; with_area: number; avg_est2026: number; avg_role: number;107 sum_role: number; logements: number;108 };109 valeur_bins: { label: string; value: number }[];110 construction: { label: string; n: number; total: number; moyenne: number | null }[];111 rec: {112 max_role: { municipalite: string; v: number; cubf_libelle: string | null };113 max_est: { municipalite: string; v: number };114 };115 tx: {116 monthly: { m: string; n: number; total: number; median: number }[];117 monthly_by_type: { keys: string[]; points: { t: string; values: number[] }[] };118 amount_bins: { label: string; value: number }[];119 daily: { date: string; n: number }[];120 max_date: string;121 max: { amount: number; city: string | null; date: string };122 best_month: { m: string; n: number };123 top_villes: { city: string; n: number; moyenne: number }[];124 };125 market: {126 idx_by_type: { label: string; points: Point[] }[];127 ppm2_by_type: { label: string; points: Point[] }[];128 };129}130const V = v2 as unknown as V2Data;131132/** Records & faits marquants, calculés depuis les données réelles (jamais inventés). */133export function buildRecords(s: ProvStats): KaRecord[] {134 const out: KaRecord[] = [];135 const topVille = s.par_ville[0];136 if (topVille) {137 out.push({138 label: "Municipalité la plus valorisée",139 value: `${topVille.ville} — ${compact(topVille.total)}`,140 });141 }142 const topMed = s.par_ville.reduce((a, b) => ((b.mediane ?? 0) > (a.mediane ?? 0) ? b : a), s.par_ville[0]);143 if (topMed?.mediane) {144 out.push({145 label: "Valeur médiane la plus élevée (top 200)",146 value: `${topMed.ville} — ${money(topMed.mediane)}`,147 });148 }149 let bestYoy: { year: number; yoy: number } | null = null;150 for (let i = 1; i < s.totaux_annee.length; i++) {151 const yoy = (s.totaux_annee[i].total / s.totaux_annee[i - 1].total - 1) * 100;152 if (!bestYoy || yoy > bestYoy.yoy) bestYoy = { year: s.totaux_annee[i].year, yoy };153 }154 if (bestYoy) {155 out.push({156 label: "Plus forte hausse annuelle du parc",157 value: pct(bestYoy.yoy),158 date: String(bestYoy.year),159 });160 }161 const topType = s.par_type.reduce((a, b) => (b.total > a.total ? b : a), s.par_type[0]);162 if (topType) {163 const share = (topType.total / s.valeur_totale_2026) * 100;164 out.push({165 label: "Type de bien dominant",166 value: `${TYPE_FR[topType.type] ?? topType.type} — ${compact(topType.total)} (${share.toLocaleString("fr-CA", { maximumFractionDigits: 1 })} %)`,167 });168 }169 out.push({170 label: "Croissance 2021→2026 (périmètre constant)",171 value: pct(s.croissance_2021_2026_pct),172 });173 // records v2 — rôle & corpus de ventes (stats-v2.json, données réelles)174 if (V.rec?.max_role) {175 out.push({176 label: "Plus grosse évaluation au rôle",177 value: `${V.rec.max_role.cubf_libelle ?? "Immeuble"} (${V.rec.max_role.municipalite}) — ${compact(V.rec.max_role.v)}`,178 });179 }180 if (V.rec?.max_est) {181 out.push({182 label: "Estimation Vrai-Prix la plus élevée",183 value: `${V.rec.max_est.municipalite} — ${compact(V.rec.max_est.v)}`,184 });185 }186 if (V.tx?.max) {187 out.push({188 label: "Plus grosse vente du corpus",189 value: `${compact(V.tx.max.amount)}${V.tx.max.city ? ` — ${V.tx.max.city}` : ""}`,190 date: V.tx.max.date,191 });192 }193 if (V.tx?.best_month) {194 out.push({195 label: "Mois record de ventes",196 value: `${V.tx.best_month.n.toLocaleString("fr-CA")} ventes`,197 date: moisLabel(V.tx.best_month.m),198 });199 }200 const topTx = V.tx?.top_villes?.[0];201 if (topTx) {202 out.push({203 label: "Ville la plus active en ventes (2021-2026)",204 value: `${topTx.city} — ${topTx.n.toLocaleString("fr-CA")} ventes`,205 });206 }207 return out;208}209210function buildDashboard() {211 const s = stats as ProvStats;212 const u = V.units;213 const gpct = (a: number, b: number) => r1((100 * a) / (b || 1));214215 /* --- millésimes (2021-2026) : deltas millésime vs millésime précédent --- */216 const ta = s.totaux_annee;217 const last = ta[ta.length - 1];218 const prev = ta[ta.length - 2];219 const avgPrev = prev ? prev.total / prev.n : 0;220221 /* --- corpus de ventes : 12 derniers mois vs 12 mois précédents (réel) --- */222 const m = V.tx.monthly;223 const last12 = m.slice(-12);224 const prev12 = m.slice(-24, -12);225 const sum = (a: { n: number; total: number }[], k: "n" | "total") => a.reduce((x, y) => x + y[k], 0);226 const lastMonth = m[m.length - 1];227 const sameMonthN1 = m[m.length - 13];228229 const kpis: KaKpi[] = [230 {231 id: "unites", label: "Propriétés couvertes (rôle 2026)", value: s.unites,232 delta_pct: prev ? delta(last.n, prev.n) : null, direction: "up",233 spark: ta.map((a) => ({ t: String(a.year), v: a.n })),234 help: "Unités d'évaluation estimées au millésime 2026 — variation vs millésime 2025.",235 },236 {237 id: "valeur_totale", label: "Valeur totale du parc (2026)", value: compact(s.valeur_totale_2026),238 delta_pct: prev ? delta(last.total, prev.total) : null, direction: "up",239 spark: ta.map((a) => ({ t: String(a.year), v: a.total })),240 help: "Somme des estimations Vrai-Prix — variation vs millésime 2025.",241 },242 {243 id: "valeur_moyenne", label: "Valeur moyenne (2026)", value: money(u.avg_est2026),244 delta_pct: avgPrev ? delta(u.avg_est2026, avgPrev) : null, direction: "up",245 spark: ta.map((a) => ({ t: String(a.year), v: Math.round(a.total / a.n) })),246 },247 { id: "valeur_mediane", label: "Valeur médiane (2026)", value: money(s.valeur_mediane_2026) },248 { id: "municipalites", label: "Municipalités couvertes", value: s.municipalites },249 { id: "logements", label: "Logements au rôle", value: u.logements },250 {251 id: "ventes_12m", label: "Ventes réelles — 12 derniers mois", value: sum(last12, "n"),252 delta_pct: delta(sum(last12, "n"), sum(prev12, "n")),253 direction: sum(last12, "n") >= sum(prev12, "n") ? "up" : "down",254 spark: m.slice(-24).map((x) => ({ t: x.m, v: x.n })),255 help: "Corpus de ventes publiées — 12 derniers mois vs les 12 mois précédents.",256 },257 {258 id: "volume_12m", label: "Volume des ventes — 12 derniers mois", value: compact(sum(last12, "total")),259 delta_pct: delta(sum(last12, "total"), sum(prev12, "total")),260 direction: sum(last12, "total") >= sum(prev12, "total") ? "up" : "down",261 spark: m.slice(-24).map((x) => ({ t: x.m, v: x.total })),262 },263 {264 id: "prix_vente_median", label: `Prix de vente médian (${moisLabel(lastMonth.m)})`, value: money(lastMonth.median),265 delta_pct: sameMonthN1 ? delta(lastMonth.median, sameMonthN1.median) : null,266 direction: sameMonthN1 && lastMonth.median >= sameMonthN1.median ? "up" : "down",267 spark: m.slice(-24).map((x) => ({ t: x.m, v: x.median })),268 help: "Médiane des ventes du dernier mois complet du corpus — variation vs le même mois un an plus tôt.",269 },270 {271 id: "transactions", label: "Ventes réelles du corpus (2021-01 → 2026-07)", value: TRANSACTIONS,272 help: "Toutes les ventes publiées intégrées au modèle de comparables.",273 },274 ];275276 const gauges = [277 {278 id: "geoloc", label: "Unités géolocalisées", value: gpct(u.geoloc, u.total), max: 100, unit: "%",279 help: "Unités du rôle avec coordonnées lat/lng valides.",280 },281 {282 id: "role_connu", label: "Valeur au rôle connue", value: gpct(u.with_role, u.total), max: 100, unit: "%",283 help: "Unités avec évaluation municipale renseignée.",284 },285 {286 id: "annee_connue", label: "Année de construction connue", value: gpct(u.with_year, u.total), max: 100, unit: "%",287 },288 {289 id: "aire_connue", label: "Superficie de plancher connue", value: gpct(u.with_area, u.total), max: 100, unit: "%",290 },291 ];292293 const series: KaSerie[] = [294 {295 id: "valeur_millesime", title: "Valeur provinciale par millésime (2021-2026)", unit: "$",296 kind: "line", points: ta.map((a) => ({ t: String(a.year), v: a.total })),297 },298 {299 id: "unites_millesime", title: "Unités estimées par millésime", unit: "unités",300 kind: "line", points: ta.map((a) => ({ t: String(a.year), v: a.n })),301 },302 {303 id: "ventes_mois", title: "Ventes réelles par mois (corpus 2021-2026)", unit: "ventes",304 kind: "bar", points: m.map((x) => ({ t: x.m, v: x.n })),305 },306 {307 id: "volume_mois", title: "Volume mensuel des ventes ($)", unit: "$",308 kind: "area", points: m.map((x) => ({ t: x.m, v: x.total })),309 },310 {311 id: "prix_median_mois", title: "Prix de vente médian par mois", unit: "$",312 kind: "line", points: m.map((x) => ({ t: x.m, v: x.median })),313 },314 ];315316 const multiseries = [317 {318 id: "indice_marche", title: "Indice de marché par type (base 1,0)", unit: "",319 series: V.market.idx_by_type,320 },321 {322 id: "ppm2", title: "Prix au m² des ventes, par type", unit: "$/m²",323 series: V.market.ppm2_by_type,324 },325 ];326327 const stacked = [328 {329 id: "ventes_type", title: "Ventes mensuelles par type de propriété", unit: "ventes",330 keys: V.tx.monthly_by_type.keys, points: V.tx.monthly_by_type.points,331 },332 ];333334 const breakdowns = [335 {336 id: "types", title: "Répartition de la valeur par type de bien", kind: "donut" as const,337 items: s.par_type.map((t) => ({ label: TYPE_FR[t.type] ?? t.type, value: t.total })),338 },339 {340 id: "types_n", title: "Unités par type de bien", kind: "bars" as const,341 items: s.par_type.map((t) => ({ label: TYPE_FR[t.type] ?? t.type, value: t.n })),342 },343 {344 id: "construction", title: "Valeur par tranche d'année de construction", kind: "bars" as const,345 items: V.construction.map((c) => ({ label: c.label, value: c.total })),346 },347 ];348349 const distributions = [350 {351 id: "valeurs", title: "Distribution des valeurs estimées (2026)", unit: "unités",352 bins: V.valeur_bins,353 },354 {355 id: "montants_vente", title: "Distribution des montants de vente (2021-2026)", unit: "ventes",356 bins: V.tx.amount_bins,357 },358 ];359360 const geo = {361 title: "Top municipalités par valeur totale estimée",362 items: s.par_ville.slice(0, 15).map((v) => ({ label: v.ville, value: v.total })),363 };364365 const heatmap = {366 title: `Ventes réelles par jour (corpus, jusqu'au ${V.tx.max_date})`,367 cells: V.tx.daily.map((d) => ({ date: d.date, value: d.n })),368 };369370 const topMediane = [...s.par_ville]371 .filter((v) => v.mediane != null)372 .sort((a, b) => (b.mediane ?? 0) - (a.mediane ?? 0))373 .slice(0, 20);374375 const idxEnsemble = V.market.idx_by_type.find((x) => x.label === "Ensemble");376 const ppm2 = (label: string, t: string) =>377 V.market.ppm2_by_type.find((x) => x.label === label)?.points.find((p) => p.t === t)?.v ?? null;378 const last12Months = (idxEnsemble?.points ?? []).slice(-12);379380 const tables = [381 {382 id: "top_municipalites",383 title: "Palmarès des 200 plus grandes municipalités (millésime 2026)",384 columns: ["Rang", "Municipalité", "Propriétés", "Valeur totale ($)", "Valeur médiane ($)"],385 rows: s.par_ville.map((v, i) => [i + 1, v.ville, v.n, v.total, v.mediane] as (string | number | null)[]),386 },387 {388 id: "top_medianes",389 title: "Top 20 municipalités par valeur médiane (parmi le top 200)",390 columns: ["Rang", "Municipalité", "Valeur médiane ($)", "Propriétés", "Valeur totale ($)"],391 rows: topMediane.map((v, i) => [i + 1, v.ville, v.mediane, v.n, v.total] as (string | number | null)[]),392 },393 {394 id: "par_type",395 title: "Répartition par type de propriété",396 columns: ["Type", "Unités", "Valeur totale ($)", "Valeur médiane ($)"],397 rows: s.par_type.map((t) => [TYPE_FR[t.type] ?? t.type, t.n, t.total, t.mediane] as (string | number | null)[]),398 },399 {400 id: "construction",401 title: "Parc par tranche d'année de construction",402 columns: ["Tranche", "Unités", "Valeur totale ($)", "Valeur moyenne ($)"],403 rows: V.construction.map((c) => [c.label, c.n, c.total, c.moyenne] as (string | number | null)[]),404 },405 {406 id: "indice_marche",407 title: "Indice de marché — 12 derniers mois",408 columns: ["Mois", "Indice (ensemble)", "$/m² unifamiliale", "$/m² condo", "$/m² plex"],409 rows: last12Months.map((p) => [410 p.t, p.v, ppm2("Unifamiliale", p.t), ppm2("Condo", p.t), ppm2("Plex", p.t),411 ] as (string | number | null)[]),412 },413 {414 id: "top_villes_ventes",415 title: "Top 20 villes par nombre de ventes (corpus 2021-2026)",416 columns: ["Rang", "Ville", "Ventes", "Montant moyen ($)"],417 rows: V.tx.top_villes.map((v, i) => [i + 1, v.city, v.n, v.moyenne] as (string | number | null)[]),418 },419 ];420421 return {422 updated: V.generated,423 period: {424 from: null as string | null,425 to: null as string | null,426 label: PERIOD_LABEL,427 applicable: false,428 note:429 "Les données de Vrai-Prix sont un instantané du rôle d'évaluation foncière (millésime 2026) : " +430 "le paramètre `period` est accepté mais sans effet. Les séries temporelles réelles servies sont " +431 "les millésimes 2021-2026, le corpus de ventes mensuel (2021-01 → 2026-07) et l'indice de marché.",432 },433 kpis,434 gauges,435 series,436 multiseries,437 stacked,438 breakdowns,439 distributions,440 geo,441 heatmap,442 tables,443 records: buildRecords(s),444 };445}446447export type StatsDashboard = ReturnType<typeof buildDashboard>;448449/** Cache mémoire : les données sont des imports statiques, on ne construit qu'une fois. */450let cache: StatsDashboard | null = null;451export function getDashboard(): StatsDashboard {452 if (!cache) cache = buildDashboard();453 return cache;454}455