Repository Public
1// Fiche de propriété : types, appels d'API et lecture tolérante des données.2// Écrit contre l'API v1 d'Immo-Ka (lecture seule) ; la v2 garde ces routes.3// Les données sont sales (prix à 0 ou 1 $, champs nuls, libellés variables4// d'une source à l'autre) : tout est décodé avec tolérance, rien n'est inventé.56import { thumb as sharedThumb } from "@/lib/api";7import { cleanCity, slugify } from "@/lib/format";89// --- Types ----------------------------------------------------------------------10export interface Room {11 nom?: string;12 niveau?: string;13 dimensions?: string;14 revetement?: string;15}1617/** `details` : dictionnaire libre (libellé de la source → valeur), plus quelques18 * clés techniques (`pieces`, `transaction`, `photo_captions`…). */19export interface PropertyDetails {20 pieces?: Room[];21 transaction?: string;22 price_from?: boolean;23 photo_captions?: string[];24 listing_origin_url?: string;25 listed_at?: string;26 [key: string]: unknown;27}2829/** Estimation de la valeur marchande (« vrai prix ») et rôle d'évaluation apparié. */30export interface VraiPrix {31 id: string;32 value: number | null;33 low: number | null;34 high: number | null;35 confidence_pct: number | null;36 /** A | B | C | D, rarement renseignée */37 confidence: string | null;38 url: string;39 valeur_role?: number | null;40 valeur_terrain?: number | null;41 valeur_batiment?: number | null;42 annee_construction_role?: number | null;43 superficie_terrain_role_m2?: number | null;44 aire_etages_role_m2?: number | null;45}4647export interface Poi {48 cat: string;49 name: string;50 dist_m: number;51 lat?: number;52 lng?: number;53}5455export interface Quartier {56 dauid?: string | null;57 demographie?: {58 population: number | null;59 densite: number | null;60 age_median: number | null;61 revenu_median: number | null;62 pct_locataires: number | null;63 loyer_moyen: number | null;64 pct_francais: number | null;65 pct_univ: number | null;66 };67 proximite?: Record<string, number>;68 defavorisation?: { quintile_materiel: number | null; quintile_social: number | null };69 chaleur?: { classe: number; ecart: number | null };70 crime?:71 | { type: "points"; rayon_m: number; douze_mois: number; douze_mois_precedents: number; categories?: { nom: string; n: number; n_prec: number }[] }72 | { type: "igc"; ville: string; annee: number; indice: number; indice_canada: number | null };73}7475export interface Duplicate {76 uid: string;77 source: string;78 url: string;79 broker_name: string;80 agency: string;81 price_label: string;82}8384export interface Property {85 uid: string;86 source: string;87 external_id: string;88 url: string;89 title: string | null;90 address: string | null;91 sector: string | null;92 city: string | null;93 region: string | null;94 property_type: string | null;95 price: number | null;96 price_label: string | null;97 bedrooms: number | null;98 bathrooms: number | null;99 powder_rooms: number | null;100 area_sqft: number | null;101 lot_sqft: number | null;102 year_built: number | null;103 mls: string | null;104 status: string | null;105 broker_name: string | null;106 broker_phone: string | null;107 agency?: string | null;108 description: string | null;109 features: string[] | null;110 details: PropertyDetails | null;111 images: string[] | null;112 lat: number | null;113 lng: number | null;114 first_seen?: number | null;115 last_seen?: number | null;116 updated_at?: number | null;117 active?: number | null;118 days_on_market?: number | null;119 vraiprix?: VraiPrix | null;120 // fiche seulement121 price_history?: { ts: number; price: number | null }[];122 duplicates?: Duplicate[];123 poi?: Poi[];124 quartier?: Quartier | null;125}126127// --- Client -------------------------------------------------------------------128async function get<T>(path: string): Promise<T> {129 const ctrl = new AbortController();130 const timer = window.setTimeout(() => ctrl.abort(), 25000);131 try {132 const res = await fetch(path, { signal: ctrl.signal });133 if (!res.ok) throw new Error(`API ${res.status} ${path}`);134 return (await res.json()) as T;135 } finally {136 window.clearTimeout(timer);137 }138}139140export const isNotFound = (e: unknown) => /API 404/.test(String(e));141142export const fetchProperty = (uid: string) => get<Property>(`/api/listings/${encodeURIComponent(uid)}`);143144/** Fiche PDF produite par le serveur. */145export const pdfUrl = (uid: string) => `/api/listings/${encodeURIComponent(uid)}/pdf`;146147/** Miniature servie par l'API (`/api/img`). L'API v1 d'Immo-Ka n'a pas cette148 * route : les composants retombent alors d'eux-mêmes sur l'image d'origine. */149export const thumb = sharedThumb;150151interface ListResponse {152 total: number;153 count: number;154 listings: Property[];155}156157const distKm = (a: { lat: number; lng: number }, b: { lat: number; lng: number }) => {158 const r = Math.PI / 180;159 const x = (b.lng - a.lng) * r * Math.cos(((a.lat + b.lat) / 2) * r);160 const y = (b.lat - a.lat) * r;161 return Math.sqrt(x * x + y * y) * 6371;162};163164/**165 * Propriétés comparables : même ville et même type, prix voisin (± 30 %),166 * classées par proximité quand les coordonnées sont connues. Si le marché167 * local est trop mince, on élargit au même type sans borne de prix.168 */169export async function fetchComparables(p: Property, max = 8): Promise<Property[]> {170 if (!p.city) return [];171 const base = new URLSearchParams({ city: p.city, limit: "60", sort: "recent" });172 if (p.property_type) base.set("property_type", p.property_type);173 const tight = new URLSearchParams(base);174 if (priceUsable(p)) {175 tight.set("price_min", String(Math.round(p.price! * 0.7)));176 tight.set("price_max", String(Math.round(p.price! * 1.3)));177 }178 let rows = (await get<ListResponse>(`/api/listings?${tight}`)).listings;179 if (rows.filter((x) => x.uid !== p.uid).length < 3 && tight.toString() !== base.toString()) {180 rows = (await get<ListResponse>(`/api/listings?${base}`)).listings;181 }182 const here = p.lat != null && p.lng != null ? { lat: p.lat, lng: p.lng } : null;183 const seen = new Set<string>();184 return rows185 .filter((x) => x.uid !== p.uid && priceUsable(x))186 .filter((x) => {187 // une même propriété publiée deux fois ne compte qu'une fois188 const k = `${(x.address || x.title || x.uid).toLowerCase()}|${x.price}`;189 if (seen.has(k)) return false;190 seen.add(k);191 return true;192 })193 .map((x) => ({ x, d: here && x.lat != null && x.lng != null ? distKm(here, { lat: x.lat, lng: x.lng }) : 9999 }))194 .sort((a, b) => a.d - b.d || (b.x.images?.length ? 1 : 0) - (a.x.images?.length ? 1 : 0))195 .slice(0, max)196 .map(({ x }) => x);197}198199/**200 * Adaptateur vers la carte partagée `ListingCard`. Le socle Immo-Ka typera sa201 * carte sur ses propres inscriptions : cette fonction deviendra l'identité.202 */203export function toCardListing(p: Property) {204 const cmp = priceComparison(p);205 return {206 ...p,207 title: p.address || p.title || "",208 address: p.address || "",209 city: p.city || "",210 sector: p.sector || "",211 images: p.images ?? [],212 unit_type: p.property_type || "",213 fv_verdict: cmp?.verdict ?? null,214 fv_deviation: cmp ? cmp.deviation : null,215 };216}217218// --- Noms des sources -----------------------------------------------------------219interface SourceRow {220 id: string;221 name: string;222}223/** Identifiant de source → nom lisible (`/api/sources/names` en v2, `/api/sources` en v1). */224export async function fetchSourceNames(): Promise<Record<string, string>> {225 try {226 return await get<Record<string, string>>("/api/sources/names");227 } catch {228 const d = await get<{ sources: SourceRow[] }>("/api/sources");229 return Object.fromEntries(d.sources.map((s) => [s.id, s.name]));230 }231}232export function sourceLabel(id: string, names: Record<string, string> | undefined): string {233 if (names?.[id]) return names[id]!;234 return id235 .replace(/_ag_/g, " ")236 .replace(/_/g, " ")237 .replace(/\b\w/g, (c) => c.toUpperCase());238}239240// --- Liens internes (à raccorder par le socle) ------------------------------------241/** Page d'annuaire d'une agence. L'identifiant est provisoirement le nom mis en slug. */242export const agencyPath = (agency: string) => `/agence/${slugify(agency)}`;243/** Page d'une bannière de courtage ; `id` vient de `/api/bannieres`. */244export const bannerPath = (id: string) => `/banniere/${encodeURIComponent(id)}`;245/** Page des taux hypothécaires. */246export const ratesPath = () => "/taux-hypothecaires";247/** Recherche (carte) restreinte à une ville. */248export const searchPath = (city?: string | null) => (city ? `/recherche?city=${encodeURIComponent(city)}` : "/recherche");249export const contactPath = (uid: string) => `/contact?sujet=${encodeURIComponent(`Erreur sur la fiche ${uid}`)}`;250251export interface Banniere {252 id: string;253 name: string;254 covered_by?: string | null;255 brokers_n?: number;256}257export const fetchBannieres = () => get<{ bannieres: Banniere[] }>("/api/bannieres");258259const bare = (s: string) =>260 s261 .toLowerCase()262 .normalize("NFD")263 .replace(/[̀-ͯ]/g, "")264 .replace(/\b(inc|ltee|enr|agence immobiliere|immobilier|courtier)\b\.?/g, "")265 .replace(/[^a-z0-9]+/g, " ")266 .trim();267268/** Bannière de l'annuaire qui correspond à l'inscription (par source couverte, sinon par nom d'agence). */269export function matchBanniere(p: Property, list: Banniere[] | undefined): Banniere | null {270 if (!list?.length) return null;271 const ag = p.agency ? bare(p.agency) : "";272 return (ag && list.find((b) => bare(b.name) === ag)) || list.find((b) => b.covered_by === p.source) || null;273}274275// --- Lecture tolérante ------------------------------------------------------------276/** « 2 872 $ (2026) », « $ 2950 / année », « 19989,50 » → nombre ; null si illisible. */277export function parseAmount(v: unknown): number | null {278 if (v == null) return null;279 if (typeof v === "number") return Number.isFinite(v) && v > 0 ? v : null;280 const s = String(v)281 .replace(/\(.*?\)/g, "")282 .replace(/[^\d.,]/g, "");283 if (!s) return null;284 const n = parseFloat(s.replace(/,(\d{1,2})$/, ".$1").replace(/,/g, ""));285 return Number.isFinite(n) && n > 0 ? n : null;286}287288const yearIn = (v: unknown): string | null => String(v ?? "").match(/\b(20\d{2})\b/)?.[1] ?? null;289290/** Première valeur non vide parmi des libellés ; `prefix` accepte « Taxes municipales (2026) ». */291function pick(p: Property, keys: string[], prefix = false): { key: string; value: unknown } | null {292 const d = p.details ?? {};293 for (const k of keys) {294 const v = d[k];295 if (v != null && String(v).trim()) return { key: k, value: v };296 }297 if (prefix) {298 for (const [k, v] of Object.entries(d)) {299 if (v != null && String(v).trim() && keys.some((x) => k.toLowerCase().startsWith(x.toLowerCase()))) return { key: k, value: v };300 }301 }302 return null;303}304305export const isRental = (p: Property) => p.details?.transaction === "location";306307/** Prix exploitable : écarte les 0 $, 1 $ et les coquilles manifestes. */308export const priceUsable = (p: Pick<Property, "price">): boolean => p.price != null && p.price >= 1000 && p.price < 500_000_000;309310/** Inscription à vendre dont le prix permet un calcul de financement. */311export const financeable = (p: Property) => priceUsable(p) && !isRental(p) && p.price! >= 25_000;312313export function titleOf(p: Property): string {314 return (p.address || p.title || p.property_type || "Propriété à vendre").trim();315}316317/** « Gatineau (Gatineau) » → « Gatineau » ; « Rosemont (Montréal) » reste tel quel. */318export function cityLabel(city: string | null | undefined): string {319 const c = (city || "").replace(/^\*+/, "").trim();320 const m = c.match(/^(.*?)\s*\((.*?)\)\s*$/);321 if (!m) return cleanCity(c);322 const [, a, b] = m as unknown as [string, string, string];323 return !a.trim() ? b.trim() : !b.trim() || a.trim().toLowerCase() === b.trim().toLowerCase() ? a.trim() : `${a.trim()} (${b.trim()})`;324}325326export function placeOf(p: Property): string {327 const city = cityLabel(p.city);328 const sector = (p.sector || "").replace(/[()]/g, "").replace(/^\d+\s*-\s*/, "").trim();329 return [sector && !city.toLowerCase().includes(sector.toLowerCase()) ? sector : null, city, p.region && p.region !== city ? p.region : null].filter(Boolean).join(", ");330}331332/** Type lisible : écarte les libellés qui ne décrivent pas un immeuble (sources de petites annonces). */333export function typeOf(p: Property): string | null {334 const t = (p.property_type || "").trim();335 if (!t || t.length > 28 || /\b(19|20)\d{2}\b/.test(t)) return null;336 return t;337}338339export interface Taxes {340 municipales: number | null;341 scolaires: number | null;342 total: number;343 annee: string | null;344}345/** Taxes annuelles publiées par la source ; null si absentes ou invraisemblables. */346export function taxesOf(p: Property): Taxes | null {347 const m = pick(p, ["Taxes municipales", "Taxe municipale"], true);348 const s = pick(p, ["Taxes scolaires", "Taxe scolaire"], true);349 let municipales = parseAmount(m?.value);350 let scolaires = parseAmount(s?.value);351 let annee = yearIn(m?.value) ?? yearIn(m?.key) ?? yearIn(s?.value) ?? yearIn(s?.key);352 let total = (municipales ?? 0) + (scolaires ?? 0);353 if (total <= 0) {354 // certaines sources regroupent : « Taxes municipales (2026): 16 040 $ ; Taxes scolaires (2026): 658 $ »355 const grouped = String(p.details?.["Taxes"] ?? "");356 const mm = grouped.match(/municipales?[^:]*:\s*([\d\s.,]+)\s*\$/i);357 const ss = grouped.match(/scolaires?[^:]*:\s*([\d\s.,]+)\s*\$/i);358 municipales = parseAmount(mm?.[1]);359 scolaires = parseAmount(ss?.[1]);360 annee = yearIn(grouped);361 total = (municipales ?? 0) + (scolaires ?? 0);362 }363 if (total <= 0) {364 const t = parseAmount(pick(p, ["Taxes annuelles totales", "Taxes annuelles"])?.value);365 if (t != null) total = t;366 }367 if (total <= 0 || total > 500_000) return null;368 return { municipales, scolaires, total, annee };369}370371/** Frais de copropriété mensuels publiés ; un « 1,00 $ » de remplissage est ignoré. */372export function condoFeesOf(p: Property): number | null {373 const f = pick(p, ["Frais de copropriété", "Frais de condo", "Frais communs"], true);374 const n = parseAmount(f?.value);375 if (n == null || n < 20) return null;376 const monthly = /\ban\b|année|annuel/i.test(`${f!.key} ${String(f!.value)}`) ? n / 12 : n;377 return monthly > 5000 ? null : Math.round(monthly);378}379380/** Coût d'énergie annuel publié par la source (Centris), en dollars. */381export function energyCostOf(p: Property): number | null {382 const n = parseAmount(pick(p, ["Coût d'énergie"], true)?.value);383 return n != null && n >= 100 && n < 30_000 ? n : null;384}385386export interface MunicipalValue {387 total: number;388 terrain: number | null;389 batiment: number | null;390 annee: string | null;391 /** publiée par la source, ou appariée au rôle par le service d'estimation */392 origine: "source" | "role";393}394/** Évaluation municipale : publiée par la source, sinon rôle d'évaluation apparié. */395export function municipalValueOf(p: Property): MunicipalValue | null {396 const vp = p.vraiprix;397 const t = pick(p, ["Évaluation municipale (total)", "Évaluation municipale (totale)", "Évaluation municipale totale", "Évaluation totale", "Évaluation municipale"]);398 let total = parseAmount(t?.value);399 const pubTerrain = parseAmount(pick(p, ["Évaluation municipale (terrain)", "Évaluation du terrain"])?.value);400 const pubBatiment = parseAmount(pick(p, ["Évaluation municipale (bâtiment)", "Évaluation municipale (bâtisse)", "Évaluation du bâtiment"])?.value);401 const origine: MunicipalValue["origine"] = total != null || (pubTerrain != null && pubBatiment != null) ? "source" : "role";402 const terrain = pubTerrain ?? vp?.valeur_terrain ?? null;403 const batiment = pubBatiment ?? vp?.valeur_batiment ?? null;404 if (total == null && terrain != null && batiment != null) total = terrain + batiment;405 if (total == null && vp?.valeur_role) total = vp.valeur_role;406 if (total == null || total < 1000) return null;407 const annee = yearIn(pick(p, ["Évaluation municipale (année)", "Année d'évaluation", "Évaluation"])?.value);408 return { total, terrain, batiment, annee, origine };409}410411export type PriceVerdict = "sous" | "marche" | "sur";412export interface PriceComparison {413 verdict: PriceVerdict;414 /** écart signé (−0,08 = 8 % sous l'estimation) */415 deviation: number;416 value: number;417 low: number | null;418 high: number | null;419 /** demi-largeur relative de la fourchette (0,12 = ± 12 %) */420 spread: number | null;421 confidence: string | null;422 confidencePct: number | null;423 url: string | null;424}425/** Seuils du verdict : règle unique du backend v2 (`@/lib/verdict`). */426import { deviationOf, estimateCoherent, verdictOfDeviation, VERDICT_BAND as BAND, DEVIATION_MAX } from "./verdict";427export const VERDICT_BAND = BAND;428export const COMPARABLE_LIMIT = DEVIATION_MAX;429430export function priceComparison(p: Property): PriceComparison | null {431 const vp = p.vraiprix;432 if (!priceUsable(p) || isRental(p) || !vp || vp.value == null || vp.value <= 0) return null;433 const deviation = deviationOf(p.price, vp.value);434 if (deviation == null || !estimateCoherent(vp.value, vp.low, vp.high)) return null;435 const hasRange = vp.low != null && vp.high != null && vp.high > vp.low;436 return {437 verdict: verdictOfDeviation(deviation),438 deviation,439 value: vp.value,440 low: hasRange ? vp.low : null,441 high: hasRange ? vp.high : null,442 spread: hasRange ? (vp.high! - vp.low!) / 2 / vp.value : null,443 confidence: vp.confidence || null,444 confidencePct: vp.confidence_pct ?? null,445 url: vp.url || null,446 };447}448449/** Jours observés sur le marché (depuis la première synchronisation). */450export function daysOnline(p: Property): number | null {451 if (p.days_on_market != null) return p.days_on_market;452 return p.first_seen ? Math.max(0, Math.round((Date.now() / 1000 - p.first_seen) / 86400)) : null;453}454455/** Numéro de téléphone → lien `tel:` ; null si le numéro est inexploitable. */456export function telHref(phone: string | null | undefined): string | null {457 const digits = (phone || "").replace(/[^\d+]/g, "");458 return digits.replace(/\D/g, "").length >= 10 ? `tel:${digits}` : null;459}460export function fmtPhone(phone: string): string {461 const d = phone.replace(/\D/g, "").replace(/^1(?=\d{10}$)/, "");462 return d.length === 10 ? `${d.slice(0, 3)} ${d.slice(3, 6)}-${d.slice(6)}` : phone.trim();463}464465// --- Emplacement, risques, énergie --------------------------------------------------466export interface CommerceItem {467 id: string;468 commerce: string;469 nom: string;470 adresse: string;471 dist_m: number;472 lat: number;473 lng: number;474}475export interface CommercesNearby {476 n: number;477 commerces: CommerceItem[];478 transit?: CommerceItem[];479}480export const fetchCommerces = (lat: number, lng: number) => get<CommercesNearby>(`/api/commerces?lat=${lat}&lng=${lng}`);481482export interface GazStation {483 nom: string;484 adresse: string;485 dist_m: number;486 lat?: number;487 lng?: number;488 regulier: number | null;489 super: number | null;490 diesel: number | null;491 moins_chere: boolean;492}493export interface GazNearby {494 n: number;495 rayon_m: number;496 mediane_regulier: number | null;497 min_regulier: number | null;498 stations: GazStation[];499 maj: string | null;500}501export const fetchGaz = (lat: number, lng: number, limit = 60) => get<GazNearby>(`/api/gaz?lat=${lat}&lng=${lng}&limit=${limit}`);502503export interface InondationZone {504 type: string;505 severite: "eleve" | "modere" | "present";506 recurrence: string;507 distance_m: number;508 date_rapport: string | null;509}510export interface Inondation {511 statut: "en_zone" | "a_proximite" | "hors_zone" | "non_cartographie";512 severite: "eleve" | "modere" | "present" | null;513 couvert: boolean;514 zones: InondationZone[];515}516export const fetchInondation = (lat: number, lng: number) => get<Inondation>(`/api/inondation?lat=${lat}&lng=${lng}`);517518export interface AirMesure {519 moyenne: number;520 annee: number;521 n: number;522 unite: string;523 ref: number | null;524 ref_nom: string | null;525}526export interface AirNearby {527 station: string | null;528 ville?: string;529 distance_km?: number;530 mesures: Record<string, AirMesure>;531}532export const fetchAir = (lat: number, lng: number) => get<AirNearby>(`/api/air?lat=${lat}&lng=${lng}`);533534export interface HydroEstimate {535 disponible: boolean;536 raison?: string;537 adresse?: string;538 cout_annuel?: number;539 cout_mensuel?: number;540 kwh_annuel?: number;541 cache?: boolean;542 en_attente?: boolean;543}544/** Coût d'électricité estimé à l'adresse (outil public d'Hydro-Québec). `solve` force le calcul. */545export function fetchHydro(p: Property, solve = false) {546 const q = new URLSearchParams({ adresse: p.address || p.title || "", uid: p.uid });547 if (p.lat != null) q.set("lat", String(p.lat));548 if (p.lng != null) q.set("lng", String(p.lng));549 if (solve) q.set("solve", "1");550 return get<HydroEstimate>(`/api/hydro?${q}`);551}552553// --- Taux hypothécaires (module hypothécaire d'Immo-Ka) --------------------------------554export interface MortgageRate {555 provider: string;556 institution: string;557 product_name: string | null;558 rate_type: "fixed" | "variable" | "adjustable" | "other";559 term_months: number;560 kind: "posted" | "special";561 rate: number;562 apr: number | null;563 insured_status: "insured" | "insurable" | "uninsured" | "unknown";564 source_url: string | null;565 last_checked: number;566 age_minutes: number;567 stale: boolean;568}569export interface MortgageBest extends MortgageRate {570 median_rate: number | null;571 institutions_count: number;572 per_institution: MortgageRate[];573}574/** Meilleur taux observé pour un type et un terme, avec le taux de chaque institution. */575export const fetchBestRate = (rateType: "fixed" | "variable", termMonths: number) =>576 get<MortgageBest>(`/api/mortgage/rates/best?rate_type=${rateType}&term_months=${termMonths}`);577