Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : UQO Éval — Le Grand Défi Immobilier8 * File : packages/engine/src/snapshot.ts9 * Module : engine10 * Repository : https://git.spboucher.ai/uqo-eval-jeux11 * Project Website : https://jeux.uqo-eval.app12 * Created : 2026-11-2513 * Last Modified : 2026-11-2514 *15 * Author : Simon-Pierre Boucher16 * Position : Professor of Finance17 * Institution : Université du Québec en Outaouais (UQO)18 * Organization : SP Boucher19 * Website : https://spboucher.ai20 * Git : https://git.spboucher.ai21 *22 * Preferred Contact: contact@spboucher.ai23 * Development : dev@spboucher.ai24 * Support : support@spboucher.ai25 * Security/Admin : admin@spboucher.ai26 *27 * Copyright (c) 202628 * Simon-Pierre Boucher29 * All rights reserved where applicable. This file is governed by the30 * applicable project license, copyright notices and relevant law.31 * Existing third-party rights and notices remain unaffected.32 *33 * License : None specified (no license file in this repository)34 *35 * Do not embed credentials, private keys, access tokens,36 * certificates or confidential personal information.37 *38 * =============================================================================39 * END OF SP BOUCHER SOURCE HEADER40 * =============================================================================41 */4243/**44 * Instantané d'une propriété dans une compétition, fiche publique envoyée au45 * navigateur (sans prix ni identifiant de la source) et rétroaction46 * pédagogique affichée après la réponse.47 */48import { formatDate, formatDecimal, formatInt, formatLivingArea, formatLotArea, formatMoney, formatPercent, formatSignedMoney } from "./format.ts";49import { createRng, hashSeed } from "./rng.ts";50import { answerMetrics, median } from "./scoring.ts";51import { CATEGORY_LABELS, CATEGORY_PLURALS, type Course, type NormalizedProperty } from "./types.ts";5253/** Données figées à la génération de la banque (serveur seulement). */54export type PropertySnapshot = Omit<NormalizedProperty, "sourceUid" | "source" | "imageUrls" | "dedupeKeys" | "qualityScore">;5556export function toSnapshot(p: NormalizedProperty): PropertySnapshot {57 const { sourceUid: _uid, source: _source, imageUrls: _images, dedupeKeys: _keys, qualityScore: _quality, ...rest } = p;58 return rest;59}6061/** Contexte de marché calculé sur les propriétés comparables au moment de la génération. */62export interface MarketContext {63 /** Portée de la comparaison : même catégorie dans la municipalité, sinon dans la région. */64 scope: "municipalite" | "region";65 scopeLabel: string;66 n: number;67 medianPrice: number;68 /** Centile (0 à 100) du prix affiché parmi les comparables. */69 percentile: number;70 medianPricePerSqft: number | null;71 nPerSqft: number;72}7374export const MIN_COMPARABLES = 8;7576/** Prix (et prix au pied carré) d'un groupe de propriétés comparables. */77export interface ComparableGroup {78 prices: readonly number[];79 perSqft: readonly number[];80}8182export type ComparableLookup = (scope: MarketContext["scope"], category: string, key: string) => ComparableGroup | null;8384/** Recherche de comparables à partir d'un bassin en mémoire (tests, simulations). */85export function poolLookup(pool: readonly NormalizedProperty[]): ComparableLookup {86 return (scope, category, key) => {87 const group = pool.filter(88 (o) => o.category === category && (scope === "municipalite" ? o.municipality === key : o.regionCode === key),89 );90 return {91 prices: group.map((o) => o.price),92 perSqft: group.filter((o) => o.livingAreaSqft).map((o) => Math.round(o.price / o.livingAreaSqft!)),93 };94 };95}9697/** Retire une occurrence de `value` : la propriété ne se compare pas à elle-même. */98function without(values: readonly number[], value: number): number[] {99 const out = [...values];100 const at = out.indexOf(value);101 if (at >= 0) out.splice(at, 1);102 return out;103}104105export function buildMarketContext(p: NormalizedProperty, lookup: ComparableLookup): MarketContext | null {106 const ownPerSqft = p.livingAreaSqft ? Math.round(p.price / p.livingAreaSqft) : null;107 const candidates: { scope: MarketContext["scope"]; key: string | null; label: string }[] = [108 { scope: "municipalite", key: p.municipality, label: p.municipality },109 { scope: "region", key: p.regionCode, label: p.regionName ?? "" },110 ];111 for (const { scope, key, label } of candidates) {112 if (!key) continue;113 const group = lookup(scope, p.category, key);114 if (!group) continue;115 const prices = without(group.prices, p.price);116 if (prices.length < MIN_COMPARABLES) continue;117 const perSqft = ownPerSqft === null ? [...group.perSqft] : without(group.perSqft, ownPerSqft);118 const below = prices.filter((v) => v < p.price).length;119 const equal = prices.filter((v) => v === p.price).length;120 return {121 scope,122 scopeLabel: label,123 n: prices.length,124 medianPrice: Math.round(median(prices)),125 percentile: Math.round((100 * (below + equal / 2)) / prices.length),126 medianPricePerSqft: perSqft.length >= MIN_COMPARABLES ? Math.round(median(perSqft)) : null,127 nPerSqft: perSqft.length,128 };129 }130 return null;131}132133export interface Fact {134 key: string;135 label: string;136 value: string;137}138139export interface PublicCard {140 categoryLabel: string;141 subtype: string | null;142 municipality: string;143 sector: string | null;144 regionName: string | null;145 /** Caractéristiques principales (chiffres clés). */146 facts: Fact[];147 /** Caractéristiques secondaires. */148 details: Fact[];149 description: string | null;150 /** Emplacement approximatif : centre décalé et rayon, jamais l'adresse civique. */151 location: { lat: number; lng: number; radiusM: number } | null;152}153154const STREET_TYPES =155 "[Rr]ues?|[Aa]venue|[Aa]v\\.|[Bb]oulevard|[Bb]oul\\.|[Bb]lvd\\.?|[Cc]hemin|[Cc]h\\.|[Pp]lace|[Rr]ang|[Mm]ont[ée]e|[Rr]oute|[Rr]te|[Cc]roissant|[Ii]mpasse|[Aa]ll[ée]e|[Tt]errasse|[Cc]arr[ée]|[Pp]romenade|[Cc][ôo]te|[Cc]ours|[Rr]uelle|[Ss]entier|[Aa]utoroute";156/** « 123, rue des Érables », « chemin du Lac-Noir », « Place Renaud » : odonyme français, avec ou sans numéro. */157const STREET_FR = new RegExp(158 `(?:\\b\\d{1,5}[A-Za-z]?\\s*,?\\s+)?\\b(?:${STREET_TYPES})\\s+(?:(?:de la|de l['’]|des|du|de|d['’]|la|le|les|l['’])\\s*)*[A-ZÀ-Ý0-9][\\wÀ-ÿ'’-]*(?:[ -]+(?:(?:de la|de l['’]|des|du|de|d['’])\\s*)?[A-ZÀ-Ý][\\wÀ-ÿ'’-]*){0,3}`,159 "g",160);161/** « 123 Maple Street », « Elm Road » : odonyme anglais. */162const STREET_EN = /(?:\b\d{1,5}\s+)?\b[A-Z][\w'’-]+(?:\s+[A-Z][\w'’-]+)?\s+(?:Street|Road|Avenue|Drive|Crescent|Lane|Court|Boulevard|Blvd)\b\.?/g;163/** « 7928 Kingsley Ave » : générique anglais abrégé, reconnu seulement derrière un numéro civique. */164const STREET_EN_SHORT = /\b\d{1,5}\s+[A-Z][\w'’-]+(?:\s+[A-Z][\w'’-]+)?\s+(?:Ave|St|Rd|Dr|Cres|Ln|Ct|Pl|Hwy)\b\.?/g;165/** Numéro civique isolé devant une virgule ou un mot : « au 1450, » */166const CIVIC = /\b(?:au|du|le)\s+\d{2,5}\s*,/gi;167168/**169 * Retire d'un texte tout nom de rue : une adresse, même partielle, suffit à170 * retrouver l'annonce d'origine (et donc son prix) par une simple recherche.171 */172export function redactStreets(text: string | null): string | null {173 if (!text) return null;174 const out = text175 .replace(STREET_FR, "[rue retirée]")176 .replace(STREET_EN, "[rue retirée]")177 .replace(STREET_EN_SHORT, "[rue retirée]")178 .replace(CIVIC, "[adresse retirée],")179 .replace(/(\[(?:rue|adresse) retirée\][\s,]*){2,}/g, "[adresse retirée] ")180 .replace(/\s+/g, " ")181 .trim();182 return out.length >= 60 ? out : null;183}184185/** Un secteur n'est affiché que s'il désigne un quartier ou un arrondissement, jamais une rue ni une adresse. */186export function publicSector(sector: string | null): string | null {187 if (!sector) return null;188 const value = sector.trim();189 if (!value || /\d/.test(value)) return null;190 if (new RegExp(`^(?:${STREET_TYPES})\\s`).test(value) || /\b(?:Street|Road|Avenue|Drive|Crescent|Lane|Court|Blvd)\b/.test(value)) return null;191 return value;192}193194const plural = (n: number, one: string, many: string): string => `${formatInt(n)} ${n > 1 ? many : one}`;195196export function toPublicCard(s: PropertySnapshot, opaqueSeed: string): PublicCard {197 const facts: Fact[] = [];198 if (s.bedrooms) facts.push({ key: "bedrooms", label: s.bedrooms > 1 ? "chambres" : "chambre", value: String(s.bedrooms) });199 if (s.bathrooms) {200 facts.push({ key: "bathrooms", label: s.bathrooms > 1 ? "salles de bain" : "salle de bain", value: String(s.bathrooms) });201 }202 if (s.powderRooms) facts.push({ key: "powder", label: s.powderRooms > 1 ? "salles d'eau" : "salle d'eau", value: String(s.powderRooms) });203 if (s.livingAreaSqft) facts.push({ key: "area", label: "Superficie habitable", value: formatLivingArea(s.livingAreaSqft) });204 if (s.lotAreaSqft) facts.push({ key: "lot", label: "Terrain", value: formatLotArea(s.lotAreaSqft) });205 if (s.yearBuilt) facts.push({ key: "year", label: "Construction", value: String(s.yearBuilt) });206207 const details: Fact[] = [];208 const add = (key: string, label: string, value: string | null | undefined): void => {209 if (value) details.push({ key, label, value });210 };211 add("rooms", "Pièces", s.rooms ? String(s.rooms) : null);212 add("floors", "Étages", s.floors ? String(s.floors) : null);213 add("unitFloor", "Étage de l'unité", s.unitFloor);214 add("garage", "Garage", s.garage);215 add("parking", "Stationnement", s.parking);216 add("basement", "Sous-sol", s.basement);217 add("pool", "Piscine", s.pool);218 add("heating", "Chauffage", s.heating);219 add("energy", "Énergie", s.heatingEnergy);220 add("fireplace", "Foyer ou poêle", s.fireplace);221 add("siding", "Revêtement extérieur", s.siding);222 add("roofing", "Toiture", s.roofing);223 add("foundation", "Fondation", s.foundation);224 add("windows", "Fenêtres", s.windows);225 add("view", "Vue", s.view);226 add("waterfront", "Plan d'eau", s.waterfront);227 add("site", "Particularités du site", s.siteFeatures);228 add("condoFees", "Frais de copropriété", s.condoFeesYearly ? `${formatMoney(s.condoFeesYearly)} par an` : null);229230 let location: PublicCard["location"] = null;231 if (s.lat !== null && s.lng !== null) {232 // Décalage déterministe de 120 à 320 m : la carte montre le quartier, pas l'adresse.233 const rng = createRng(hashSeed(`loc:${opaqueSeed}`));234 const angle = rng.range(0, 2 * Math.PI);235 const distance = rng.range(120, 320);236 const dLat = (distance * Math.cos(angle)) / 111_320;237 const dLng = (distance * Math.sin(angle)) / (111_320 * Math.cos((s.lat * Math.PI) / 180));238 location = { lat: Number((s.lat + dLat).toFixed(4)), lng: Number((s.lng + dLng).toFixed(4)), radiusM: 600 };239 }240 return {241 categoryLabel: CATEGORY_LABELS[s.category],242 subtype: s.subtype,243 municipality: s.municipality,244 // Ni adresse, ni nom de rue, ni lien vers l'annonce : rien qui permette de la retrouver.245 sector: publicSector(s.sector),246 regionName: s.regionName,247 facts,248 details,249 description: redactStreets(s.description),250 location,251 };252}253254export const PRICE_DISCLAIMER =255 "Le prix affiché correspond au prix demandé par le vendeur à une date donnée. Il ne constitue pas nécessairement le prix de transaction ni la valeur marchande de la propriété.";256257export interface Insight {258 key: string;259 label: string;260 value: string;261 note?: string;262}263264export interface Feedback {265 verdict: "exact" | "sous-estimation" | "surestimation";266 correctPrice: number;267 chosenPrice: number;268 /** Écart signé en dollars (prix choisi − prix affiché). */269 delta: number;270 /** Erreur relative, en pourcentage. */271 relErrorPct: number;272 headline: string;273 priceObservedAt: string;274 insights: Insight[];275 reflections: { course: Course; question: string }[];276 disclaimer: string;277}278279function reflectionsFor(s: PropertySnapshot, ctx: MarketContext | null, seed: string, course: Course | null): Feedback["reflections"] {280 const category = CATEGORY_LABELS[s.category].toLowerCase();281 const cost: string[] = [282 "Quels éléments de cette propriété pourraient influencer son coût de remplacement ou sa dépréciation ?",283 ];284 if (s.yearBuilt) {285 const age = Math.max(0, Number(s.priceObservedAt.slice(0, 4)) - s.yearBuilt);286 cost.push(287 `Construite en ${s.yearBuilt}, cette propriété a environ ${age} ans. Quelles formes de dépréciation (physique, fonctionnelle, économique) faudrait-il examiner sur place avant de conclure ?`,288 );289 }290 if (s.assessment?.land && s.assessment.building) {291 cost.push(292 `Le rôle d'évaluation répartit la valeur entre le terrain (${formatMoney(s.assessment.land)}) et le bâtiment (${formatMoney(s.assessment.building)}). En quoi cette répartition éclaire-t-elle une démarche par le coût ?`,293 );294 }295 const materials = [s.siding, s.roofing, s.foundation].filter(Boolean).join(" · ");296 if (materials) {297 cost.push(`Matériaux relevés : ${materials}. Comment la qualité de construction se refléterait-elle dans un coût de remplacement à neuf ?`);298 }299 if (s.garage || s.pool) {300 cost.push("Quels éléments accessoires (garage, piscine, aménagements) devraient être estimés séparément du bâtiment principal ?");301 }302303 const comparison: string[] = [304 `Quels ajustements seraient nécessaires pour comparer cette propriété à une ${category} similaire située dans une autre municipalité ?`,305 "Quelles caractéristiques retiendriez-vous pour juger de la comparabilité d'une autre propriété avec celle-ci ?",306 ];307 if (ctx) {308 comparison.push(309 `Le prix médian affiché des ${CATEGORY_PLURALS[s.category]} comparables (${ctx.scopeLabel}) est de ${formatMoney(ctx.medianPrice)} (n = ${ctx.n}). Quelles différences entre propriétés examineriez-vous pour comprendre l'écart, sans présumer d'un lien de cause à effet ?`,310 );311 }312 if (s.livingAreaSqft) {313 comparison.push("Quelle unité de comparaison retiendriez-vous ici (prix global, prix au pied carré, autre) et pourquoi ?");314 }315316 const rng = createRng(hashSeed(`reflexion:${seed}`));317 const all: Feedback["reflections"] = [318 { course: "IMM1003", question: rng.pick(cost) },319 { course: "IMM1033", question: rng.pick(comparison) },320 ];321 return course ? all.filter((r) => r.course === course) : all;322}323324export function buildFeedback(325 s: PropertySnapshot,326 ctx: MarketContext | null,327 chosenPrice: number,328 seed: string,329 course: Course | null,330): Feedback {331 const correctPrice = s.price;332 const m = answerMetrics(chosenPrice, correctPrice);333 const verdict: Feedback["verdict"] = m.isCorrect ? "exact" : m.signedRelError < 0 ? "sous-estimation" : "surestimation";334 const headline = m.isCorrect335 ? "Exact : vous avez reconnu le prix affiché."336 : verdict === "sous-estimation"337 ? "Vous avez sous-estimé le prix affiché."338 : "Vous avez surestimé le prix affiché.";339340 const insights: Insight[] = [];341 if (s.livingAreaSqft) {342 const perSqft = correctPrice / s.livingAreaSqft;343 insights.push({344 key: "ppsf",345 label: "Prix affiché au pied carré",346 value: `${formatInt(perSqft)} $/pi²`,347 note:348 ctx?.medianPricePerSqft != null349 ? `Médiane des ${CATEGORY_PLURALS[s.category]} comparables (${ctx.scopeLabel}) : ${formatInt(ctx.medianPricePerSqft)} $/pi² (n = ${ctx.nPerSqft}).`350 : undefined,351 });352 }353 if (ctx) {354 insights.push({355 key: "median",356 label: `Prix médian affiché — ${CATEGORY_PLURALS[s.category]}, ${ctx.scopeLabel}`,357 value: formatMoney(ctx.medianPrice),358 note: `Cette propriété se situe au ${ctx.percentile}e centile des ${ctx.n} prix affichés comparables.`,359 });360 }361 if (s.assessment) {362 const ratio = correctPrice / s.assessment.total;363 insights.push({364 key: "assessment",365 label: `Évaluation municipale${s.assessment.year ? ` (rôle ${s.assessment.year})` : ""}`,366 value: formatMoney(s.assessment.total),367 note: `Le prix affiché équivaut à ${formatDecimal(ratio, 2)} fois l'évaluation municipale. Le rôle reflète le marché à une date de référence antérieure.`,368 });369 }370 const firstPoint = s.priceHistory[0];371 if (s.priceHistory.length >= 2 && firstPoint && firstPoint.price !== correctPrice) {372 const change = (correctPrice - firstPoint.price) / firstPoint.price;373 insights.push({374 key: "history",375 label: "Révision du prix affiché",376 value: `${formatMoney(firstPoint.price)} → ${formatMoney(correctPrice)}`,377 note: `Variation de ${change > 0 ? "+" : "−"}${formatPercent(Math.abs(change) * 100)} depuis le ${formatDate(firstPoint.date)}.`,378 });379 }380 if (s.annualRevenue) {381 insights.push({382 key: "revenue",383 label: "Revenus bruts annuels déclarés",384 value: formatMoney(s.annualRevenue),385 note: `Rapport prix affiché / revenus bruts : ${formatDecimal(correctPrice / s.annualRevenue, 1)}.`,386 });387 }388 if (s.municipalTaxes) {389 insights.push({ key: "taxes", label: "Taxes municipales annuelles", value: formatMoney(s.municipalTaxes) });390 }391 if (s.firstSeenAt) {392 insights.push({ key: "seen", label: "Première observation de l'annonce", value: formatDate(s.firstSeenAt) });393 }394395 return {396 verdict,397 correctPrice,398 chosenPrice,399 delta: chosenPrice - correctPrice,400 relErrorPct: m.relError * 100,401 headline,402 priceObservedAt: s.priceObservedAt,403 insights,404 reflections: reflectionsFor(s, ctx, seed, course),405 disclaimer: PRICE_DISCLAIMER,406 };407}408409export { formatSignedMoney, plural };410