Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : Immo-Ka iOS9// File : ImmoKa/Core/Models/Listing.swift10// Description : inscription d'une propriété à vendre (liste et fiche) —11// décodage tolérant. Les sources publient des formes12// variables : nombres en chaîne, champs nuls, prix à 0 ou 113// $, villes mal formées.14// Module : ImmoKa15// Repository : https://git.spboucher.ai/immo-ka-ios-v316// Project Website : https://www.immo-ka.com17// Created : 2026-11-2518// Last Modified : 2026-11-2819//20// =============================================================================21// AUTHOR & PROFESSIONAL AFFILIATION22// =============================================================================23//24// Author : Simon-Pierre Boucher25// Position : Professor of Finance26// Institution : Université du Québec en Outaouais (UQO)27// Department : Département des sciences administratives28// Organization : SP Boucher29//30// Website : https://spboucher.ai31// Git : https://git.spboucher.ai32//33// =============================================================================34// OFFICIAL CONTACT DIRECTORY35// =============================================================================36//37// General : info@spboucher.ai38// Professional : contact@spboucher.ai39// Direct : simon@spboucher.ai40// Research : research@spboucher.ai41// Development : dev@spboucher.ai42// Support : support@spboucher.ai43// Security/Admin : admin@spboucher.ai44// Notifications : notifications@spboucher.ai45//46// Preferred Contact: support@spboucher.ai47//48// =============================================================================49// COPYRIGHT & INTELLECTUAL PROPERTY50// =============================================================================51//52// Copyright (c) 202653// Simon-Pierre Boucher54//55// All rights reserved where applicable.56//57// This file is governed by the applicable project license,58// copyright notices, institutional agreements and relevant law.59//60// Unless expressly authorized by the applicable license or61// rights holder, copying, redistribution, sublicensing,62// publication and commercial exploitation are not permitted.63//64// Existing third-party rights and notices remain unaffected.65//66// =============================================================================67// CONFIDENTIALITY & SECURITY68// =============================================================================69//70// Classification : Public71// Distribution : Public repository; use is governed by the project license72// Security Contact : admin@spboucher.ai73//74// Access to this source does not independently grant permission75// to redistribute or disclose confidential materials.76//77// Do not embed credentials, private keys, access tokens,78// certificates or confidential personal information.79//80// =============================================================================81// LICENSE & MAINTENANCE82// =============================================================================83//84// License : None specified (no license file in this repository)85// Maintainer : Simon-Pierre Boucher86// Technical Contact: dev@spboucher.ai87//88// =============================================================================89// END OF SP BOUCHER SOURCE HEADER90// =============================================================================9192import CoreLocation93import Foundation9495/// Position du prix demandé face au prix de vente attendu (v3 : sous, dans, au-dessus de l'intervalle).96/// En lecture v2, c'est l'ancien verdict du vrai prix, aux seuils publiés par le service.97enum Verdict: String, Codable, Sendable, CaseIterable {98 case sous, marche, sur99100 /// Code compact des points de carte (« s », « m », « o »).101 init?(code: String?) {102 switch code {103 case "s", "sous": self = .sous104 case "m", "marche", "juste", "d", "dans": self = .marche105 case "o", "sur": self = .sur106 default: return nil107 }108 }109110 /// Verdict calculé à partir du prix demandé et de la valeur estimée : repli pour le seul cas où le service111 /// ne publie pas `vp_verdict` (lecture de la v1). Les seuils sont ceux que le service publie112 /// (`verdict_thresholds`) ; tant qu'ils sont inconnus, aucun verdict : on préfère se taire que tromper.113 static func from(price: Double?, estimate: Double?, thresholds: VerdictThresholds? = VerdictThresholds.current)114 -> (verdict: Verdict, deviation: Double)? {115 guard let t = thresholds, let p = price, let e = estimate, Listing.priceIsPlausible(p), e >= 10_000 else { return nil }116 let pct = (p - e) / e * 100117 guard pct >= t.ecartMinPct, pct <= t.ecartMaxPct else { return nil }118 if pct <= t.sousMaxPct { return (.sous, pct / 100) }119 if pct >= t.surMinPct { return (.sur, pct / 100) }120 return (.marche, pct / 100)121 }122123 var label: String {124 switch self {125 case .sous: "Sous l'intervalle"126 case .marche: "Dans l'intervalle"127 case .sur: "Au-dessus"128 }129 }130131 var longLabel: String {132 switch self {133 case .sous: "Sous le prix de vente attendu"134 case .marche: "Dans l'intervalle attendu"135 case .sur: "Au-dessus du prix de vente attendu"136 }137 }138}139140/// Seuils du verdict publiés par le service (`verdict_thresholds` de `/api/version` et de `/api/facets`).141/// L'app ne recode aucun seuil : elle garde les derniers seuils reçus (aussi hors ligne) et s'en sert pour142/// expliquer la règle et, en lecture v1 seulement, pour le calcul de repli.143struct VerdictThresholds: Codable, Sendable, Equatable {144 /// écart (en %) au plus égal à cette valeur : « sous la valeur estimée »145 var sousMaxPct: Double146 /// écart (en %) au moins égal à cette valeur : « au-dessus de la valeur estimée »147 var surMinPct: Double148 /// hors de cette plage, l'écart signale un mauvais appariement : aucun verdict149 var ecartMinPct: Double150 var ecartMaxPct: Double151152 enum CodingKeys: String, CodingKey {153 case sousMaxPct = "sous_max_pct", surMinPct = "sur_min_pct", ecartMinPct = "ecart_min_pct", ecartMaxPct = "ecart_max_pct"154 }155156 private static let key = "api.verdictThresholds"157 private static let lock = NSLock()158 nonisolated(unsafe) private static var cached: VerdictThresholds?159 nonisolated(unsafe) private static var loaded = false160161 /// Derniers seuils reçus du service ; nil tant qu'aucune version 2 n'a répondu sur cet appareil.162 static var current: VerdictThresholds? {163 lock.lock(); defer { lock.unlock() }164 if !loaded {165 loaded = true166 cached = UserDefaults.standard.data(forKey: key).flatMap { try? JSONDecoder().decode(VerdictThresholds.self, from: $0) }167 }168 return cached169 }170171 static func store(_ t: VerdictThresholds) {172 lock.lock(); defer { lock.unlock() }173 guard !loaded || cached != t else { return }174 loaded = true175 cached = t176 if let d = try? JSONEncoder().encode(t) { UserDefaults.standard.set(d, forKey: key) }177 }178179 /// « 8 % » : seuil sous la valeur estimée, en valeur absolue.180 var sousLabel: String { VerdictThresholds.label(sousMaxPct) }181 var surLabel: String { VerdictThresholds.label(surMinPct) }182 private static func label(_ pct: Double) -> String {183 let v = abs(pct)184 return v == v.rounded() ? "\(Int(v)) %" : String(format: "%.1f %%", v).replacingOccurrences(of: ".", with: ",")185 }186 var symmetric: Bool { abs(sousMaxPct) == abs(surMinPct) }187}188189/// Estimation « vrai prix » d'une propriété : valeur, fourchette, données du rôle d'évaluation.190struct VraiPrix: Decodable, Sendable, Hashable {191 var value: Double192 var low: Double?193 var high: Double?194 var confidence: String?195 var confidencePct: Double?196 var url: String?197 var valeurRole: Double?198 var valeurTerrain: Double?199 var valeurBatiment: Double?200 var anneeRole: Int?201 var terrainM2: Double?202 var etagesM2: Double?203204 init(value: Double, low: Double? = nil, high: Double? = nil) {205 self.value = value; self.low = low; self.high = high206 }207208 init(from decoder: Decoder) throws {209 let c = try decoder.container(keyedBy: AnyKey.self)210 // « {} » = estimation tentée sans correspondance : pas d'estimation211 guard let v = c.dbl(AnyKey("value")) ?? c.dbl(AnyKey("estimate")), v > 0 else {212 throw DecodingError.dataCorrupted(.init(codingPath: decoder.codingPath, debugDescription: "estimation absente"))213 }214 value = v215 low = c.dbl(AnyKey("low"))216 high = c.dbl(AnyKey("high"))217 confidence = c.text(AnyKey("confidence"))218 confidencePct = c.dbl(AnyKey("confidence_pct"))219 url = c.text(AnyKey("url"))220 valeurRole = c.dbl(AnyKey("valeur_role"))221 valeurTerrain = c.dbl(AnyKey("valeur_terrain"))222 valeurBatiment = c.dbl(AnyKey("valeur_batiment"))223 anneeRole = c.int(AnyKey("annee_construction_role"))224 terrainM2 = c.dbl(AnyKey("superficie_terrain_role_m2"))225 etagesM2 = c.dbl(AnyKey("aire_etages_role_m2"))226 }227}228229/// Pièce de la propriété (nom, niveau, dimensions, revêtement).230struct Room: Decodable, Sendable, Hashable, Identifiable {231 var nom: String232 var niveau: String?233 var dimensions: String?234 var revetement: String?235 let id = UUID()236237 private enum CodingKeys: CodingKey {}238239 static func == (a: Room, b: Room) -> Bool { a.nom == b.nom && a.niveau == b.niveau && a.dimensions == b.dimensions }240 func hash(into hasher: inout Hasher) { hasher.combine(nom); hasher.combine(niveau); hasher.combine(dimensions) }241242 init(from decoder: Decoder) throws {243 let c = try decoder.container(keyedBy: AnyKey.self)244 guard let n = c.text(AnyKey("nom")) ?? c.text(AnyKey("name")) else {245 throw DecodingError.dataCorrupted(.init(codingPath: decoder.codingPath, debugDescription: "pièce sans nom"))246 }247 nom = n248 niveau = c.text(AnyKey("niveau"))249 dimensions = c.text(AnyKey("dimensions"))250 revetement = c.text(AnyKey("revetement"))251 }252}253254/// Une ligne « libellé : valeur » publiée par la source.255struct DetailRow: Sendable, Hashable, Identifiable {256 var label: String257 var value: String258 var id: String { label }259}260261/// Groupes d'affichage des caractéristiques.262enum DetailGroup: String, Sendable, CaseIterable, Identifiable {263 case batiment, terrain, energie, finances, autres264 var id: String { rawValue }265 var title: String {266 switch self {267 case .batiment: "Bâtiment"268 case .terrain: "Terrain et services"269 case .energie: "Chauffage et énergie"270 case .finances: "Taxes, évaluation et frais"271 case .autres: "Autres caractéristiques"272 }273 }274275 /// Classement d'un libellé de source par mots-clés (sans accents, minuscules).276 static func of(_ label: String) -> DetailGroup {277 let k = label.folding(options: [.diacriticInsensitive, .caseInsensitive], locale: Fmt.locale).lowercased()278 func has(_ words: String...) -> Bool { words.contains { k.contains($0) } }279 if has("taxe", "evaluation", "frais", "copropriete", "cotisation", "depense", "revenu", "cout ", "cout d", "assurance") { return .finances }280 if has("chauffage", "energie", "climatis", "thermopompe", "foyer", "poele") { return .energie }281 if has("terrain", "topograph", "zonage", "egout", "eau", "proximite", "vue", "cadastre", "lot", "amenagement", "plan d'eau", "acces") { return .terrain }282 if has("construction", "annee", "revetement", "toit", "fenest", "fondation", "sous-sol", "garage", "stationnement",283 "allee", "piscine", "piece", "etage", "salle", "chambre", "cuisine", "armoire", "batiment", "immeuble",284 "superficie", "dimension", "style", "type de", "genre", "ascenseur", "balcon", "unite") { return .batiment }285 return .autres286 }287}288289/// Champs libres de la source (`details`) : lignes à afficher, pièces, et quelques métadonnées utiles.290struct ListingDetails: Decodable, Sendable, Hashable {291 var rows: [DetailRow] = []292 var rooms: [Room] = []293 var postalCode: String?294 var listedAt: String?295 var coverThumb: String?296 var photoCaptions: [String] = []297 var pricePerSqft: Double?298299 init() {}300301 init(from decoder: Decoder) throws {302 guard let c = try? decoder.container(keyedBy: AnyKey.self) else { return }303 postalCode = c.text(AnyKey("postal_code"))304 listedAt = c.text(AnyKey("listed_at"))305 coverThumb = c.text(AnyKey("cover_thumb"))306 photoCaptions = c.strings(AnyKey("photo_captions"))307 pricePerSqft = c.dbl(AnyKey("prix_pi2"))308 rooms = c.list(AnyKey("pieces"))309 // les lignes d'affichage sont celles dont le libellé est rédigé par la source (majuscule initiale) ;310 // les clés techniques (snake_case) ne sont pas montrées311 var out: [DetailRow] = []312 for key in c.allKeys {313 let k = key.stringValue314 guard let first = k.unicodeScalars.first, CharacterSet.uppercaseLetters.contains(first) || k.contains(" "),315 !k.contains("_") else { continue }316 guard let v = c.text(key), v.count <= 400 else { continue }317 out.append(DetailRow(label: k, value: v))318 }319 rows = out.sorted { $0.label.localizedStandardCompare($1.label) == .orderedAscending }320 }321322 /// Valeur d'une ligne par mots-clés du libellé (« taxes municipales » → « 6 807 $ (2026) »).323 func value(matching words: String...) -> String? {324 rows.first { r in325 let k = r.label.folding(options: [.diacriticInsensitive, .caseInsensitive], locale: Fmt.locale).lowercased()326 return words.allSatisfy { k.contains($0) }327 }?.value328 }329330 var grouped: [(group: DetailGroup, rows: [DetailRow])] {331 let by = Dictionary(grouping: rows) { DetailGroup.of($0.label) }332 return DetailGroup.allCases.compactMap { g in by[g].map { (g, $0) } }333 }334}335336struct Poi: Decodable, Sendable, Hashable, Identifiable {337 var cat: String338 var name: String339 var distM: Double340 var lat: Double?341 var lng: Double?342 var id: String { "\(cat)|\(name)|\(Int(distM))" }343344 init(from decoder: Decoder) throws {345 let c = try decoder.container(keyedBy: AnyKey.self)346 cat = c.str(AnyKey("cat")) ?? c.str(AnyKey("category")) ?? ""347 name = c.str(AnyKey("name")) ?? ""348 distM = c.dbl(AnyKey("dist_m")) ?? c.dbl(AnyKey("distance_m")) ?? 0349 lat = c.dbl(AnyKey("lat"))350 lng = c.dbl(AnyKey("lng"))351 }352}353354struct PricePoint: Decodable, Sendable, Hashable, Identifiable {355 var ts: Double356 var price: Double?357 var id: Double { ts }358 init(from decoder: Decoder) throws {359 let c = try decoder.container(keyedBy: AnyKey.self)360 ts = c.dbl(AnyKey("ts")) ?? 0361 price = c.dbl(AnyKey("price"))362 }363}364365/// Autre publication de la même propriété (« aussi publiée sur… »).366struct Duplicate: Decodable, Sendable, Hashable, Identifiable {367 var uid: String368 var source: String369 var url: String?370 var brokerName: String?371 var agency: String?372 var priceLabel: String?373 var id: String { uid }374 init(from decoder: Decoder) throws {375 let c = try decoder.container(keyedBy: AnyKey.self)376 guard let u = c.text(AnyKey("uid")) else {377 throw DecodingError.dataCorrupted(.init(codingPath: decoder.codingPath, debugDescription: "doublon sans uid"))378 }379 uid = u380 source = c.str(AnyKey("source")) ?? ""381 url = c.text(AnyKey("url"))382 brokerName = c.text(AnyKey("broker_name")) ?? c.text(AnyKey("broker"))383 agency = c.text(AnyKey("agency"))384 priceLabel = c.text(AnyKey("price_label"))385 }386}387388/// Portrait du quartier (aire de diffusion du recensement) : démographie, proximité, défavorisation, chaleur.389struct Quartier: Decodable, Sendable, Hashable {390 struct Prox: Sendable, Hashable, Identifiable {391 var key: String392 var value: Double393 var id: String { key }394 var label: String {395 switch key {396 case "prox_epicerie": "Épicerie"397 case "prox_pharmacie": "Pharmacie"398 case "prox_garderie": "Garderie"399 case "prox_ecole_prim": "École primaire"400 case "prox_ecole_sec": "École secondaire"401 case "prox_sante": "Soins de santé"402 case "prox_parc": "Parc"403 case "prox_transport": "Transport en commun"404 case "prox_emploi": "Emplois"405 case "prox_bibliotheque": "Bibliothèque"406 default: Fmt.prettySource(key.replacingOccurrences(of: "prox_", with: ""))407 }408 }409 }410411 var population: Double?412 var densite: Double?413 var ageMedian: Double?414 var revenuMedian: Double?415 var pctLocataires: Double?416 var loyerMoyen: Double?417 var pctFrancais: Double?418 var pctUniv: Double?419 var proximite: [Prox] = []420 var quintileMateriel: Int?421 var quintileSocial: Int?422 var chaleurClasse: Int?423 var chaleurEcart: Double?424 var crimeTexte: String?425426 init(from decoder: Decoder) throws {427 let c = try decoder.container(keyedBy: AnyKey.self)428 if let d = try? c.nestedContainer(keyedBy: AnyKey.self, forKey: AnyKey("demographie")) {429 population = d.dbl(AnyKey("population"))430 densite = d.dbl(AnyKey("densite"))431 ageMedian = d.dbl(AnyKey("age_median"))432 revenuMedian = d.dbl(AnyKey("revenu_median"))433 pctLocataires = d.dbl(AnyKey("pct_locataires"))434 loyerMoyen = d.dbl(AnyKey("loyer_moyen"))435 pctFrancais = d.dbl(AnyKey("pct_francais"))436 pctUniv = d.dbl(AnyKey("pct_univ"))437 }438 if let p = try? c.nestedContainer(keyedBy: AnyKey.self, forKey: AnyKey("proximite")) {439 proximite = p.allKeys.compactMap { k in p.dbl(k).map { Prox(key: k.stringValue, value: $0) } }440 .filter { $0.value >= 0 && $0.value <= 1 }441 .sorted { $0.value > $1.value }442 }443 if let f = try? c.nestedContainer(keyedBy: AnyKey.self, forKey: AnyKey("defavorisation")) {444 quintileMateriel = f.int(AnyKey("quintile_materiel"))445 quintileSocial = f.int(AnyKey("quintile_social"))446 }447 if let h = try? c.nestedContainer(keyedBy: AnyKey.self, forKey: AnyKey("chaleur")) {448 chaleurClasse = h.int(AnyKey("classe"))449 chaleurEcart = h.dbl(AnyKey("ecart"))450 }451 if let k = try? c.nestedContainer(keyedBy: AnyKey.self, forKey: AnyKey("crime")) {452 if k.str(AnyKey("type")) == "points", let n = k.int(AnyKey("douze_mois")) {453 let prev = k.int(AnyKey("douze_mois_precedents"))454 let r = k.int(AnyKey("rayon_m")) ?? 500455 crimeTexte = "\(Fmt.int(n)) événements rapportés à moins de \(r) m sur 12 mois" + (prev.map { " (\(Fmt.int($0)) l'année précédente)" } ?? "")456 } else if let i = k.dbl(AnyKey("indice")) {457 let ca = k.dbl(AnyKey("indice_canada"))458 crimeTexte = "Indice de gravité de la criminalité : \(Fmt.int(i))" + (ca.map { " (Canada : \(Fmt.int($0)))" } ?? "")459 }460 }461 }462463 var hasDemographics: Bool { population != nil || ageMedian != nil || revenuMedian != nil || pctLocataires != nil }464 var isEmpty: Bool { !hasDemographics && proximite.isEmpty && quintileMateriel == nil && chaleurClasse == nil && crimeTexte == nil }465}466467struct Listing: Decodable, Sendable, Identifiable, Hashable {468 var uid: String469 var source: String470 var url: String?471 var title: String472 var address: String473 var sector: String474 var city: String475 var region: String476 var propertyType: String477 var price: Double?478 var priceLabel: String?479 var bedrooms: Int?480 var bathrooms: Int?481 var powderRooms: Int?482 var areaSqft: Double?483 var lotSqft: Double?484 var yearBuilt: Int?485 var mls: String?486 var status: String?487 var brokerName: String?488 var brokerPhone: String?489 var agency: String?490 var description: String491 var features: [String]492 var details: ListingDetails493 var images: [String]494 var lat: Double?495 var lng: Double?496 var firstSeen: Double?497 var lastSeen: Double?498 var updatedAt: Double?499 var active: Bool500 var daysOnMarket: Int?501 var vraiprix: VraiPrix?502 /// prix de vente attendu (v3) ; quand il est présent, il remplace l'estimation de la v2 partout503 var estimate: SaleEstimate?504 /// l'inscription vient de la v3 : l'absence d'estimation ou de position veut dire « le service s'abstient »505 var isV3 = false506 /// famille canonique de la v3 (`unifamiliale`, `condo`, `plex`…)507 var family: String?508 /// attributs à trois états (v3) : clé absente = inconnu, jamais « non »509 var flags: [String: Bool] = [:]510 /// jours observés depuis la première observation par Immo-Ka ; `marketCensored` : stock initial, durée réelle plus longue511 var daysObserved: Int?512 var marketCensored = false513 var pricePrev: Double?514 var priceDelta: Double?515 var priceChangedAt: Double?516 var imageCount: Int?517 var taxTotal: Double?518 var condoFee: Double?519 var garageSpaces: Int?520 var parkingSpaces: Int?521 var statusObservedAt: Double?522 /// autres sources qui publient la même propriété (identifiants)523 var dupSources: [String] = []524 /// verdict et écart publiés par le service (v2) ; sinon calculés à partir de l'estimation525 var serverVerdict: Verdict?526 var serverDeviation: Double?527 var hasServerVerdictField = false528 // fiche seulement529 var priceHistory: [PricePoint]530 var poi: [Poi]531 var duplicates: [Duplicate]532 var quartier: Quartier?533534 var id: String { uid }535536 static func == (a: Listing, b: Listing) -> Bool { a.uid == b.uid && a.updatedAt == b.updatedAt && a.price == b.price }537 func hash(into hasher: inout Hasher) { hasher.combine(uid) }538539 /// Prix de vente plausible : écarte les 0 $, les 1 $ et les loyers publiés par erreur.540 static func priceIsPlausible(_ p: Double?) -> Bool {541 guard let p else { return false }542 return p >= 10_000 && p <= 150_000_000543 }544545 var plausiblePrice: Double? { Listing.priceIsPlausible(price) ? price : nil }546547 var coordinate: CLLocationCoordinate2D? {548 guard let lat, let lng, abs(lat) <= 90, abs(lng) <= 180, !(lat == 0 && lng == 0) else { return nil }549 return CLLocationCoordinate2D(latitude: lat, longitude: lng)550 }551552 /// Verdict du vrai prix et écart (−0,08 = 8 % sous la valeur estimée).553 var verdictInfo: (verdict: Verdict, deviation: Double)? {554 // v3 : la position vient du modèle ; nulle, le service s'abstient et l'app aussi555 if isV3 {556 guard let e = estimate, let p = e.position else { return nil }557 return (p, (e.gapPct ?? 0) / 100)558 }559 // service v3, inscription lue par une route v2 : son verdict vient de l'ancien modèle, on ne le montre pas560 if ServiceGeneration.current >= 3 { return nil }561 if let v = serverVerdict, let d = serverDeviation { return (v, d) }562 // la v2 publie toujours le champ `vp_verdict` : nul, il signifie « pas de jugement » (écart aberrant)563 if hasServerVerdictField { return nil }564 return Verdict.from(price: price, estimate: vraiprix?.value)565 }566 var verdict: Verdict? { verdictInfo?.verdict }567568 /// Estimation à afficher : le prix de vente attendu de la v3 ; en lecture v2, l'ancienne valeur estimée.569 /// Une inscription v3 sans estimation n'en a pas : les données du rôle de `vraiprix` restent, pas sa valeur.570 var expected: (value: Double, low: Double?, high: Double?)? {571 if let e = estimate { return (e.value, e.low, e.high) }572 if isV3 || ServiceGeneration.current >= 3 { return nil }573 return vraiprix.map { ($0.value, $0.low, $0.high) }574 }575 var deviation: Double? { verdictInfo?.deviation }576577 /// Titre d'affichage : l'adresse d'abord (les titres des sources répètent souvent ville et code postal).578 var displayTitle: String {579 if !address.isEmpty { return address }580 if !title.isEmpty { return title }581 return propertyType.isEmpty ? "Propriété à vendre" : "\(propertyType) à vendre"582 }583584 var cleanCity: String { Fmt.cleanCity(city) }585586 /// « Quartier · Ville »587 var place: String {588 var parts: [String] = []589 let s = Fmt.cleanCity(sector)590 if !s.isEmpty, s.caseInsensitiveCompare(cleanCity) != .orderedSame { parts.append(s) }591 if !cleanCity.isEmpty { parts.append(cleanCity) }592 return parts.isEmpty ? address : parts.joined(separator: " · ")593 }594595 /// Type de propriété normalisé (« Propriétés résidentielles » → « Maison »…), vide si la source publie autre chose.596 var kind: String { PropertyKind.normalize(propertyType) }597598 var pricePerSqft: Double? {599 guard let p = plausiblePrice, let a = areaSqft, a >= 200, a <= 60_000 else { return nil }600 let v = p / a601 return v >= 20 && v <= 5_000 ? v : nil602 }603604 /// Numéro de téléphone composable du courtier.605 var phoneURL: URL? {606 guard let p = brokerPhone else { return nil }607 let digits = p.filter(\.isNumber)608 guard digits.count >= 10 else { return nil }609 return URL(string: "tel://\(digits)")610 }611612 var isLand: Bool { kind == "Terrain" }613614 /// Statut donné par la source quand il dit autre chose que « à vendre ».615 var statusLabel: String? {616 switch status {617 case "offre-acceptee": "Offre acceptée"618 case "vendu-conditionnel": "Vendu sous conditions"619 case "vendu": "Vendu"620 case "retire": "Retirée"621 case "loue": "Louée"622 default: nil623 }624 }625626 /// Baisse de prix observée (montant négatif) depuis la dernière modification.627 var priceDrop: Double? {628 guard let d = priceDelta, d < 0, let prev = pricePrev, prev > 0 else { return nil }629 return d630 }631632 /// Complète une fiche de la v2 (quartier, points d'intérêt, courtier) par ce que seule la v3 sait :633 /// prix de vente attendu, statut, durée observée, attributs à trois états. La v3 fait foi pour l'estimation.634 func merging(v3 o: Listing) -> Listing {635 var l = self636 l.isV3 = true637 l.estimate = o.estimate638 l.family = o.family639 l.flags = o.flags640 l.status = o.status ?? l.status641 l.statusObservedAt = o.statusObservedAt642 l.daysObserved = o.daysObserved643 l.marketCensored = o.marketCensored644 l.pricePrev = o.pricePrev; l.priceDelta = o.priceDelta; l.priceChangedAt = o.priceChangedAt645 l.taxTotal = o.taxTotal; l.condoFee = o.condoFee646 l.garageSpaces = o.garageSpaces; l.parkingSpaces = o.parkingSpaces647 l.dupSources = o.dupSources648 l.imageCount = o.imageCount649 if l.images.isEmpty { l.images = o.images }650 if l.description.isEmpty { l.description = o.description }651 if l.priceHistory.isEmpty { l.priceHistory = o.priceHistory }652 if l.price == nil { l.price = o.price }653 if l.propertyType.isEmpty { l.propertyType = o.propertyType }654 if l.agency == nil { l.agency = o.agency }655 if l.brokerName == nil { l.brokerName = o.brokerName }656 return l657 }658659 init(from decoder: Decoder) throws {660 let c = try decoder.container(keyedBy: AnyKey.self)661 guard let u = c.text(AnyKey("uid")) else {662 throw DecodingError.dataCorrupted(.init(codingPath: decoder.codingPath, debugDescription: "inscription sans uid"))663 }664 uid = u665 source = c.str(AnyKey("source")) ?? ""666 url = c.text(AnyKey("url"))667 title = c.text(AnyKey("title")) ?? ""668 address = c.text(AnyKey("address")) ?? ""669 sector = c.text(AnyKey("sector")) ?? ""670 city = c.text(AnyKey("city")) ?? ""671 // la v2 publie le nom de la région administrative à côté de son code (« 05 » → « Estrie »)672 region = c.text(AnyKey("region_name")) ?? c.text(AnyKey("region")) ?? ""673 propertyType = c.text(AnyKey("property_type")) ?? c.text(AnyKey("ptype")) ?? ""674 price = c.dbl(AnyKey("price"))675 priceLabel = c.text(AnyKey("price_label"))676 // bornes d'affichage : un numéro civique est parfois lu comme un nombre de chambres677 bedrooms = c.int(AnyKey("bedrooms")).flatMap { (0...20).contains($0) ? $0 : nil }678 bathrooms = c.int(AnyKey("bathrooms")).flatMap { (0...20).contains($0) ? $0 : nil }679 powderRooms = c.int(AnyKey("powder_rooms")).flatMap { (0...20).contains($0) ? $0 : nil }680 areaSqft = c.dbl(AnyKey("area_sqft")).flatMap { $0 >= 100 && $0 <= 25_000 ? $0 : nil }681 lotSqft = c.dbl(AnyKey("lot_sqft")).flatMap { $0 > 0 ? $0 : nil }682 yearBuilt = c.int(AnyKey("year_built")).flatMap { (1600...2100).contains($0) ? $0 : nil }683 mls = c.text(AnyKey("mls"))684 status = c.text(AnyKey("status"))685 brokerName = c.text(AnyKey("broker_name")) ?? c.text(AnyKey("broker"))686 brokerPhone = c.text(AnyKey("broker_phone"))687 agency = c.text(AnyKey("agency"))688 description = c.text(AnyKey("description")) ?? ""689 features = c.strings(AnyKey("features"))690 if features.isEmpty { features = c.strings(AnyKey("features_text")) }691 flags = c.flags(AnyKey("features"))692 details = c.objectOrEncoded(AnyKey("details")) ?? ListingDetails()693 images = c.strings(AnyKey("images")).filter { $0.hasPrefix("http") }694 // liste allégée (points de carte, v1) : une seule image695 if images.isEmpty, let one = c.text(AnyKey("image")), one.hasPrefix("http") { images = [one] }696 lat = c.dbl(AnyKey("lat"))697 lng = c.dbl(AnyKey("lng"))698 firstSeen = c.dbl(AnyKey("first_seen"))699 lastSeen = c.dbl(AnyKey("last_seen"))700 updatedAt = c.dbl(AnyKey("updated_at"))701 active = c.bool(AnyKey("active")) ?? true702 daysOnMarket = c.int(AnyKey("days_on_market"))703 vraiprix = c.objectOrEncoded(AnyKey("vraiprix"))704 // estimation aplatie (points de carte v1 : « vp » ; liste v2 : « vp_value »)705 if vraiprix == nil, let v = c.dbl(AnyKey("vp")) ?? c.dbl(AnyKey("vp_value")), v > 0 {706 vraiprix = VraiPrix(value: v, low: c.dbl(AnyKey("vp_low")), high: c.dbl(AnyKey("vp_high")))707 }708 serverVerdict = Verdict(code: c.text(AnyKey("vp_verdict")))709 hasServerVerdictField = c.contains(AnyKey("vp_verdict"))710 // la v2 publie l'écart en pourcentage (−9,6) ; l'app le garde en fraction (−0,096)711 serverDeviation = c.dbl(AnyKey("vp_deviation")).map { $0 / 100 }712 // --- v3 : prix de vente attendu, durée observée, statut daté ---713 family = c.text(AnyKey("family"))714 isV3 = c.contains(AnyKey("estimate")) || c.contains(AnyKey("ptype")) || c.contains(AnyKey("market"))715 estimate = c.opt(AnyKey("estimate"))716 if let m = try? c.nestedContainer(keyedBy: AnyKey.self, forKey: AnyKey("market")) {717 daysObserved = m.int(AnyKey("days_observed"))718 marketCensored = m.bool(AnyKey("censored")) ?? false719 if daysOnMarket == nil { daysOnMarket = daysObserved }720 }721 pricePrev = c.dbl(AnyKey("price_prev"))722 priceDelta = c.dbl(AnyKey("price_delta"))723 priceChangedAt = c.dbl(AnyKey("price_changed_at"))724 imageCount = c.int(AnyKey("n_images"))725 taxTotal = c.dbl(AnyKey("tax_total"))726 condoFee = c.dbl(AnyKey("condo_fee"))727 garageSpaces = c.int(AnyKey("garage_spaces"))728 parkingSpaces = c.int(AnyKey("parking_spaces"))729 statusObservedAt = c.dbl(AnyKey("status_observed_at"))730 dupSources = c.strings(AnyKey("dup_sources"))731 priceHistory = c.list(AnyKey("price_history"))732 poi = c.list(AnyKey("poi"))733 duplicates = c.list(AnyKey("duplicates"))734 quartier = c.opt(AnyKey("quartier"))735 if quartier?.isEmpty == true { quartier = nil }736 }737}738739/// Types de propriété : les sources en publient plus de mille libellés ; l'app n'en propose qu'une liste nette.740enum PropertyKind {741 /// Types proposés dans les filtres, dans l'ordre d'importance.742 static let all = ["Maison", "Condo", "Duplex", "Triplex", "Multiplex", "Maison de ville", "Jumelé", "Chalet",743 "Terrain", "Fermette/Agricole", "Maison mobile", "Commercial"]744745 /// Valeurs exactes à envoyer au filtre `property_type` de la v2 (plusieurs valeurs séparées par des746 /// virgules) : certains courtiers publient « Propriétés résidentielles », « Détachée », « Lot »…747 static func queryValue(_ kind: String) -> String {748 switch kind {749 case "Maison": "Maison,Détachée,Propriétés résidentielles,Résidentiel"750 case "Terrain": "Terrain,Lot"751 case "Chalet": "Chalet,Propriété récréative"752 case "Multiplex": "Multiplex,Sixplex,7 plex"753 case "Maison de ville": "Maison de ville,Attachée"754 default: kind755 }756 }757758 static func icon(_ kind: String) -> String {759 switch kind {760 case "Condo": "building"761 case "Duplex", "Triplex", "Multiplex": "building.2"762 case "Terrain": "square.dashed"763 case "Commercial": "storefront"764 case "Chalet": "tree"765 case "Fermette/Agricole": "leaf"766 default: "house"767 }768 }769770 static func normalize(_ raw: String) -> String {771 let t = raw.trimmingCharacters(in: .whitespacesAndNewlines)772 if all.contains(t) { return t }773 let k = t.folding(options: [.diacriticInsensitive, .caseInsensitive], locale: Fmt.locale).lowercased()774 if k.isEmpty { return "" }775 if k.contains("condo") || k.contains("copropriete") || k.contains("appartement") || k.contains("loft") { return "Condo" }776 if k.contains("duplex") { return "Duplex" }777 if k.contains("triplex") { return "Triplex" }778 if k.contains("plex") || k.contains("revenus") || k.contains("immeuble a logements") { return "Multiplex" }779 if k.contains("terrain") || k == "lot" || k.contains("terre") { return "Terrain" }780 if k.contains("chalet") || k.contains("recreati") { return "Chalet" }781 if k.contains("maison de ville") || k.contains("townhouse") || k.contains("en rangee") { return "Maison de ville" }782 if k.contains("jumele") || k.contains("semi-detach") { return "Jumelé" }783 if k.contains("mobile") { return "Maison mobile" }784 if k.contains("ferme") || k.contains("agricole") { return "Fermette/Agricole" }785 if k.contains("commerc") || k.contains("industri") || k.contains("bureau") { return "Commercial" }786 if k.contains("maison") || k.contains("residenti") || k.contains("detache") || k.contains("bungalow")787 || k.contains("plain-pied") || k.contains("cottage") || k.contains("unifamili") || k == "propriete" { return "Maison" }788 return ""789 }790}791