Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : Vrai-Prix iOS9// File : VraiPrix/Core/V3/V3Models.swift10// Description : modèles de l'API v3 : valeur à quatre régimes, position11// d'un prix, fiche de propriété, ventes qualifiées,12// inscriptions rattachées, comparables, recherche. Lecture13// tolérante (JSONValue).14// Module : VraiPrix15// Repository : https://git.spboucher.ai/vrai-prix-ios-v316// Project Website : https://www.vrai-prix.com17// Created : 2026-11-2818// 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// MARK: - Valeur9697/// Régime d'une valeur. L'écran ne montre jamais un montant hors de `valeur` et `ordre`.98enum ValueStatus: String, Sendable, Hashable, Codable {99 /// valeur ferme : montant, intervalle, position d'un prix100 case valeur101 /// ordre de grandeur : montant approché et intervalle, aucune position de prix102 case ordre103 /// le modèle s'abstient : aucun montant104 case abstention105 /// hors du champ du modèle : aucun montant106 case horsChamp = "hors_champ"107108 var hasAmount: Bool { self == .valeur || self == .ordre }109}110111struct Motif: JSONModel, Hashable, Codable {112 var code: String113 var libelle: String114115 init(code: String, libelle: String) { self.code = code; self.libelle = libelle }116 init(json j: JSONValue) {117 code = j["code"].text ?? ""118 libelle = j["libelle"].text ?? ""119 }120121 /// Titre de la famille d'une absence de valeur (le seul texte que l'app possède ; le libellé vient du moteur).122 var familyTitle: String? {123 if code.hasPrefix("hors-champ") { return "Hors du champ du modèle" }124 switch code {125 case "non-rattachee": return "Propriété non rattachée au rôle"126 case "caracteristiques-discordantes": return "Caractéristiques discordantes"127 case "mesures-discordantes": return "Mesures discordantes"128 case "sans-repere", "sans-coordonnees", "non-estimee", "donnees-insuffisantes": return "Données insuffisantes"129 default: return nil130 }131 }132}133134/// Le bloc `valeur` de l'API v3 (complet sur une fiche, résumé dans les listes).135struct ValueBlock: JSONModel, Hashable, Codable {136 var status: ValueStatus?137 var value: Double?138 var low: Double?139 var high: Double?140 /// (haut − bas) / valeur141 var width: Double?142 /// `haute`, `moyenne`, `faible`143 var confidence: String?144 var motif: Motif?145 var dateValeur: String?146 var ventesJusqua: String?147 var modele: String?148 var level: Double?149150 init(status: ValueStatus?, value: Double? = nil, low: Double? = nil, high: Double? = nil, motif: Motif? = nil) {151 self.status = status; self.value = value; self.low = low; self.high = high; self.motif = motif152 }153154 init(json j: JSONValue) {155 status = j["statut"].text.flatMap(ValueStatus.init(rawValue:))156 value = j["valeur"].double; low = j["bas"].double; high = j["haut"].double157 width = j["largeur"].double; confidence = j["confiance"].text158 motif = j["motif"].model(Motif.self)159 dateValeur = j["date_valeur"].text; ventesJusqua = j["ventes_jusqua"].text; modele = j["modele"].text160 level = j["niveau_intervalle"].double161 // un statut inconnu de cette version : un montant complet se lit comme un ordre de grandeur, sinon rien162 if status == nil, !j["statut"].isNull { status = (value != nil && low != nil && high != nil) ? .ordre : .abstention }163 }164165 /// Montants complets d'un régime qui en porte.166 var amounts: (value: Double, low: Double, high: Double)? {167 guard let status, status.hasAmount, let value, let low, let high, value > 0, low <= value, high >= value else { return nil }168 return (value, low, high)169 }170171 var isFirm: Bool { status == .valeur && amounts != nil }172173 var confidenceLabel: String? {174 switch confidence {175 case "haute": "Confiance haute"176 case "moyenne": "Confiance moyenne"177 case "faible": "Confiance faible"178 default: nil179 }180 }181}182183// MARK: - Position d'un prix184185/// Position d'un prix face à l'intervalle : la seule convention de l'API v3. Aucune quatrième position.186enum PricePosition: String, Sendable, Hashable, Codable, CaseIterable {187 case sous188 case dans189 case auDessus = "au-dessus"190191 var label: String {192 switch self {193 case .sous: "Sous l'intervalle"194 case .dans: "Dans l'intervalle"195 case .auDessus: "Au-dessus de l'intervalle"196 }197 }198 var shortLabel: String {199 switch self {200 case .sous: "Sous"201 case .dans: "Dans"202 case .auDessus: "Au-dessus"203 }204 }205 /// −1 à gauche de l'intervalle, 0 dedans, +1 à droite206 var side: Int {207 switch self {208 case .sous: -1209 case .dans: 0210 case .auDessus: 1211 }212 }213214 /// Règle du moteur, pour un prix déjà comparable (bornes comprises). Sert aux écrans qui n'ont que les montants.215 init(price: Double, low: Double, high: Double) {216 self = price < low ? .sous : (price > high ? .auDessus : .dans)217 }218}219220/// Bloc `position` d'une inscription, ou réponse de `/api/v3/position`.221struct PositionBlock: JSONModel, Hashable, Codable {222 var position: PricePosition?223 var motif: String?224 var motifLibelle: String?225 /// le prix réellement comparé (un prix demandé est d'abord ramené au prix de vente attendu)226 var prixCompare: Double?227 var ecartPct: Double?228 var value: Double?229 var low: Double?230 var high: Double?231 var rapport: Double?232233 init(json j: JSONValue) {234 position = j["position"].text.flatMap(PricePosition.init(rawValue:))235 motif = j["motif"].text; motifLibelle = j["motif_libelle"].text236 prixCompare = j["prix_compare"].double; ecartPct = j["ecart_pct"].double237 // `valeur` est un montant dans le bloc d'une inscription, un bloc de valeur dans /api/v3/position238 value = j["valeur"].double ?? j["valeur"]["valeur"].double239 low = j["bas"].double ?? j["valeur"]["bas"].double240 high = j["haut"].double ?? j["valeur"]["haut"].double241 rapport = j["rapport_vente_demande"].double242 }243}244245struct PositionV3: JSONModel {246 var block: PositionBlock247 var valeur: ValueBlock?248 init(json j: JSONValue) { block = PositionBlock(json: j); valeur = j["valeur"].model() }249}250251// MARK: - Territoire (référence)252253struct TerritoryRef: JSONModel, Hashable, Identifiable {254 var id: String255 var niveau: String256 var nom: String257 var slug: String?258 var municipaliteSlug: String?259260 init(json j: JSONValue) {261 id = j["id"].text ?? ""262 niveau = j["niveau"].text ?? ""263 nom = j["nom"].text ?? ""264 slug = j["slug"].text; municipaliteSlug = j["municipalite_slug"].text265 }266267 /// Nom à l'écran : celui d'une rue vient du rôle en capitales.268 var title: String { niveau == "rue" ? Fmt.address(nom) : nom }269270 var levelLabel: String { TerritoryRef.levelLabel(niveau) }271272 static func levelLabel(_ n: String) -> String {273 switch n {274 case "province": "Province"275 case "region": "Région"276 case "mrc": "MRC"277 case "municipalite": "Municipalité"278 case "arrondissement": "Arrondissement"279 case "rue": "Rue"280 default: Fmt.capitalized(n)281 }282 }283}284285// MARK: - Fiche d'une propriété286287struct PropertyV3: JSONModel {288 /// Caractéristique que le moteur nettoie : sa valeur, et d'où elle vient.289 struct Sourced: Sendable, Hashable {290 var value: Double?291 /// `role`, `role-estimee`, `ecartee`, `absente`292 var provenance: String?293 var roleValue: Double?294 init(_ j: JSONValue) { value = j["valeur"].double; provenance = j["provenance"].text; roleValue = j["valeur_au_role"].double }295296 var note: String? {297 switch provenance {298 case "role-estimee": "estimée par l'évaluateur municipal"299 case "ecartee": "valeur du rôle écartée comme invalide"300 default: nil301 }302 }303 }304305 struct LastSale: Sendable, Hashable {306 var date: String?307 var prix: Double?308 var deMarche: Bool?309 var prixRamene: Double?310 var rameneMotif: String?311 var dansIntervalle: Bool?312 }313314 struct Roll: Sendable, Hashable {315 var montant: Double?316 var terrain: Double?317 var batiment: Double?318 var reference: String?319 var anterieure: Double?320 }321322 var id: String323 var adresse: String?324 var appartement: String?325 var municipalite: String?326 var municipaliteSlug: String?327 var lat: Double?328 var lng: Double?329 var genre: String?330 var genreLibelle: String?331 var immeubleUnites: Int?332 var annee: Sourced333 var aire: Sourced334 var terrain: Sourced335 var logements: Sourced336 var etages: Int?337 var front: Double?338 var lienPhysique: String?339 var forme: String?340 var usage: String?341 var matricule: String?342 var roleReference: String?343 var territoires: [TerritoryRef]344 var valeur: ValueBlock345 var derniereVente: LastSale?346 var inscriptions: [ListingV3]347 var ventesUnite: [SaleV3]348 var ventesImmeuble: [SaleV3]349 var totalImmeuble: Int350 var role: Roll351 var roleRatio: Double?352 var roleRatioDate: String?353 var page: String?354355 init(json j: JSONValue) {356 id = j["id"].text ?? ""357 let a = j["adresse"]358 adresse = a["brute"].text; appartement = a["appartement"].text359 municipalite = a["municipalite"].text; municipaliteSlug = a["municipalite_slug"].text360 lat = j["lat"].double; lng = j["lng"].double361 genre = j["genre"].text; genreLibelle = j["genre_libelle"].text362 immeubleUnites = j["immeuble"]["nb_unites"].int363 let c = j["caracteristiques"]364 annee = Sourced(c["annee_construction"]); aire = Sourced(c["aire_etages_m2"])365 terrain = Sourced(c["terrain_m2"]); logements = Sourced(c["nb_logements"])366 etages = c["nb_etages"].int; front = c["front_terrain_m"].double367 lienPhysique = c["lien_physique"].text368 forme = c["forme_batiment"]["libelle"].text ?? c["genre_construction"].text369 usage = c["usage"]["libelle"].text; matricule = c["matricule"].text370 roleReference = c["millesime"]["role_reference"].text371 let t = j["territoires"]372 territoires = ["region", "mrc", "municipalite", "arrondissement", "rue"].compactMap { t[$0].model(TerritoryRef.self) }373 valeur = j["valeur"].model() ?? ValueBlock(status: nil)374 if let d = j["derniere_vente"].object {375 derniereVente = LastSale(date: d["date"].text, prix: d["prix_vente"].double, deMarche: d["de_marche"].bool,376 prixRamene: d["prix_ramene_a_la_date_de_valeur"].double,377 rameneMotif: d["prix_ramene_motif"]["libelle"].text, dansIntervalle: d["dans_l_intervalle"].bool)378 }379 inscriptions = j["inscriptions"].list()380 ventesUnite = j["ventes"]["unite"].list(); ventesImmeuble = j["ventes"]["immeuble"].list()381 totalImmeuble = j["ventes"]["total_immeuble"].int ?? ventesImmeuble.count382 let r = j["reperes"]["valeur_role"]383 role = Roll(montant: r["montant"].double, terrain: r["terrain"].double, batiment: r["batiment"].double,384 reference: r["reference"].text, anterieure: r["anterieure"].double)385 roleRatio = j["reperes"]["role_ratio_municipal"]["montant"].double386 roleRatioDate = j["reperes"]["role_ratio_municipal"]["date"].text387 page = j["liens"]["page"].text388 }389390 var title: String {391 let s = Fmt.address(adresse)392 if let appartement, !appartement.isEmpty { return s + ", app. " + appartement }393 return s.isEmpty ? "Propriété" : s394 }395396 var kind: String { [genreLibelle.map(Fmt.capitalized), municipalite].compactMap { $0 }.joined(separator: " · ") }397398 var coordinate: CLLocationCoordinate2D? {399 guard let lat, let lng, lat != 0, lng != 0 else { return nil }400 return .init(latitude: lat, longitude: lng)401 }402403 /// L'inscription en ligne dont le prix demandé se lit contre la valeur (la plus récemment vue).404 var listing: ListingV3? { inscriptions.first }405}406407// MARK: - Ventes408409struct SaleMark: JSONModel, Hashable {410 var code: String411 var famille: String?412 var libelle: String413 init(json j: JSONValue) { code = j["code"].text ?? ""; famille = j["famille"].text; libelle = j["libelle"].text ?? (j["code"].text ?? "") }414}415416/// Une vente publiée : prix réel, avec sa qualification par le moteur quand il la connaît.417struct SaleV3: JSONModel, Hashable, Identifiable {418 var id: String419 var date: String?420 var prix: Double?421 var rue: String?422 var ville: String?423 var type: String?424 var annee: Int?425 var aireM2: Double?426 var terrainM2: Double?427 var lat: Double?428 var lng: Double?429 /// `unite`, `immeuble`, `ambigu`, `introuvable`430 var rattachement: String?431 var proprieteId: String?432 var roleALaVente: Double?433 var ratioRole: Double?434 /// nil : vente que le moteur n'a pas encore qualifiée435 var deMarche: Bool?436 var marques: [SaleMark]437 var deCettePropriete: Bool?438439 init(json j: JSONValue) {440 id = j["id"].text ?? ""441 date = j["date"].text; prix = j["prix_vente"].double442 rue = j["rue"].text ?? j["adresse"].text; ville = j["ville"].text; type = j["type_vente"].text443 annee = j["annee_construction"].int; aireM2 = j["aire_etages_m2"].double; terrainM2 = j["terrain_m2"].double444 lat = j["lat"].double; lng = j["lng"].double445 rattachement = j["rattachement"].text ?? j["niveau"].text446 proprieteId = j["propriete_id"].text447 roleALaVente = j["role_a_la_vente"].double; ratioRole = j["ratio_prix_role"].double448 let q = j["qualification"]449 deMarche = q["de_marche"].bool ?? j["de_marche"].bool450 marques = q["marques"].items.isEmpty ? j["marques"].list() : q["marques"].list()451 deCettePropriete = j["de_cette_propriete"].bool452 }453454 var title: String { Fmt.address(rue).isEmpty ? "Adresse non publiée" : Fmt.address(rue) }455 var typeLabel: String? {456 switch type {457 case "unifamilial": "Unifamiliale"458 case "condo": "Copropriété"459 case "plex": "Plex"460 case nil, "indéterminé": nil461 default: type.map(Fmt.capitalized)462 }463 }464 var coordinate: CLLocationCoordinate2D? {465 guard let lat, let lng, lat != 0, lng != 0 else { return nil }466 return .init(latitude: lat, longitude: lng)467 }468}469470struct SalesPageV3: JSONModel {471 var items: [SaleV3]472 var total: Int?473 var totalAll: Int?474 var nextCursor: String?475 var since: String?476 var updatedTo: String?477 var qualified: Bool478 var truncated: Bool479480 init(json j: JSONValue) {481 items = j["items"].list()482 total = j["total"].int; totalAll = j["total_toutes_ventes"].int483 nextCursor = j["next_cursor"].text; since = j["since"].text; updatedTo = j["updated_to"].text484 qualified = j["qualifications_disponibles"].bool ?? true485 truncated = j["truncated"].bool ?? false486 }487}488489struct SaleDetailV3: JSONModel {490 var vente: SaleV3491 var connue: Bool492 var deMarche: Bool?493 var marques: [SaleMark]494 var roleALaVente: Double?495 var roleAnnee: Int?496 var ratio: Double?497 var ratioAttendu: Double?498 var bandeBas: Double?499 var bandeHaut: Double?500 var niveau: String?501 var rattachementLibelle: String?502 var distanceM: Double?503 var proprieteId: String?504 var proprieteTitre: String?505 var proprieteGenre: String?506 var proprieteValeur: ValueBlock?507 var avertissementValeur: String?508 var autresUnite: [SaleV3]509 var autresImmeuble: [SaleV3]510 var valeurALaVenteMotif: String?511 var page: String?512513 init(json j: JSONValue) {514 vente = j["vente"].model() ?? SaleV3(json: .object([:]))515 connue = j["connue_du_moteur"].bool ?? false516 let q = j["qualification"]517 deMarche = q["de_marche"].bool; marques = q["marques"].list()518 roleALaVente = q["role_a_la_vente"].double; roleAnnee = q["role_annee_de_reference"].int519 ratio = q["ratio_prix_role"].double; ratioAttendu = q["ratio_attendu"].double520 bandeBas = q["bande"]["bas"].double; bandeHaut = q["bande"]["haut"].double521 let r = j["rattachement"]522 niveau = r["niveau"].text; rattachementLibelle = r["motif_libelle"].text; distanceM = r["distance_m"].double523 let p = j["propriete"]524 proprieteId = p["id"].text525 if let a = p["adresse"].text {526 let s = Fmt.address(a)527 proprieteTitre = (p["appartement"].text).map { s + ", app. " + $0 } ?? s528 }529 proprieteGenre = p["genre_libelle"].text530 proprieteValeur = p["valeur"].model()531 avertissementValeur = p["valeur_non_comparable_au_prix"].text532 autresUnite = j["autres_ventes"]["unite"].list(); autresImmeuble = j["autres_ventes"]["immeuble"].list()533 valeurALaVenteMotif = j["valeur_a_la_vente"]["motif"].text534 page = j["liens"]["page"].text535 }536}537538// MARK: - Inscriptions539540/// Une propriété à vendre : ce que l'annonce publie, et les blocs du moteur (rattachement, valeur, position).541struct ListingV3: JSONModel, Hashable, Identifiable {542 struct PricePoint: Sendable, Hashable, Identifiable {543 var date: String544 var prix: Double545 var id: String { date }546 }547548 var id: String549 var source: String?550 var url: String?551 var titre: String?552 var adresse: String?553 var ville: String?554 var secteur: String?555 var typeAnnonce: String?556 var groupe: String?557 var prixDemande: Double?558 var chambres: Int?559 var sallesDeBain: Int?560 var superficiePi2: Double?561 var terrainPi2: Double?562 var annee: Int?563 var image: String?564 var nbImages: Int?565 var lat: Double?566 var lng: Double?567 var vueLe: String?568 var premiereVueLe: String?569 /// `unite`, `immeuble`, `ambigu`, `introuvable`570 var niveau: String?571 var rattachementLibelle: String?572 var proprieteId: String?573 var valeur: ValueBlock?574 var position: PositionBlock?575 var regroupement: Int?576 // détail577 var etat: String?578 var vivante: Bool?579 var description: String?580 var caracteristiques: [String]581 var images: [String]582 var courtier: String?583 var agence: String?584 var numero: String?585 var historique: [PricePoint]586587 init(json j: JSONValue) {588 id = j["id"].text ?? ""589 source = j["source"].text; url = j["url"].text; titre = j["titre"].text590 adresse = j["adresse"].text; ville = j["ville"].text ?? j["municipalite"].text; secteur = j["secteur"].text591 typeAnnonce = j["type_annonce"].text; groupe = j["groupe"].text592 prixDemande = j["prix_demande"].double593 chambres = j["chambres"].int; sallesDeBain = j["salles_de_bain"].int594 superficiePi2 = j["superficie_pi2"].double; terrainPi2 = j["terrain_pi2"].double595 annee = j["annee_construction"].int596 images = j["images"].items.compactMap(\.text)597 image = j["image"].text ?? j["photo"]["origine"].text ?? images.first598 nbImages = j["nb_images"].int ?? j["nb_photos"].int ?? (images.isEmpty ? nil : images.count)599 lat = j["lat"].double; lng = j["lng"].double600 vueLe = j["vue_le"].text; premiereVueLe = j["premiere_vue_le"].text601 let r = j["rattachement"]602 niveau = r["niveau"].text; rattachementLibelle = r["motif_libelle"].text; proprieteId = r["propriete_id"].text603 valeur = j["valeur"].model(); position = j["position"].model()604 regroupement = j["regroupement"]["inscriptions"].int ?? (j["regroupement"]["inscriptions"].items.isEmpty ? nil : j["regroupement"]["inscriptions"].items.count)605 etat = j["etat"].text; vivante = j["vivante"].bool606 description = j["description"].text607 caracteristiques = j["caracteristiques"].items.compactMap(\.text)608 courtier = j["courtier"].text ?? j["courtier"]["nom"].text609 agence = j["agence"].text ?? j["agence"]["nom"].text610 numero = j["numero_inscription"].text611 historique = j["historique_prix_demande"].items.compactMap { p in612 guard let d = p["date"].text, let v = p["prix_demande"].double else { return nil }613 return PricePoint(date: d, prix: v)614 }615 }616617 var title: String {618 let a = Fmt.address(adresse)619 return a.isEmpty ? (titre ?? typeAnnonce ?? "Propriété à vendre") : a620 }621 var place: String { [secteur, ville].compactMap { $0 }.filter { !$0.isEmpty }.reduce(into: [String]()) { if !$0.contains($1) { $0.append($1) } }.joined(separator: ", ") }622 var isOnline: Bool { vivante ?? (etat == nil || etat == "en-ligne") }623 var stateLabel: String? {624 switch etat {625 case "retiree": "Inscription retirée"626 case "vendue": "Inscription vendue"627 default: nil628 }629 }630 var coordinate: CLLocationCoordinate2D? {631 guard let lat, let lng, lat != 0, lng != 0 else { return nil }632 return .init(latitude: lat, longitude: lng)633 }634 var sourceLabel: String { (source ?? "").replacingOccurrences(of: "_", with: " ").capitalized }635636 static func groupLabel(_ g: String?) -> String {637 switch g {638 case "maison": "Maison"639 case "condo": "Copropriété"640 case "plex": "Plex"641 case "terrain": "Terrain"642 case "chalet": "Chalet"643 case "fermette": "Fermette"644 case "mobile": "Maison mobile"645 case "commercial": "Commercial"646 case "autre", nil: "Autre"647 default: Fmt.capitalized(g ?? "")648 }649 }650}651652struct ListingsPageV3: JSONModel {653 struct Facet: Sendable, Hashable, Identifiable {654 var key: String655 var n: Int656 var id: String { key }657 }658659 var items: [ListingV3]660 var total: Int?661 var nextCursor: String?662 var groupes: [Facet]663 var municipalites: [Facet]664 var positions: [String: Int]665 var releveLe: String?666 var linked: Bool667 var truncated: Bool668669 init(json j: JSONValue) {670 items = j["items"].list()671 total = j["total"].int; nextCursor = j["next_cursor"].text672 let f = j["facets"]673 groupes = f["groupes"].items.compactMap { x in x["groupe"].text.map { Facet(key: $0, n: x["n"].int ?? 0) } }674 municipalites = f["municipalites"].items.compactMap { x in x["nom"].text.map { Facet(key: $0, n: x["n"].int ?? 0) } }675 positions = f["positions"].counts676 releveLe = j["releve_le"].text677 linked = j["rattachements_disponibles"].bool ?? true678 truncated = j["truncated"].bool ?? false679 }680}681682// MARK: - Comparables683684struct ComparableV3: JSONModel, Hashable, Identifiable {685 var venteId: String686 var proprieteId: String?687 var date: String?688 var prix: Double?689 /// prix ramené au niveau de prix d'aujourd'hui par l'indice : une aide à la lecture, hors de la valeur690 var prixAjuste: Double?691 var ajustementSerie: String?692 var ajustementMotif: String?693 var adresse: String?694 var municipalite: String?695 var lat: Double?696 var lng: Double?697 var distanceM: Double?698 var aireM2: Double?699 var annee: Int?700 var comparabilite: String?701 var rapproche: [String]702 var separe: [String]703 var memeUnite: Bool704705 var id: String { venteId }706707 init(json j: JSONValue) {708 venteId = j["vente_id"].text ?? UUID().uuidString709 proprieteId = j["propriete_id"].text710 date = j["date"].text; prix = j["prix_vente"].double; prixAjuste = j["prix_ajuste"].double711 ajustementSerie = j["ajustement"]["serie_nom"].text; ajustementMotif = j["ajustement"]["motif_libelle"].text712 adresse = j["adresse"].text; municipalite = j["municipalite"].text713 lat = j["lat"].double; lng = j["lng"].double; distanceM = j["distance_m"].double714 aireM2 = j["aire_etages_m2"].double; annee = j["annee_construction"].int715 comparabilite = j["comparabilite"].text716 rapproche = j["rapproche"].items.compactMap { $0["libelle"].text }717 separe = j["separe"].items.compactMap { $0["libelle"].text }718 memeUnite = j["meme_unite"].bool ?? false719 }720721 var coordinate: CLLocationCoordinate2D? {722 guard let lat, let lng, lat != 0, lng != 0 else { return nil }723 return .init(latitude: lat, longitude: lng)724 }725}726727struct ComparablesV3: JSONModel {728 var items: [ComparableV3]729 var sansComparables: Motif?730 var fenetreMois: Int?731 var prixAjustes: Int?732733 init(json j: JSONValue) {734 items = j["items"].list()735 sansComparables = j["sans_comparables"].model()736 fenetreMois = j["fenetre_mois"].int; prixAjustes = j["nature"]["prix_ajustes"].int737 }738}739740// MARK: - Carte de valeurs741742struct PropertyPointV3: JSONModel, Hashable, Identifiable {743 var id: String744 var adresse: String?745 var appartement: String?746 var municipalite: String?747 var genre: String?748 var genreLibelle: String?749 var lat: Double750 var lng: Double751 var valeurRole: Double?752 var valeur: ValueBlock?753754 init(json j: JSONValue) {755 id = j["id"].text ?? ""756 adresse = j["adresse"].text; appartement = j["appartement"].text757 municipalite = j["municipalite"].text; genre = j["genre"].text; genreLibelle = j["genre_libelle"].text758 lat = j["lat"].double ?? 0; lng = j["lng"].double ?? 0759 valeurRole = j["valeur_role"].double; valeur = j["valeur"].model()760 }761762 var title: String {763 let s = Fmt.address(adresse)764 if let appartement, !appartement.isEmpty { return s + ", app. " + appartement }765 return s766 }767}768769struct PropertiesV3: JSONModel {770 var items: [PropertyPointV3]771 var truncated: Bool772 var available: Bool773 init(json j: JSONValue) {774 items = j["items"].list(PropertyPointV3.self).filter { $0.lat != 0 && $0.lng != 0 }775 truncated = j["truncated"].bool ?? false776 available = j["valeurs_disponibles"].bool ?? true777 }778}779780// MARK: - Recherche781782struct SearchV3: JSONModel {783 struct Address: Sendable, Hashable, Identifiable {784 struct UnitRef: Sendable, Hashable, Identifiable {785 var id: String786 var appartement: String?787 }788 var adresse: String789 var municipalite: String?790 var uniteId: String?791 var unites: [UnitRef]792 var nbUnites: Int793 var genreLibelle: String?794 var lat: Double?795 var lng: Double?796 var id: String { adresse + "|" + (municipalite ?? "") }797 var title: String { Fmt.address(adresse) }798 var subtitle: String {799 [municipalite, nbUnites > 1 ? "\(Fmt.int(nbUnites)) unités" : genreLibelle.map(Fmt.capitalized)].compactMap { $0 }.joined(separator: " · ")800 }801 }802803 struct Place: Sendable, Hashable, Identifiable {804 var type: String805 var nom: String806 var municipalite: String?807 var slug: String?808 var municipaliteSlug: String?809 var nbUnites: Int?810 var id: String { type + "|" + nom + "|" + (municipaliteSlug ?? "") }811 var title: String { type == "rue" ? Fmt.address(nom) : nom }812 var subtitle: String {813 [type == "rue" ? "Rue" : "Municipalité", type == "rue" ? municipalite : nil, nbUnites.flatMap { $0 > 0 ? "\(Fmt.int($0)) propriétés" : nil }]814 .compactMap { $0 }.joined(separator: " · ")815 }816 /// Identifiant de territoire à ouvrir : le slug de la municipalité ; une rue se résout par la liste des rues.817 var territory: String? { type == "municipalite" ? (slug ?? municipaliteSlug) : nil }818 }819820 var adresses: [Address]821 var lieux: [Place]822 var corrections: [String]823824 init(json j: JSONValue) {825 adresses = j["adresses"].items.compactMap { a in826 guard let adr = a["adresse"].text else { return nil }827 return Address(adresse: adr, municipalite: a["municipalite"].text, uniteId: a["unite_id"].text,828 unites: a["unites"].items.compactMap { u in u["id"].text.map { .init(id: $0, appartement: u["appartement"].text) } },829 nbUnites: a["nb_unites"].int ?? 1, genreLibelle: a["genre_libelle"].text, lat: a["lat"].double, lng: a["lng"].double)830 }831 lieux = j["lieux"].items.compactMap { p in832 guard let nom = p["nom"].text, let type = p["type"].text else { return nil }833 return Place(type: type, nom: nom, municipalite: p["municipalite"].text, slug: p["slug"].text,834 municipaliteSlug: p["municipalite_slug"].text, nbUnites: p["nb_unites"].int)835 }836 corrections = j["requete"]["corrections"].items.compactMap { c in837 c.text ?? [c["de"].text, c["a"].text].compactMap { $0 }.joined(separator: " → ")838 }.filter { !$0.isEmpty }839 }840841 var isEmpty: Bool { adresses.isEmpty && lieux.isEmpty }842}843844// MARK: - Estimation libre845846struct FreeEstimateV3: JSONModel {847 var status: ValueStatus?848 var value: Double?849 var low: Double?850 var high: Double?851 var motif: Motif?852 var nVentes: Int?853 var rayonKm: Double?854 var base: String?855 var precision: String?856 var depuis: String?857 var jusqua: String?858 var erreurMedianePct: Double?859 var dansIntervallePct: Double?860 var methode: String?861 var comparables: [ComparableV3]862863 init(json j: JSONValue) {864 status = j["statut"].text.flatMap(ValueStatus.init(rawValue:))865 value = j["valeur"].double; low = j["bas"].double; high = j["haut"].double866 motif = j["motif"].model()867 nVentes = j["n_ventes"].int; rayonKm = j["rayon_km"].double; base = j["base"].text868 precision = j["point"]["precision"].text869 depuis = j["periode"]["depuis"].text; jusqua = j["periode"]["jusqua"].text870 erreurMedianePct = j["mesure"]["erreur_mediane_pct"].double871 dansIntervallePct = j["mesure"]["dans_l_intervalle_pct"].double872 methode = j["nature"]["methode"].text873 comparables = j["comparables"].list()874 }875}876877// MARK: - Points de carte878879extension MapPoint {880 /// Propriété de la carte de valeurs : le montant de l'étiquette est celui d'une valeur ferme ou d'un ordre de grandeur.881 init(v3 p: PropertyPointV3) {882 self.init(id: "u" + p.id, layer: .units, lat: p.lat, lng: p.lng, amount: p.valeur?.amounts?.value, title: p.title,883 subtitle: [p.municipalite, p.genreLibelle.map(Fmt.capitalized)].compactMap { $0 }.joined(separator: " · "),884 type: p.genre, date: nil, unitID: p.id, est: p.valeur?.amounts?.value, image: nil, vsRolePct: nil, reading: nil, note: nil,885 v3: V3(value: p.valeur ?? ValueBlock(status: nil)))886 }887888 init?(v3 s: SaleV3) {889 guard let c = s.coordinate else { return nil }890 self.init(id: "s" + s.id, layer: .sales, lat: c.latitude, lng: c.longitude, amount: s.prix, title: s.title,891 subtitle: [s.ville, s.typeLabel].compactMap { $0 }.joined(separator: " · "), type: s.type, date: s.date,892 unitID: s.proprieteId, est: nil, image: nil, vsRolePct: nil, reading: nil,893 note: s.deMarche == false ? (s.marques.first?.libelle).map { "Hors marché : " + $0 } ?? "Vente hors marché" : nil,894 v3: V3(saleID: s.id, marketSale: s.deMarche))895 }896897 init?(v3 l: ListingV3) {898 guard let c = l.coordinate else { return nil }899 self.init(id: "l" + l.id, layer: .listings, lat: c.latitude, lng: c.longitude, amount: l.prixDemande, title: l.title,900 subtitle: [l.place, ListingV3.groupLabel(l.groupe)].filter { !$0.isEmpty }.joined(separator: " · "), type: l.groupe, date: nil,901 unitID: l.id, est: l.valeur?.amounts?.value, image: l.image, vsRolePct: nil, reading: nil,902 note: l.valeur?.amounts == nil ? (l.niveau == "unite" ? l.valeur?.motif?.libelle : l.rattachementLibelle).map { "Sans valeur : " + $0 } : l.position?.motifLibelle,903 v3: V3(value: l.valeur, position: l.position?.position, gapPct: l.position?.ecartPct, hasPositionBlock: true))904 }905}906