Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : UQO Éval — Le Grand Défi Immobilier8 * File : tests/unit/snapshot.test.ts9 * Module : tests10 * 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 */4243import { describe, expect, it } from "vitest";44import {45 MIN_COMPARABLES,46 PRICE_DISCLAIMER,47 buildFeedback,48 buildMarketContext,49 poolLookup,50 toPublicCard,51 toSnapshot,52 type MarketContext,53 type NormalizedProperty,54} from "../../packages/engine/src/index.ts";55import { makeProperty } from "../helpers/factories.ts";5657/** Distance en mètres entre deux points (haversine). */58function distanceM(lat1: number, lng1: number, lat2: number, lng2: number): number {59 const rad = Math.PI / 180;60 const a = Math.sin(((lat2 - lat1) * rad) / 2) ** 2 + Math.cos(lat1 * rad) * Math.cos(lat2 * rad) * Math.sin(((lng2 - lng1) * rad) / 2) ** 2;61 return 2 * 6_371_000 * Math.asin(Math.sqrt(a));62}6364const rich = (): NormalizedProperty =>65 makeProperty({66 sourceUid: "centris:28765432",67 source: "centris",68 price: 487_650,69 sector: "Plateau du Parc",70 powderRooms: 1,71 municipalTaxes: 3_456,72 annualRevenue: 31_200,73 assessment: { total: 398_700, land: 120_300, building: 278_400, year: 2024 },74 priceHistory: [{ date: "2026-09-12", price: 512_340 }, { date: "2026-11-01", price: 487_650 }],75 description: "Belle propriété lumineuse dans un quartier paisible.",76 imageUrls: ["https://photos.origine.test/a/1.jpg", "https://photos.origine.test/a/2.jpg"],77 dedupeKeys: ["mls:28765432", "adr:123 rue des erables|gatineau"],78 qualityScore: 93,79 lat: 45.476_512_3,80 lng: -75.701_398_7,81 });8283describe("toSnapshot", () => {84 it("retire l'identifiant source, la source, les URL des photos, les clés de déduplication et la cote de qualité", () => {85 const snapshot = toSnapshot(rich()) as Record<string, unknown>;86 for (const key of ["sourceUid", "source", "imageUrls", "dedupeKeys", "qualityScore"]) expect(snapshot).not.toHaveProperty(key);87 expect(snapshot.price).toBe(487_650);88 expect(snapshot.municipality).toBe("Gatineau");89 });90 it("ne modifie pas la propriété d'origine", () => {91 const p = rich();92 toSnapshot(p);93 expect(p.sourceUid).toBe("centris:28765432");94 expect(p.imageUrls).toHaveLength(2);95 });96});9798describe("toPublicCard — fiche envoyée au navigateur", () => {99 const p = rich();100 const card = toPublicCard(toSnapshot(p), "question-opaque-1");101 const json = JSON.stringify(card);102103 it("n'expose que les champs publics attendus", () => {104 expect(Object.keys(card).sort()).toEqual(["categoryLabel", "description", "details", "facts", "location", "municipality", "regionName", "sector", "subtype"].sort());105 for (const fact of [...card.facts, ...card.details]) expect(Object.keys(fact).sort()).toEqual(["key", "label", "value"]);106 });107 it("ne contient ni le prix, ni l'historique de prix, ni l'évaluation, ni les taxes, ni les revenus", () => {108 const digits = json.replace(/[\s ]/g, "");109 for (const secret of [487_650, 512_340, 398_700, 120_300, 278_400, 3_456, 31_200]) expect(digits).not.toContain(String(secret));110 expect(json).not.toMatch(/price|prix|assessment|évaluation|taxes|revenu/i);111 });112 it("ne contient ni l'identifiant source, ni la source, ni l'URL des photos, ni les clés de déduplication", () => {113 expect(json).not.toContain("28765432");114 expect(json).not.toMatch(/centris|origine\.test|https?:|mls:|adr:/i);115 });116 it("ne contient pas les coordonnées exactes : le point est décalé et arrondi à quatre décimales", () => {117 expect(card.location).not.toBeNull();118 expect(json).not.toContain("45.4765123");119 expect(json).not.toContain("75.7013987");120 expect(card.location!.lat).not.toBe(p.lat);121 expect(card.location!.lng).not.toBe(p.lng);122 expect(card.location!.radiusM).toBe(600);123 expect(String(card.location!.lat).split(".")[1]!.length).toBeLessThanOrEqual(4);124 expect(String(card.location!.lng).split(".")[1]!.length).toBeLessThanOrEqual(4);125 });126 it("décale le point de 120 à 320 m (à l'arrondi de quatre décimales près), dans toutes les directions", () => {127 const snapshot = toSnapshot(p);128 const distances: number[] = [];129 const quadrants = new Set<string>();130 for (let i = 0; i < 2_000; i++) {131 const loc = toPublicCard(snapshot, `graine-${i}`).location!;132 const d = distanceM(p.lat!, p.lng!, loc.lat, loc.lng);133 distances.push(d);134 quadrants.add(`${loc.lat > p.lat! ? "N" : "S"}${loc.lng > p.lng! ? "E" : "O"}`);135 }136 // 4 décimales ≈ 11 m en latitude et 8 m en longitude : tolérance de 10 m sur les bornes.137 expect(Math.min(...distances)).toBeGreaterThanOrEqual(110);138 expect(Math.max(...distances)).toBeLessThanOrEqual(330);139 expect(Math.min(...distances)).toBeLessThan(135);140 expect(Math.max(...distances)).toBeGreaterThan(305);141 expect(quadrants.size).toBe(4);142 });143 it("garde le même décalage pour la même graine et le change avec une autre graine", () => {144 const snapshot = toSnapshot(p);145 expect(toPublicCard(snapshot, "g1").location).toEqual(toPublicCard(snapshot, "g1").location);146 expect(toPublicCard(snapshot, "g1").location).not.toEqual(toPublicCard(snapshot, "g2").location);147 });148 it("n'invente pas d'emplacement quand les coordonnées sont absentes", () => {149 expect(toPublicCard(toSnapshot(makeProperty({ lat: null, lng: null })), "g").location).toBeNull();150 });151 it("présente les chiffres clés avec accord en nombre et double unité", () => {152 const byKey = Object.fromEntries(card.facts.map((f) => [f.key, f]));153 expect(byKey.bedrooms).toMatchObject({ label: "chambres", value: "3" });154 expect(byKey.bathrooms).toMatchObject({ label: "salles de bain", value: "2" });155 expect(byKey.powder).toMatchObject({ label: "salle d'eau", value: "1" });156 expect(byKey.area!.value).toMatch(/^1\s500 pi² \(139 m²\)$/);157 expect(byKey.lot!.value).toMatch(/^6\s000 pi² \(557 m²\)$/);158 expect(byKey.year!.value).toBe("1995");159 });160 it("omet toute caractéristique absente plutôt que d'afficher une valeur vide", () => {161 const bare = toPublicCard(toSnapshot(makeProperty({ bedrooms: null, bathrooms: null, livingAreaSqft: null, lotAreaSqft: null, yearBuilt: null, rooms: null, floors: null, garage: null, basement: null, heating: null, heatingEnergy: null, siding: null, roofing: null, foundation: null, windows: null, parking: null })), "g");162 expect(bare.facts).toEqual([]);163 expect(bare.details).toEqual([]);164 });165 it("affiche les frais de copropriété (charge connue de l'acheteur) mais aucun autre montant", () => {166 const condo = toPublicCard(toSnapshot(makeProperty({ category: "condo", condoFeesYearly: 3_600, lotAreaSqft: null })), "g");167 expect(condo.categoryLabel).toBe("Copropriété");168 const fees = condo.details.find((d) => d.key === "condoFees")!;169 expect(fees.value).toMatch(/^3\s600\s\$ par an$/);170 expect(condo.details.filter((d) => /\$/.test(d.value))).toHaveLength(1);171 });172 it("exprime un grand terrain en hectares", () => {173 const farm = toPublicCard(toSnapshot(makeProperty({ lotAreaSqft: 1_076_390 })), "g");174 expect(farm.facts.find((f) => f.key === "lot")!.value).toMatch(/^10,00 ha/);175 });176});177178describe("buildMarketContext", () => {179 const subject = makeProperty({ sourceUid: "sujet", price: 450_000, livingAreaSqft: 1_500 });180 const neighbours = (n: number, overrides: Partial<NormalizedProperty> = {}): NormalizedProperty[] =>181 Array.from({ length: n }, (_, i) => makeProperty({ sourceUid: `v${i}`, price: 300_000 + i * 25_000, livingAreaSqft: 1_000 + i * 50, ...overrides }));182183 it("compare dans la municipalité quand elle compte assez de comparables, sans compter la propriété elle-même", () => {184 const pool = [subject, ...neighbours(MIN_COMPARABLES)];185 const ctx = buildMarketContext(subject, poolLookup(pool))!;186 expect(ctx.scope).toBe("municipalite");187 expect(ctx.scopeLabel).toBe("Gatineau");188 expect(ctx.n).toBe(8);189 // prix voisins : 300k … 475k par 25k → médiane 387 500190 expect(ctx.medianPrice).toBe(387_500);191 // 6 voisins moins chers (300…425), 1 égal (450) → (6 + 0,5) / 8 = 81 %192 expect(ctx.percentile).toBe(81);193 expect(ctx.nPerSqft).toBe(8);194 });195 it("se replie sur la région quand la municipalité manque de comparables", () => {196 const pool = [subject, ...neighbours(3), ...neighbours(10, { municipality: "Chelsea" }).map((p, i) => ({ ...p, sourceUid: `r${i}` }))];197 const ctx = buildMarketContext(subject, poolLookup(pool))!;198 expect(ctx.scope).toBe("region");199 expect(ctx.scopeLabel).toBe("Outaouais");200 expect(ctx.n).toBe(13);201 });202 it("ne compare pas avec d'autres catégories et retourne null faute de comparables", () => {203 const pool = [subject, ...neighbours(20, { category: "condo" })];204 expect(buildMarketContext(subject, poolLookup(pool))).toBeNull();205 expect(buildMarketContext(subject, poolLookup([subject]))).toBeNull();206 });207 it("ne publie pas de médiane au pied carré sous le seuil de comparables", () => {208 const pool = [subject, ...neighbours(9).map((p, i) => (i < 4 ? p : { ...p, livingAreaSqft: null }))];209 const ctx = buildMarketContext(subject, poolLookup(pool))!;210 expect(ctx.n).toBe(9);211 expect(ctx.nPerSqft).toBe(4);212 expect(ctx.medianPricePerSqft).toBeNull();213 });214});215216describe("buildFeedback — rétroaction après la réponse", () => {217 const p = rich();218 const snapshot = toSnapshot(p);219 const ctx: MarketContext = { scope: "municipalite", scopeLabel: "Gatineau", n: 42, medianPrice: 455_000, percentile: 63, medianPricePerSqft: 298, nPerSqft: 40 };220221 it("rend le verdict « exact » avec un écart nul", () => {222 const f = buildFeedback(snapshot, ctx, 487_650, "q1", null);223 expect(f).toMatchObject({ verdict: "exact", correctPrice: 487_650, chosenPrice: 487_650, delta: 0, relErrorPct: 0 });224 expect(f.headline).toMatch(/^Exact/);225 });226 it("rend le verdict « sous-estimation » avec un écart signé négatif", () => {227 const f = buildFeedback(snapshot, ctx, 437_650, "q1", null);228 expect(f.verdict).toBe("sous-estimation");229 expect(f.delta).toBe(-50_000);230 expect(f.relErrorPct).toBeCloseTo((50_000 / 487_650) * 100, 10);231 expect(f.headline).toMatch(/sous-estimé/);232 });233 it("rend le verdict « surestimation » avec un écart signé positif", () => {234 const f = buildFeedback(snapshot, ctx, 537_650, "q1", null);235 expect(f.verdict).toBe("surestimation");236 expect(f.delta).toBe(50_000);237 expect(f.relErrorPct).toBeCloseTo((50_000 / 487_650) * 100, 10);238 expect(f.headline).toMatch(/surestimé/);239 });240 it("porte toujours la mention : le prix affiché n'est pas nécessairement le prix de transaction", () => {241 for (const chosen of [487_650, 400_000, 600_000]) {242 const f = buildFeedback(snapshot, null, chosen, "q1", "IMM1003");243 expect(f.disclaimer).toBe(PRICE_DISCLAIMER);244 expect(f.disclaimer).toMatch(/prix demandé par le vendeur/);245 expect(f.disclaimer).toMatch(/ne constitue pas nécessairement le prix de transaction ni la valeur marchande/);246 }247 });248 it("donne la date d'observation du prix", () => {249 expect(buildFeedback(snapshot, ctx, 487_650, "q1", null).priceObservedAt).toBe("2026-11-01");250 });251 it("fournit les repères disponibles : pied carré, médiane, évaluation, révision de prix, revenus, taxes, première observation", () => {252 const f = buildFeedback(snapshot, ctx, 487_650, "q1", null);253 const byKey = Object.fromEntries(f.insights.map((i) => [i.key, i]));254 expect(Object.keys(byKey).sort()).toEqual(["assessment", "history", "median", "ppsf", "revenue", "seen", "taxes"]);255 expect(byKey.ppsf!.value).toBe("325 $/pi²"); // 487 650 / 1 500256 expect(byKey.ppsf!.note).toMatch(/298 \$\/pi² \(n = 40\)/);257 expect(byKey.median!.value.replace(/\s/g, "")).toBe("455000$");258 expect(byKey.median!.note).toMatch(/63e centile des 42 prix/);259 expect(byKey.assessment!.label).toBe("Évaluation municipale (rôle 2024)");260 expect(byKey.assessment!.note).toMatch(/1,22 fois/);261 expect(byKey.history!.value.replace(/\s/g, "")).toBe("512340$→487650$");262 expect(byKey.history!.note).toMatch(/−4,8 % depuis le 12 septembre 2026/);263 expect(byKey.revenue!.note).toMatch(/15,6/);264 expect(byKey.taxes!.value.replace(/\s/g, "")).toBe("3456$");265 expect(byKey.seen!.value).toBe("1 octobre 2026");266 });267 it("n'invente aucun repère quand la donnée est absente", () => {268 const bare = toSnapshot(makeProperty({ livingAreaSqft: null, assessment: null, municipalTaxes: null, firstSeenAt: null, priceHistory: [] }));269 expect(buildFeedback(bare, null, 450_000, "q", null).insights).toEqual([]);270 });271 it("propose une question de réflexion par cours, ou seulement celle du cours du participant", () => {272 const both = buildFeedback(snapshot, ctx, 487_650, "q1", null).reflections;273 expect(both.map((r) => r.course)).toEqual(["IMM1003", "IMM1033"]);274 expect(both.every((r) => r.question.trim().endsWith("?"))).toBe(true);275 expect(buildFeedback(snapshot, ctx, 487_650, "q1", "IMM1003").reflections.map((r) => r.course)).toEqual(["IMM1003"]);276 expect(buildFeedback(snapshot, ctx, 487_650, "q1", "IMM1033").reflections.map((r) => r.course)).toEqual(["IMM1033"]);277 });278 it("est déterministe pour une même graine", () => {279 expect(buildFeedback(snapshot, ctx, 437_650, "q7", null)).toEqual(buildFeedback(snapshot, ctx, 437_650, "q7", null));280 });281});282