SPB Git

Repository Public

comps.ts 10.5 KB 312 lines typescript

1/**2 * =============================================================================3 *                  SP BOUCHER | SOFTWARE & RESEARCH4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : Vrai-Prix8 * File             : src/lib/comps.ts9 * Module           : lib10 * Repository       : https://git.spboucher.ai/vrai-prix11 * Created          : 2026-09-0812 * Last Modified    : 2026-09-0813 *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/**43 * Atelier « mon évaluation » d'une propriété à vendre : construit le bassin de44 * comparables (ventes réelles autour du sujet, + annonces actives voisines) à45 * partir duquel l'utilisateur choisit, ajuste et réconcilie SA valeur — puis la46 * compare à la mesure Vrai-Prix déjà calculée (table vp_eval).47 *48 * Chaque candidat porte les ajustements du moteur (marché, superficie, âge) et49 * son poids gaussien, en dollars, pour servir de point de départ transparent.50 */51import { getCandidates, getMarketIndex, getUnit, type UnitRow } from "./db";52import {53  adjustComps,54  ageAdjustment,55  areaAdjustment,56  estimate,57  haversineM,58  monthsBetween,59  timeFactor,60  type CompInput,61  type Subject,62} from "./engine";63import { candidatesAround, indexType, toComps } from "./estimator";64import { getListing, groupToTypeProp, listingsNear, type ListingDetail } from "./immoka";6566export interface CompCandidate {67  id: string;68  kind: "sale" | "listing";69  date: string; // vente : date de l'acte ; annonce : aujourd'hui (prix demandé courant)70  amount: number;71  lat: number;72  lng: number;73  distanceM: number;74  monthsAgo: number;75  street: string | null;76  city: string | null;77  propertyType: string | null;78  yearBuilt: number | null;79  floorArea: number | null; // m²80  landArea: number | null; // m²81  valeurRole: number | null;82  adjTime: number;83  adjArea: number;84  adjAge: number;85  adjustedPrice: number;86  weight: number;87  engineUsed: boolean; // fait partie des 12 comparables retenus par le moteur88  idProvinc?: string | null;89  uid?: string; // annonce à vendre90  image?: string | null;91}9293export interface CompsSubject {94  uid: string;95  address: string | null;96  city: string | null;97  lat: number;98  lng: number;99  typeProp: string;100  floorArea: number | null;101  yearBuilt: number | null;102  landArea: number | null;103  price: number;104  unitId: string | null;105  fromUnit: boolean; // caractéristiques lues au rôle (unité jumelée) vs à l'annonce106}107108export interface CompsPayload {109  subject: CompsSubject;110  engine: {111    estimate: number | null;112    low: number | null;113    high: number | null;114    modelEstimate: number | null;115    compsEstimate: number | null;116    modelWeight: number;117    nComps: number;118    compIds: string[];119  };120  comps: CompCandidate[];121  index: { month: string; idx: number }[];122  nowISO: string;123  params: { months: number; radiusKm: number; includeListings: boolean; limit: number };124}125126function since(months: number): string {127  const d = new Date();128  d.setMonth(d.getMonth() - months);129  return d.toISOString().slice(0, 10);130}131132const SQFT = 0.092903;133134/** Sujet du calcul : l'unité du rôle jumelée si disponible, sinon l'annonce. */135export function subjectFor(det: ListingDetail, unit: UnitRow | null): CompsSubject | null {136  const l = det.listing;137  if (unit) {138    return {139      uid: l.uid,140      address: l.address,141      city: l.city,142      lat: unit.lat,143      lng: unit.lng,144      typeProp: unit.type_prop,145      floorArea: unit.aire_etages_m2,146      yearBuilt: unit.annee_construction,147      landArea: unit.superficie_terrain_m2,148      price: l.price,149      unitId: unit.id_provinc,150      fromUnit: true,151    };152  }153  if (l.lat == null || l.lng == null) return null;154  const area = l.area_sqft && l.area_sqft > 100 && l.area_sqft < 20000 ? l.area_sqft * SQFT : null;155  return {156    uid: l.uid,157    address: l.address,158    city: l.city,159    lat: l.lat,160    lng: l.lng,161    typeProp: groupToTypeProp(det.group),162    floorArea: area,163    yearBuilt: l.year_built && l.year_built > 1600 ? l.year_built : null,164    landArea: l.lot_sqft && l.lot_sqft > 50 ? l.lot_sqft * SQFT : null,165    price: l.price,166    unitId: null,167    fromUnit: false,168  };169}170171function weightOf(distanceM: number, monthsAgo: number, subjectArea: number | null, compArea: number | null): number {172  const areaDiffPct = subjectArea && compArea ? Math.abs(compArea - subjectArea) / subjectArea : 0.15;173  return (174    Math.exp(-((distanceM / 1500) ** 2)) *175    Math.exp(-((monthsAgo / 24) ** 2)) *176    Math.exp(-((areaDiffPct / 0.25) ** 2))177  );178}179180export function buildComps(181  uid: string,182  opts: { months?: number; radiusKm?: number; includeListings?: boolean; limit?: number } = {}183): CompsPayload | null {184  const det = getListing(uid);185  if (!det) return null;186  const unit = det.eval?.unit_id ? (getUnit(det.eval.unit_id) ?? null) : null;187  const subj = subjectFor(det, unit);188  if (!subj) return null;189190  const months = Math.min(Math.max(opts.months ?? 24, 6), 60);191  const radiusKm = Math.min(Math.max(opts.radiusKm ?? 3, 0.5), 25);192  const includeListings = opts.includeListings ?? true;193  const limit = Math.min(Math.max(opts.limit ?? 60, 10), 150);194  const nowISO = new Date().toISOString().slice(0, 10);195  const index = getMarketIndex(indexType(subj.typeProp));196197  const subject: Subject = {198    lat: subj.lat,199    lng: subj.lng,200    typeProp: subj.typeProp,201    floorArea: subj.floorArea,202    yearBuilt: subj.yearBuilt,203    landArea: subj.landArea,204    modelEstimate: unit?.est_2026 ?? null,205    modelP10: unit?.p10 ?? null,206    modelP90: unit?.p90 ?? null,207  };208209  // ce que le moteur retient lui-même (mêmes règles que la fiche /estimation)210  const engineRes = estimate(subject, toComps(candidatesAround(subj.lat, subj.lng)), index, nowISO);211  const engineIds = new Set(engineRes.comps.map((c) => c.id));212213  // bassin élargi de ventes : rayon et fenêtre choisis par l'utilisateur214  const halfDeg = (radiusKm / 111) * 1.05;215  const rows = getCandidates(subj.lat, subj.lng, halfDeg, since(months), 4000);216  const sales: CompCandidate[] = [];217  for (const r of rows) {218    const distanceM = haversineM(subj.lat, subj.lng, r.lat, r.lng);219    if (distanceM > radiusKm * 1000) continue;220    const monthsAgo = monthsBetween(r.date, nowISO);221    const tf = timeFactor(r.date.slice(0, 7), index);222    const adjTime = r.amount * (tf - 1);223    const adjArea = areaAdjustment(subj.floorArea, { floorArea: r.floor_area, amount: r.amount });224    const adjAge = ageAdjustment(subj.yearBuilt, { yearBuilt: r.year_built, amount: r.amount });225    sales.push({226      id: r.id,227      kind: "sale",228      date: r.date,229      amount: r.amount,230      lat: r.lat,231      lng: r.lng,232      distanceM: Math.round(distanceM),233      monthsAgo: Math.round(monthsAgo * 10) / 10,234      street: r.street,235      city: r.city,236      propertyType: r.property_type,237      yearBuilt: r.year_built,238      floorArea: r.floor_area,239      landArea: r.land_area,240      valeurRole: r.valeur_role,241      adjTime: Math.round(adjTime),242      adjArea: Math.round(adjArea),243      adjAge: Math.round(adjAge),244      adjustedPrice: Math.round(r.amount + adjTime + adjArea + adjAge),245      weight: weightOf(distanceM, monthsAgo, subj.floorArea, r.floor_area),246      engineUsed: engineIds.has(r.id),247      idProvinc: r.id_provinc,248    });249  }250  // les comparables du moteur d'abord, puis par poids décroissant251  sales.sort((a, b) => Number(b.engineUsed) - Number(a.engineUsed) || b.weight - a.weight);252  const kept = sales.slice(0, limit);253254  const comps: CompCandidate[] = [...kept];255  if (includeListings) {256    const near = listingsNear(subj.lat, subj.lng, radiusKm, { group: det.group, excludeUid: uid, limit: 30 });257    for (const c of near) {258      if (c.lat == null || c.lng == null) continue;259      const area = c.areaSqft && c.areaSqft > 100 && c.areaSqft < 20000 ? c.areaSqft * SQFT : null;260      const adjArea = areaAdjustment(subj.floorArea, { floorArea: area, amount: c.price });261      const adjAge = ageAdjustment(subj.yearBuilt, { yearBuilt: c.yearBuilt, amount: c.price });262      comps.push({263        id: `listing:${c.uid}`,264        kind: "listing",265        date: nowISO,266        amount: c.price,267        lat: c.lat,268        lng: c.lng,269        distanceM: c.distanceM ?? Math.round(haversineM(subj.lat, subj.lng, c.lat, c.lng)),270        monthsAgo: 0,271        street: c.address,272        city: c.city,273        propertyType: c.propertyType,274        yearBuilt: c.yearBuilt,275        floorArea: area,276        landArea: c.lotSqft && c.lotSqft > 50 ? c.lotSqft * SQFT : null,277        valeurRole: null,278        adjTime: 0,279        adjArea: Math.round(adjArea),280        adjAge: Math.round(adjAge),281        adjustedPrice: Math.round(c.price + adjArea + adjAge),282        weight: weightOf(c.distanceM ?? 0, 0, subj.floorArea, area),283        engineUsed: false,284        uid: c.uid,285        image: c.image,286      });287    }288  }289290  return {291    subject: subj,292    engine: {293      estimate: Number.isFinite(engineRes.estimate) ? engineRes.estimate : null,294      low: Number.isFinite(engineRes.low) ? engineRes.low : null,295      high: Number.isFinite(engineRes.high) ? engineRes.high : null,296      modelEstimate: engineRes.modelEstimate,297      compsEstimate: engineRes.compsEstimate,298      modelWeight: engineRes.modelWeight,299      nComps: engineRes.nCompsUsed,300      compIds: [...engineIds],301    },302    comps,303    index,304    nowISO,305    params: { months, radiusKm, includeListings, limit },306  };307}308309// réexport pratique pour les routes310export type { CompInput };311export { adjustComps };312
Files main
Menu

Theme