Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : Vrai-Prix8 * File : src/lib/municipalites.ts9 * Module : lib10 * Repository : https://git.spboucher.ai/vrai-prix11 * Created : 2026-08-1312 * Last Modified : 2026-08-1313 *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// Auteur : Simon-Pierre Boucher — contact@spboucher.ai43// Données agrégées par municipalité pour les pages programmatiques SEO.44// Les agrégats ne changent qu'au rebuild de la DB : cache mémoire par processus.4546import { getDb } from "./db";47import { cacheDisque } from "./local-db";4849/** Les agrégats du rôle ne bougent qu'au réentraînement du modèle : 3 jours de cache disque. */50const TTL_ROLE_MS = 3 * 24 * 3600 * 1000;51import { slugify } from "./seo";5253export interface MunSummary {54 nom: string;55 slug: string;56 n: number;57 lat: number;58 lng: number;59}6061export interface TypeStats {62 type: string;63 n: number;64 total2026: number;65 mediane2026: number | null;66}6768export interface MunStats {69 nom: string;70 slug: string;71 n: number;72 total2026: number;73 total2021: number;74 mediane2026: number | null;75 croissancePct: number | null;76 parType: TypeStats[];77}7879export interface SampleUnit {80 id_provinc: string;81 adresse: string | null;82 apt: string | null;83 type_prop: string;84 est_2026: number | null;85 annee_construction: number | null;86 aire_etages_m2: number | null;87}8889let munList: MunSummary[] | null = null;90let munBySlugMap: Map<string, MunSummary> | null = null;91const statsCache = new Map<string, MunStats>();9293/** Toutes les municipalités (nom, slug, nb d'unités, centroïde) — triées par taille. */94export function allMunicipalities(): MunSummary[] {95 if (!munList) {96 const rows = cacheDisque("municipalites:v1", TTL_ROLE_MS, () =>97 getDb()98 .prepare(99 `SELECT municipalite AS nom, COUNT(*) AS n,100 AVG(lat) AS lat, AVG(lng) AS lng101 FROM units WHERE municipalite IS NOT NULL AND municipalite != ''102 GROUP BY municipalite ORDER BY n DESC`103 )104 .all() as { nom: string; n: number; lat: number; lng: number }[]105 );106 munList = rows.map((r) => ({ ...r, slug: slugify(r.nom) }));107 munBySlugMap = new Map(munList.map((m) => [m.slug, m]));108 }109 return munList;110}111112export function munBySlug(slug: string): MunSummary | undefined {113 allMunicipalities();114 return munBySlugMap!.get(slug);115}116117function median2026(nom: string, type?: string): number | null {118 const db = getDb();119 // COLLATE NOCASE : sert l'index (municipalite NOCASE, est_2026), la médiane se lit120 // alors par simple saut dans l'index (aucun tri de 500 000 lignes pour Montréal).121 const where = type122 ? "municipalite = ? COLLATE NOCASE AND type_prop = ?"123 : "municipalite = ? COLLATE NOCASE";124 const args: (string | number)[] = type ? [nom, type] : [nom];125 const cnt = (126 db.prepare(`SELECT COUNT(*) AS c FROM units WHERE ${where} AND est_2026 IS NOT NULL`).get(...args) as { c: number }127 ).c;128 if (!cnt) return null;129 const row = db130 .prepare(131 `SELECT est_2026 AS v FROM units WHERE ${where} AND est_2026 IS NOT NULL132 ORDER BY est_2026 LIMIT 1 OFFSET ?`133 )134 .get(...args, Math.floor(cnt / 2)) as { v: number } | undefined;135 return row?.v ?? null;136}137138/** Statistiques complètes d'une municipalité (cache mémoire). */139export function munStats(nom: string): MunStats | null {140 const cached = statsCache.get(nom);141 if (cached) return cached;142 const stats = cacheDisque<MunStats | null>(`munStats:v1:${nom}`, TTL_ROLE_MS, () => calculerMunStats(nom));143 if (stats) statsCache.set(nom, stats);144 return stats;145}146147function calculerMunStats(nom: string): MunStats | null {148 const db = getDb();149 const base = db150 .prepare(151 `SELECT COUNT(*) AS n, SUM(est_2026) AS t26, SUM(est_2021) AS t21152 FROM units WHERE municipalite = ?`153 )154 .get(nom) as { n: number; t26: number | null; t21: number | null };155 if (!base.n) return null;156 const types = db157 .prepare(158 `SELECT type_prop AS type, COUNT(*) AS n, SUM(est_2026) AS total2026159 FROM units WHERE municipalite = ?160 GROUP BY type_prop ORDER BY n DESC`161 )162 .all(nom) as { type: string; n: number; total2026: number }[];163 const stats: MunStats = {164 nom,165 slug: slugify(nom),166 n: base.n,167 total2026: base.t26 ?? 0,168 total2021: base.t21 ?? 0,169 mediane2026: median2026(nom),170 croissancePct:171 base.t21 && base.t26 ? ((base.t26 - base.t21) / base.t21) * 100 : null,172 parType: types.map((t) => ({173 ...t,174 mediane2026: median2026(nom, t.type),175 })),176 };177 return stats;178}179180/** Échantillon de propriétés adressées (les plus valorisées) pour le maillage interne. */181export function sampleUnits(182 nom: string,183 type: string | null,184 limit = 24185): SampleUnit[] {186 const where = type187 ? "municipalite = ? AND type_prop = ?"188 : "municipalite = ?";189 const args: string[] = type ? [nom, type] : [nom];190 return getDb()191 .prepare(192 `SELECT id_provinc, adresse, apt, type_prop, est_2026,193 annee_construction, aire_etages_m2194 FROM units195 WHERE ${where} AND adresse IS NOT NULL AND est_2026 IS NOT NULL196 ORDER BY est_2026 DESC LIMIT ?`197 )198 .all(...args, limit) as SampleUnit[];199}200201let typePairs: { nom: string; type: string }[] | null = null;202203/** Paires municipalité × type existantes (pour le sitemap des pages types). */204export function allMunTypePairs(): { nom: string; type: string }[] {205 if (!typePairs) {206 typePairs = cacheDisque("municipalites-types:v1", TTL_ROLE_MS, () =>207 getDb()208 .prepare(209 `SELECT municipalite AS nom, type_prop AS type210 FROM units WHERE municipalite IS NOT NULL AND municipalite != ''211 GROUP BY municipalite, type_prop`212 )213 .all() as { nom: string; type: string }[]214 );215 }216 return typePairs;217}218219/** Les municipalités les plus proches du centroïde (maillage entre pages voisines). */220export function neighborMunicipalities(nom: string, k = 10): MunSummary[] {221 const all = allMunicipalities();222 const me = all.find((m) => m.nom === nom);223 if (!me) return [];224 return all225 .filter((m) => m.nom !== nom)226 .map((m) => ({227 m,228 d: (m.lat - me.lat) ** 2 + 0.49 * (m.lng - me.lng) ** 2,229 }))230 .sort((a, b) => a.d - b.d)231 .slice(0, k)232 .map((x) => x.m);233}234