Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : Vrai-Prix8 * File : src/lib/db.ts9 * Module : lib10 * Repository : https://git.spboucher.ai/vrai-prix11 * Created : 2026-08-0912 * 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 */4142import type Database from "better-sqlite3";43import path from "path";44import { baseLectureSeule } from "./sqlite";4546/**47 * Base principale (unités du rôle, transactions, indice de marché).48 * PARTAGÉE avec la v1 et ouverte en LECTURE SEULE : la v2 n'y crée ni index ni49 * ligne. Les index utilisés ci-dessous (idx_units_mun_nocase_geo,50 * idx_units_mun_nocase_est, idx_tx_recent, idx_tx_city_date, idx_tx_prov,51 * idx_tx_geo, idx_units_geo) sont créés par la v1 à son démarrage.52 */53export const getDb: () => Database.Database = baseLectureSeule(54 () => process.env.VRAIPRIX_DB ?? path.join(process.cwd(), "data", "vraiprix.db")55);5657export interface UnitRow {58 id_provinc: string;59 adresse: string | null;60 apt: string | null;61 municipalite: string | null;62 arrond: string | null;63 code_mun: string | null;64 lat: number;65 lng: number;66 cubf: number | null;67 cubf_libelle: string | null;68 type_prop: string;69 annee_construction: number | null;70 annee_estimee: string | null;71 aire_etages_m2: number | null;72 superficie_terrain_m2: number | null;73 front_terrain_m: number | null;74 nb_etages: number | null;75 nb_logements: number | null;76 nb_locaux_non_resid: number | null;77 nb_chambres_locatives: number | null;78 lien_physique: string | null;79 genre_construction: string | null;80 matricule: string | null;81 unite_voisinage: string | null;82 n_adresses: number | null;83 dat_cond_marche: string | null;84 valeur_terrain: number | null;85 valeur_batiment: number | null;86 valeur_role: number | null;87 valeur_anterieure: number | null;88 est_2021: number | null;89 est_2022: number | null;90 est_2023: number | null;91 est_2024: number | null;92 est_2025: number | null;93 est_2026: number | null;94 p10: number | null;95 p90: number | null;96 est_hedo: number | null;97}9899export interface TxRow {100 id: string;101 date: string;102 amount: number;103 street: string | null;104 city: string | null;105 lat: number;106 lng: number;107 property_type: string | null;108 year_built: number | null;109 floor_area: number | null;110 building_type: string | null;111 id_provinc: string | null;112 valeur_role: number | null;113 land_area: number | null;114}115116export function getUnit(id: string): UnitRow | undefined {117 return getDb()118 .prepare("SELECT * FROM units WHERE id_provinc = ?")119 .get(id) as UnitRow | undefined;120}121122/** Candidats comparables dans une boîte englobante autour du point. */123export function getCandidates(124 lat: number,125 lng: number,126 halfDeg: number,127 sinceDate: string,128 limit = 500129): TxRow[] {130 return getDb()131 .prepare(132 `SELECT * FROM transactions133 WHERE lat BETWEEN ? AND ? AND lng BETWEEN ? AND ?134 AND date >= ? AND amount >= 50000135 LIMIT ?`136 )137 .all(lat - halfDeg, lat + halfDeg, lng - halfDeg, lng + halfDeg, sinceDate, limit) as TxRow[];138}139140export function getMarketIndex(typeProp: string): { month: string; idx: number }[] {141 return getDb()142 .prepare(143 "SELECT month, idx FROM market_index WHERE type_prop = ? ORDER BY month"144 )145 .all(typeProp) as { month: string; idx: number }[];146}147148export function searchUnits(q: string, limit = 8): (UnitRow & { score: number })[] {149 const cleaned = q150 .replace(/[^\p{L}\p{N}\s'-]/gu, " ")151 .trim()152 .split(/\s+/)153 .filter((t) => t.length > 0)154 .map((t) => `"${t}"*`)155 .join(" ");156 if (!cleaned) return [];157 return getDb()158 .prepare(159 `SELECT u.*, bm25(units_fts) AS score160 FROM units_fts JOIN units u ON u.rowid = units_fts.rowid161 WHERE units_fts MATCH ?162 ORDER BY score LIMIT ?`163 )164 .all(cleaned, limit) as (UnitRow & { score: number })[];165}166167export interface NearbyUnitRow {168 id_provinc: string;169 adresse: string | null;170 apt: string | null;171 municipalite: string | null;172 type_prop: string;173 lat: number;174 lng: number;175 est_2026: number | null;176}177178/** Unités d'évaluation dans une boîte englobante (recherche par carte). */179export function unitsNear(180 lat: number,181 lng: number,182 halfLat: number,183 halfLng: number,184 limit = 300185): NearbyUnitRow[] {186 // ORDER BY distance au centre : sans tri, l'index (lat, lng) renverrait187 // les N unités les plus au sud de la boîte (bande horizontale).188 return getDb()189 .prepare(190 `SELECT id_provinc, adresse, apt, municipalite, type_prop, lat, lng, est_2026191 FROM units192 WHERE lat BETWEEN ? AND ? AND lng BETWEEN ? AND ?193 ORDER BY (lat - ?) * (lat - ?) + 0.49 * (lng - ?) * (lng - ?)194 LIMIT ?`195 )196 .all(197 lat - halfLat,198 lat + halfLat,199 lng - halfLng,200 lng + halfLng,201 lat,202 lat,203 lng,204 lng,205 limit206 ) as NearbyUnitRow[];207}208209export function municipalityCenter(210 name: string211): { lat: number; lng: number; n: number } | undefined {212 return getDb()213 .prepare(214 `SELECT AVG(lat) AS lat, AVG(lng) AS lng, COUNT(*) AS n215 FROM units WHERE municipalite = ? COLLATE NOCASE`216 )217 .get(name) as { lat: number; lng: number; n: number } | undefined;218}219220/** Rang de la valeur dans la municipalité (percentile sur est_2026). */221export function municipalityPercentile(222 municipalite: string,223 value: number224): { below: number; total: number } | null {225 const row = getDb()226 .prepare(227 `SELECT COUNT(*) AS total,228 SUM(CASE WHEN est_2026 < ? THEN 1 ELSE 0 END) AS below229 FROM units230 WHERE municipalite = ? COLLATE NOCASE231 AND est_2026 IS NOT NULL AND est_2026 > 0`232 )233 .get(value, municipalite) as { total: number; below: number | null } | undefined;234 if (!row || row.total < 30) return null;235 return { below: row.below ?? 0, total: row.total };236}237238export interface RecentSaleRow {239 id: string;240 date: string;241 amount: number;242 street: string | null;243 city: string | null;244 property_type: string | null;245 id_provinc: string | null;246 valeur_role: number | null;247}248249/** Dernières ventes publiées appariées à une unité (fil « ventes récentes »). */250export function recentSales(limit = 6): RecentSaleRow[] {251 return getDb()252 .prepare(253 `SELECT id, date, amount, street, city, property_type, id_provinc, valeur_role254 FROM transactions255 WHERE id_provinc IS NOT NULL AND street IS NOT NULL AND amount >= 50000256 ORDER BY date DESC, amount DESC257 LIMIT ?`258 )259 .all(limit) as RecentSaleRow[];260}261262export function salesCountSince(sinceDate: string): number {263 const row = getDb()264 .prepare("SELECT COUNT(*) AS n FROM transactions WHERE date >= ?")265 .get(sinceDate) as { n: number };266 return row.n;267}268269/** Ventes publiées d'une unité (toutes, de la plus récente à la plus ancienne). */270export function salesOfUnit(id: string): TxRow[] {271 return getDb()272 .prepare("SELECT * FROM transactions WHERE id_provinc = ? AND amount > 0 ORDER BY date DESC")273 .all(id) as TxRow[];274}275276/** Série complète de l'indice de marché d'un type (ou de tous les types). */277export interface MarketIndexRow {278 month: string;279 type_prop: string;280 ppm2: number | null;281 idx: number;282 n: number;283}284export function marketIndexRows(typeProp?: string): MarketIndexRow[] {285 const d = getDb();286 return (287 typeProp288 ? d.prepare("SELECT month, type_prop, ppm2, idx, n FROM market_index WHERE type_prop = ? ORDER BY month").all(typeProp)289 : d.prepare("SELECT month, type_prop, ppm2, idx, n FROM market_index ORDER BY type_prop, month").all()290 ) as MarketIndexRow[];291}292293/** Unités dans une boîte englobante (carte), les plus proches du centre d'abord. */294export function unitsInBbox(west: number, south: number, east: number, north: number, limit = 1500): NearbyUnitRow[] {295 const lat = (south + north) / 2;296 const lng = (west + east) / 2;297 return getDb()298 .prepare(299 `SELECT id_provinc, adresse, apt, municipalite, type_prop, lat, lng, est_2026300 FROM units301 WHERE lat BETWEEN ? AND ? AND lng BETWEEN ? AND ?302 ORDER BY (lat - ?) * (lat - ?) + 0.49 * (lng - ?) * (lng - ?)303 LIMIT ?`304 )305 .all(south, north, west, east, lat, lat, lng, lng, limit) as NearbyUnitRow[];306}307308/** Ventes publiées dans une boîte englobante (carte), les plus récentes d'abord. */309export function salesInBbox(west: number, south: number, east: number, north: number, since: string, limit = 1000): TxRow[] {310 return getDb()311 .prepare(312 `SELECT * FROM transactions313 WHERE lat BETWEEN ? AND ? AND lng BETWEEN ? AND ? AND date >= ? AND amount > 0314 ORDER BY date DESC LIMIT ?`315 )316 .all(south, north, west, east, since, limit) as TxRow[];317}318