SPB Git

Repository Public

ventes.ts 10.9 KB 316 lines typescript

1/**2 * =============================================================================3 *                  SP BOUCHER | SOFTWARE & RESEARCH4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : Vrai-Prix8 * File             : src/lib/ventes.ts9 * Module           : lib10 * Repository       : https://git.spboucher.ai/vrai-prix11 * Created          : 2026-10-2012 * 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// Auteur : Simon-Pierre Boucher — contact@spboucher.ai43// Registre des ventes récentes : lecture de la table `transactions`, alimentée44// en continu par le connecteur scripts/ingest-jdm.mjs (flux « Transactions45// immobilières » du Journal de Québec / Journal de Montréal — api.qub.ca,46// même feed pour les deux quotidiens). Chaque vente est appariée à son unité47// d'évaluation (id_provinc) par le connecteur : le registre mène donc à la48// fiche d'estimation de la propriété.49import { getDb } from "./db";5051export const VENTE_TYPES = ["unifamilial", "condo", "plex", "indéterminé"] as const;52export type VenteType = (typeof VENTE_TYPES)[number];5354/** Libellés français des types de la source (regroupement du rôle, cf. méthodologie JdQ). */55export const VENTE_TYPE_LABELS: Record<string, string> = {56  unifamilial: "Unifamiliale",57  condo: "Condo",58  plex: "Plex",59  indéterminé: "Autre",60};6162/** Périodes proposées (jours) ; `all` = tout le registre. */63export const VENTE_PERIODES: Record<string, number | null> = {64  "30": 30,65  "90": 90,66  "365": 365,67  all: null,68};69export const PERIODE_LABELS: Record<string, string> = {70  "30": "30 derniers jours",71  "90": "90 derniers jours",72  "365": "12 derniers mois",73  all: "Tout le registre (depuis 2021)",74};7576const OVERVIEW_TTL_MS = 10 * 60 * 1000;7778export const VENTES_PAGE_SIZE = 50;79const MAX_PAGE_SIZE = 200;8081export interface VenteFilters {82  /** municipalité (nom exact, insensible à la casse) ou début de nom */83  q: string;84  type: string;85  min: number | null;86  max: number | null;87  periode: string;88  page: number;89  limit: number;90}9192export interface VenteRow {93  id: string;94  date: string;95  amount: number;96  street: string | null;97  city: string | null;98  property_type: string | null;99  year_built: number | null;100  floor_area: number | null;101  land_area: number | null;102  id_provinc: string | null;103  valeur_role: number | null;104  lat?: number | null;105  lng?: number | null;106}107108export interface VentesPage {109  rows: VenteRow[];110  total: number;111  page: number;112  pages: number;113  limit: number;114  since: string | null;115  filters: VenteFilters;116}117118export interface VentesOverview {119  maxDate: string | null;120  n30: number;121  n90: number;122  n365: number;123  median30: number | null;124  byType30: { type: string; n: number; median: number | null }[];125}126127function isoDaysAgo(days: number): string {128  const d = new Date();129  d.setUTCDate(d.getUTCDate() - days);130  return d.toISOString().slice(0, 10);131}132133function toInt(v: unknown, fallback: number): number {134  const n = typeof v === "string" ? parseInt(v.replace(/[^\d]/g, ""), 10) : Number(v);135  return Number.isFinite(n) && n >= 0 ? n : fallback;136}137138/** Normalise des paramètres d'URL (page ou API) en filtres sûrs. */139export function parseVenteFilters(140  sp: Record<string, string | string[] | undefined> | URLSearchParams141): VenteFilters {142  const get = (k: string): string => {143    const v = sp instanceof URLSearchParams ? sp.get(k) : sp[k];144    const s = Array.isArray(v) ? v[0] : v;145    return (s ?? "").toString().trim();146  };147  const type = get("type");148  const periode = get("periode");149  const minS = get("min");150  const maxS = get("max");151  return {152    q: get("q").slice(0, 80),153    type: (VENTE_TYPES as readonly string[]).includes(type) ? type : "",154    min: minS ? toInt(minS, 0) || null : null,155    max: maxS ? toInt(maxS, 0) || null : null,156    periode: periode in VENTE_PERIODES ? periode : "90",157    page: Math.max(1, toInt(get("page"), 1)),158    limit: Math.min(MAX_PAGE_SIZE, Math.max(1, toInt(get("limit"), VENTES_PAGE_SIZE))),159  };160}161162/** Clause WHERE + paramètres pour un jeu de filtres. */163function whereFor(f: VenteFilters): { where: string; args: (string | number)[]; since: string | null } {164  const conds: string[] = ["amount > 0"];165  const args: (string | number)[] = [];166  // « all » vaut null (aucune borne) : ne pas le confondre avec une période inconnue167  const days = f.periode in VENTE_PERIODES ? VENTE_PERIODES[f.periode] : 90;168  const since = days == null ? null : isoDaysAgo(days);169  if (since) {170    conds.push("date >= ?");171    args.push(since);172  }173  if (f.q) {174    // nom exact d'abord (index city NOCASE) ; sinon début de nom175    const exact = (176      getDb()177        .prepare("SELECT 1 AS ok FROM transactions WHERE city = ? COLLATE NOCASE LIMIT 1")178        .get(f.q) as { ok: number } | undefined179    )?.ok;180    if (exact) {181      conds.push("city = ? COLLATE NOCASE");182      args.push(f.q);183    } else {184      conds.push("city LIKE ? COLLATE NOCASE");185      args.push(`${f.q.replace(/[%_]/g, "")}%`);186    }187  }188  if (f.type) {189    conds.push("property_type = ?");190    args.push(f.type);191  }192  if (f.min != null) {193    conds.push("amount >= ?");194    args.push(f.min);195  }196  if (f.max != null) {197    conds.push("amount <= ?");198    args.push(f.max);199  }200  return { where: conds.join(" AND "), args, since };201}202203/** Totaux par jeu de filtres, gardés 10 min (compter 780 000 lignes à chaque page coûte cher). */204const totaux = new Map<string, { at: number; n: number }>();205function totalCache(cle: string, compter: () => number): number {206  const e = totaux.get(cle);207  if (e && Date.now() - e.at < OVERVIEW_TTL_MS) return e.n;208  const n = compter();209  if (totaux.size > 500) totaux.clear();210  totaux.set(cle, { at: Date.now(), n });211  return n;212}213214/** Page du registre (tri : date décroissante, puis montant). */215export function ventesRecentes(f: VenteFilters): VentesPage {216  const db = getDb();217  const { where, args, since } = whereFor(f);218  const total = totalCache(`${where}|${args.join("|")}`, () =>219    (db.prepare(`SELECT COUNT(*) AS n FROM transactions WHERE ${where}`).get(...args) as { n: number }).n220  );221  const pages = Math.max(1, Math.ceil(total / f.limit));222  const page = Math.min(f.page, pages);223  const rows = db224    .prepare(225      `SELECT id, date, amount, street, city, property_type, year_built, floor_area,226              land_area, id_provinc, valeur_role, lat, lng227       FROM transactions WHERE ${where}228       ORDER BY date DESC, amount DESC229       LIMIT ? OFFSET ?`230    )231    .all(...args, f.limit, (page - 1) * f.limit) as VenteRow[];232  return { rows, total, page, pages, limit: f.limit, since, filters: { ...f, page } };233}234235function medianAmount(where: string, args: (string | number)[]): number | null {236  const db = getDb();237  const n = (db.prepare(`SELECT COUNT(*) AS n FROM transactions WHERE ${where}`).get(...args) as { n: number }).n;238  if (!n) return null;239  const row = db240    .prepare(`SELECT amount FROM transactions WHERE ${where} ORDER BY amount LIMIT 1 OFFSET ?`)241    .get(...args, Math.floor(n / 2)) as { amount: number } | undefined;242  return row?.amount ?? null;243}244245let overviewCache: { at: number; value: VentesOverview } | null = null;246247/** Tuiles de tête du registre (cache mémoire 10 min — le connecteur est quotidien). */248export function ventesOverview(): VentesOverview {249  if (overviewCache && Date.now() - overviewCache.at < OVERVIEW_TTL_MS) return overviewCache.value;250  const db = getDb();251  const count = (since: string) =>252    (db.prepare("SELECT COUNT(*) AS n FROM transactions WHERE date >= ? AND amount > 0").get(since) as { n: number }).n;253  const d30 = isoDaysAgo(30);254  const maxDate = (db.prepare("SELECT MAX(date) AS d FROM transactions").get() as { d: string | null }).d;255  const byType30 = (256    db257      .prepare(258        `SELECT property_type AS type, COUNT(*) AS n FROM transactions259         WHERE date >= ? AND amount > 0 AND property_type IS NOT NULL260         GROUP BY property_type ORDER BY n DESC`261      )262      .all(d30) as { type: string; n: number }[]263  ).map((t) => ({264    ...t,265    median: medianAmount("date >= ? AND amount > 0 AND property_type = ?", [d30, t.type]),266  }));267  const value: VentesOverview = {268    maxDate,269    n30: count(d30),270    n90: count(isoDaysAgo(90)),271    n365: count(isoDaysAgo(365)),272    median30: medianAmount("date >= ? AND amount > 0", [d30]),273    byType30,274  };275  overviewCache = { at: Date.now(), value };276  return value;277}278279export interface VentesMunicipalite {280  rows: VenteRow[];281  n365: number;282  median365: number | null;283}284285/** Dernières ventes d'une municipalité (nom du rôle ; la source emploie les mêmes noms à 99 %). */286export function ventesParMunicipalite(nom: string, limit = 12): VentesMunicipalite {287  const db = getDb();288  const rows = db289    .prepare(290      `SELECT id, date, amount, street, city, property_type, year_built, floor_area,291              land_area, id_provinc, valeur_role292       FROM transactions293       WHERE city = ? COLLATE NOCASE AND amount > 0294       ORDER BY date DESC, amount DESC LIMIT ?`295    )296    .all(nom, limit) as VenteRow[];297  const since = isoDaysAgo(365);298  const w = "city = ? COLLATE NOCASE AND amount > 0 AND date >= ?";299  const n365 = (db.prepare(`SELECT COUNT(*) AS n FROM transactions WHERE ${w}`).get(nom, since) as { n: number }).n;300  return { rows, n365, median365: n365 ? medianAmount(w, [nom, since]) : null };301}302303/** « 7 oct. 2026 » */304export function dateFrLong(iso: string): string {305  const d = new Date(`${iso}T12:00:00Z`);306  if (Number.isNaN(d.getTime())) return iso;307  return d.toLocaleDateString("fr-CA", { day: "numeric", month: "short", year: "numeric", timeZone: "UTC" });308}309310/** Écart prix de vente / valeur au rôle, en % (null si rôle absent ou aberrant). */311export function vsRolePct(amount: number, valeurRole: number | null): number | null {312  if (valeurRole == null || valeurRole <= 0) return null;313  const p = (amount / valeurRole - 1) * 100;314  return Math.abs(p) < 400 ? p : null;315}316
Files main
Menu

Theme