SPB Git

Repository Public

Responses.swift 43.2 KB 1,101 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : Immo-Ka iOS9// File             : ImmoKa/Core/Models/Responses.swift10// Description      : réponses de l'API — recherche, facettes, annuaires11//                    (agences, bannières, inspecteurs, déménageurs), blocs12//                    d'environnement de la fiche, statistiques du marché, taux13//                    hypothécaires.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 Foundation9495struct APIVersion: Decodable, Sendable {96    var api: Int97    /// seuils du verdict du vrai prix, publiés par le service98    var thresholds: VerdictThresholds?99    init(from decoder: Decoder) throws {100        let c = try decoder.container(keyedBy: AnyKey.self)101        api = c.int(AnyKey("api")) ?? 0102        thresholds = try? c.decode(VerdictThresholds.self, forKey: AnyKey("verdict_thresholds"))103    }104}105106// MARK: - Recherche107108/// Point compact de la carte : [uid, lng, lat, prix, verdict] (v2) ou [uid, lng, lat, prix, position, famille] (v3).109struct MapPoint: Decodable, Sendable, Hashable {110    var uid: String111    var lng: Double112    var lat: Double113    var price: Double?114    var verdict: Verdict?115116    init(uid: String, lng: Double, lat: Double, price: Double?, verdict: Verdict?) {117        self.uid = uid; self.lng = lng; self.lat = lat; self.price = price; self.verdict = verdict118    }119120    init(from decoder: Decoder) throws {121        var c = try decoder.unkeyedContainer()122        uid = try c.decode(String.self)123        lng = try c.decode(Double.self)124        lat = try c.decode(Double.self)125        price = c.isAtEnd ? nil : try c.decodeIfPresent(Double.self)126        let code: String? = c.isAtEnd ? nil : try c.decodeIfPresent(String.self)127        verdict = Verdict(code: code)128    }129}130131/// Recherche unifiée (v2) : page de liste et, sur demande, tous les points de carte.132struct SearchResponse: Decodable, Sendable {133    var total: Int134    var page: Int135    var pageSize: Int136    var listings: [Listing]137    var points: [MapPoint]?138    var unpositioned: Int139140    init(total: Int, page: Int, pageSize: Int, listings: [Listing], points: [MapPoint]? = nil, unpositioned: Int = 0) {141        self.total = total; self.page = page; self.pageSize = pageSize142        self.listings = listings; self.points = points; self.unpositioned = unpositioned143    }144145    init(from decoder: Decoder) throws {146        let c = try decoder.container(keyedBy: AnyKey.self)147        total = c.int(AnyKey("total")) ?? 0148        page = c.int(AnyKey("page")) ?? 1149        pageSize = c.int(AnyKey("page_size")) ?? 24150        listings = c.list(AnyKey("listings"))151        unpositioned = c.int(AnyKey("unpositioned")) ?? 0152        points = c.contains(AnyKey("points")) && (try? c.decodeNil(forKey: AnyKey("points"))) == false153            ? c.list(AnyKey("points")) : nil154    }155}156157/// Liste paginée (v1) : `/api/listings`.158struct ListingsPage: Decodable, Sendable {159    var total: Int160    var listings: [Listing]161    init(from decoder: Decoder) throws {162        let c = try decoder.container(keyedBy: AnyKey.self)163        total = c.int(AnyKey("total")) ?? 0164        listings = c.list(AnyKey("listings"))165    }166}167168/// Collection GeoJSON (v1) : `/api/listings.geojson` — propriétés géolocalisées, champs allégés.169struct GeoCollection: Decodable, Sendable {170    private struct Feature: Decodable {171        var listing: Listing172        init(from decoder: Decoder) throws {173            let c = try decoder.container(keyedBy: AnyKey.self)174            var l = try c.decode(Listing.self, forKey: AnyKey("properties"))175            let g = try c.nestedContainer(keyedBy: AnyKey.self, forKey: AnyKey("geometry"))176            let xy = try g.decode([Double].self, forKey: AnyKey("coordinates"))177            guard xy.count >= 2 else {178                throw DecodingError.dataCorrupted(.init(codingPath: decoder.codingPath, debugDescription: "coordonnées absentes"))179            }180            l.lng = xy[0]; l.lat = xy[1]181            listing = l182        }183    }184    var listings: [Listing]185    var totalGeocoded: Int186    var totalMatching: Int187188    init(from decoder: Decoder) throws {189        let c = try decoder.container(keyedBy: AnyKey.self)190        listings = c.list(AnyKey("features"), Feature.self).map(\.listing)191        totalGeocoded = c.int(AnyKey("totalGeocoded")) ?? listings.count192        totalMatching = c.int(AnyKey("totalMatching")) ?? totalGeocoded193    }194}195196/// Valeur de facette avec son effectif. La v1 publie de simples chaînes, la v2 des objets `{<clé>: …, n: …}`.197struct FacetValue: Decodable, Sendable, Hashable, Identifiable {198    var value: String199    var n: Int200    var name: String?201    var id: String { value }202203    init(value: String, n: Int = 0) { self.value = value; self.n = n }204205    init(from decoder: Decoder) throws {206        if let s = try? decoder.singleValueContainer().decode(String.self) {207            value = s; n = 0208            return209        }210        let c = try decoder.container(keyedBy: AnyKey.self)211        guard let v = c.text(AnyKey("city")) ?? c.text(AnyKey("sector")) ?? c.text(AnyKey("property_type"))212                ?? c.text(AnyKey("source")) ?? c.text(AnyKey("region")) ?? c.text(AnyKey("value")) else {213            throw DecodingError.dataCorrupted(.init(codingPath: decoder.codingPath, debugDescription: "facette sans valeur"))214        }215        value = v216        n = c.int(AnyKey("n")) ?? 0217        name = c.text(AnyKey("name"))218    }219}220221struct Facets: Decodable, Sendable {222    typealias SourceCount = FacetValue223    var cities: [FacetValue]224    var sectors: [FacetValue]225    var propertyTypes: [FacetValue]226    var sources: [FacetValue]227    var regions: [FacetValue]228229    init(from decoder: Decoder) throws {230        let c = try decoder.container(keyedBy: AnyKey.self)231        // les sources publient des « villes » qui n'en sont pas (« 5 », « Acheter Condo… ») : on les écarte232        cities = c.list(AnyKey("cities"), FacetValue.self).filter { Fmt.isPlausibleCity($0.value) }233        sectors = c.list(AnyKey("sectors"), FacetValue.self).filter { Fmt.isPlausibleCity($0.value) }234        propertyTypes = c.list(AnyKey("property_types"))235        sources = c.list(AnyKey("sources"))236        regions = c.list(AnyKey("regions"))237    }238239    var cityNames: [String] { cities.map(\.value) }240}241242// MARK: - Blocs d'environnement de la fiche243244struct Inondation: Decodable, Sendable {245    var statut: String246    var severite: String?247    var couvert: Bool248    init(from decoder: Decoder) throws {249        let c = try decoder.container(keyedBy: AnyKey.self)250        statut = c.str(AnyKey("statut")) ?? ""251        severite = c.text(AnyKey("severite"))252        couvert = c.bool(AnyKey("couvert")) ?? false253    }254    var enZone: Bool { couvert && !statut.isEmpty && statut != "hors_zone" }255    var texte: String {256        if !couvert { return "Secteur non couvert par la cartographie des zones inondables." }257        if !enZone { return "Hors des zones inondables cartographiées." }258        let s = severite.map { " (\($0.replacingOccurrences(of: "_", with: " ")))" } ?? ""259        return "Dans une zone inondable cartographiée\(s)."260    }261}262263struct AirNearby: Decodable, Sendable {264    struct Mesure: Sendable, Identifiable {265        var polluant: String266        var moyenne: Double267        var unite: String268        var ref: Double?269        var refNom: String?270        var annee: Int?271        var id: String { polluant }272    }273    var station: String?274    var distanceKm: Double?275    var mesures: [Mesure]276277    init(from decoder: Decoder) throws {278        let c = try decoder.container(keyedBy: AnyKey.self)279        station = c.text(AnyKey("station"))280        distanceKm = c.dbl(AnyKey("distance_km"))281        var out: [Mesure] = []282        if let m = try? c.nestedContainer(keyedBy: AnyKey.self, forKey: AnyKey("mesures")) {283            for k in m.allKeys {284                guard let v = try? m.nestedContainer(keyedBy: AnyKey.self, forKey: k), let avg = v.dbl(AnyKey("moyenne")) else { continue }285                out.append(Mesure(polluant: k.stringValue, moyenne: avg, unite: v.str(AnyKey("unite")) ?? "",286                                  ref: v.dbl(AnyKey("ref")), refNom: v.text(AnyKey("ref_nom")), annee: v.int(AnyKey("annee"))))287            }288        }289        mesures = out.sorted { $0.polluant < $1.polluant }290    }291}292293struct Commerces: Decodable, Sendable {294    struct Item: Decodable, Sendable, Identifiable {295        var id: String296        var commerce: String297        var nom: String298        var distM: Double299        var lat: Double?300        var lng: Double?301        init(from decoder: Decoder) throws {302            let c = try decoder.container(keyedBy: AnyKey.self)303            commerce = c.str(AnyKey("commerce")) ?? ""304            nom = c.str(AnyKey("nom")) ?? commerce305            distM = c.dbl(AnyKey("dist_m")) ?? 0306            lat = c.dbl(AnyKey("lat")); lng = c.dbl(AnyKey("lng"))307            id = (c.str(AnyKey("id")) ?? commerce) + "-\(Int(distM))"308        }309    }310    var commerces: [Item]311    init(from decoder: Decoder) throws {312        let c = try decoder.container(keyedBy: AnyKey.self)313        commerces = c.list(AnyKey("commerces")).filter { !$0.commerce.isEmpty }.sorted { $0.distM < $1.distM }314    }315}316317struct GazNearby: Decodable, Sendable {318    struct Station: Decodable, Sendable, Identifiable {319        var nom: String320        var adresse: String321        var distM: Double322        var regulier: Double?323        var moinsChere: Bool324        var id: String { "\(nom)-\(adresse)" }325        init(from decoder: Decoder) throws {326            let c = try decoder.container(keyedBy: AnyKey.self)327            nom = c.str(AnyKey("nom")) ?? ""328            adresse = c.str(AnyKey("adresse")) ?? ""329            distM = c.dbl(AnyKey("dist_m")) ?? 0330            regulier = c.dbl(AnyKey("regulier"))331            moinsChere = c.bool(AnyKey("moins_chere")) ?? false332        }333    }334    var medianeRegulier: Double?335    var stations: [Station]336    init(from decoder: Decoder) throws {337        let c = try decoder.container(keyedBy: AnyKey.self)338        medianeRegulier = c.dbl(AnyKey("mediane_regulier"))339        stations = c.list(AnyKey("stations"))340    }341}342343struct HydroEstimate: Decodable, Sendable {344    var disponible: Bool345    var coutMensuel: Double?346    var coutAnnuel: Double?347    var kwhAnnuel: Double?348    init(from decoder: Decoder) throws {349        let c = try decoder.container(keyedBy: AnyKey.self)350        disponible = c.bool(AnyKey("disponible")) ?? false351        coutMensuel = c.dbl(AnyKey("cout_mensuel")) ?? c.dbl(AnyKey("mensuel"))352        coutAnnuel = c.dbl(AnyKey("cout_annuel")) ?? c.dbl(AnyKey("annuel"))353        kwhAnnuel = c.dbl(AnyKey("kwh_annuel")) ?? c.dbl(AnyKey("kwh"))354        if coutMensuel == nil, let a = coutAnnuel { coutMensuel = a / 12 }355    }356}357358// MARK: - Annuaires359360/// Source d'inscriptions (bannière, courtier, portail).361struct SourceEntry: Decodable, Sendable, Identifiable, Hashable {362    var id: String363    var name: String364    var url: String?365    var listingURL: String?366    var coverage: String?367    var status: String368    var type: String369    var activeListings: Int370    var lastSync: Double?371372    init(from decoder: Decoder) throws {373        let c = try decoder.container(keyedBy: AnyKey.self)374        guard let i = c.text(AnyKey("id")) else {375            throw DecodingError.dataCorrupted(.init(codingPath: decoder.codingPath, debugDescription: "source sans id"))376        }377        id = i378        name = c.text(AnyKey("name")) ?? Fmt.prettySource(i)379        url = c.text(AnyKey("url"))380        listingURL = c.text(AnyKey("listing_url"))381        coverage = c.text(AnyKey("coverage"))382        status = c.str(AnyKey("status")) ?? ""383        type = c.str(AnyKey("type")) ?? ""384        activeListings = c.int(AnyKey("active_listings")) ?? 0385        lastSync = c.dbl(AnyKey("last_sync"))386    }387}388389struct SourcesResponse: Decodable, Sendable {390    var sources: [SourceEntry]391    init(from decoder: Decoder) throws {392        let c = try decoder.container(keyedBy: AnyKey.self)393        sources = c.list(AnyKey("sources"))394    }395}396397/// Bannière (franchise ou agence indépendante) et ses bureaux, avec le nombre d'inscriptions en ligne.398struct Franchise: Decodable, Sendable, Identifiable, Hashable {399    struct Office: Decodable, Sendable, Identifiable, Hashable {400        var name: String401        var count: Int402        var sources: [String]403        var id: String { name }404        init(from decoder: Decoder) throws {405            let c = try decoder.container(keyedBy: AnyKey.self)406            name = c.text(AnyKey("name")) ?? ""407            count = c.int(AnyKey("count")) ?? 0408            sources = c.strings(AnyKey("sources"))409        }410    }411    var name: String412    var total: Int413    var offices: [Office]414    var id: String { name }415416    init(from decoder: Decoder) throws {417        let c = try decoder.container(keyedBy: AnyKey.self)418        guard let n = c.text(AnyKey("franchise")) ?? c.text(AnyKey("name")) else {419            throw DecodingError.dataCorrupted(.init(codingPath: decoder.codingPath, debugDescription: "bannière sans nom"))420        }421        name = n422        total = c.int(AnyKey("total")) ?? 0423        offices = c.list(AnyKey("agencies")).filter { !$0.name.isEmpty }424    }425426    /// Sources à interroger pour lister les propriétés de la bannière (une seule quand c'est possible).427    var sources: [String] { Array(Set(offices.flatMap(\.sources))).sorted() }428}429430struct AgenciesTree: Decodable, Sendable {431    var franchises: [Franchise]432    init(from decoder: Decoder) throws {433        let c = try decoder.container(keyedBy: AnyKey.self)434        franchises = c.list(AnyKey("franchises"))435    }436    var totalListings: Int { franchises.reduce(0) { $0 + $1.total } }437    var totalOffices: Int { franchises.reduce(0) { $0 + $1.offices.count } }438}439440/// Entrée de l'annuaire enrichi (v2, `/api/agences`) : bannière, agence inscrite à l'OACIQ ou plateforme.441struct AgencyEntry: Decodable, Sendable, Identifiable, Hashable {442    enum Kind: String, Sendable { case franchise, agency, platform }443    struct Broker: Decodable, Sendable, Identifiable, Hashable {444        var name: String445        var city: String?446        var id: String { "\(name)|\(city ?? "")" }447        init(from decoder: Decoder) throws {448            let c = try decoder.container(keyedBy: AnyKey.self)449            name = c.text(AnyKey("name")) ?? ""450            city = c.text(AnyKey("city"))451        }452    }453    var kind: Kind = .agency454    var id: String455    var name: String456    var franchise: String?457    /// nombre de bureaux (bannière)458    var offices: Int?459    var brokers: Int?460    var regions: [String]461    var activeListings: Int462    var priceMedian: Double?463    var cities: [String]464    var citiesTotal: Int?465    var url: String?466    var source: String?467    /// « agence » : ses inscriptions portent son nom dans le champ `agency` ; « source » : une source lui est dédiée468    var matchedBy: String?469    /// bannière : toutes les sources qui portent son inventaire (flux central et bureaux)470    var sources: [String] = []471    var platformKind: String?472    var rating: Double?473    var reviews: Int?474    var brokersList: [Broker]475    /// repli v1 : ses propriétés se listent par la source (le filtre `agency` n'existe pas)476    var listsBySource = false477478    init(kind: Kind, name: String, activeListings: Int, offices: Int? = nil, source: String? = nil) {479        self.kind = kind; id = name; self.name = name; self.activeListings = activeListings; self.offices = offices480        self.source = source; regions = []; cities = []; brokersList = []481        listsBySource = true482    }483484    init(from decoder: Decoder) throws {485        let c = try decoder.container(keyedBy: AnyKey.self)486        guard let n = c.text(AnyKey("name")) else {487            throw DecodingError.dataCorrupted(.init(codingPath: decoder.codingPath, debugDescription: "agence sans nom"))488        }489        name = Fmt.titleCase(n)490        id = c.text(AnyKey("id")) ?? n491        franchise = c.text(AnyKey("franchise"))492        offices = c.int(AnyKey("agencies"))493        brokers = c.int(AnyKey("brokers")).flatMap { $0 > 0 ? $0 : nil }494        regions = c.strings(AnyKey("regions"))495        activeListings = c.int(AnyKey("active_listings")) ?? 0496        priceMedian = c.dbl(AnyKey("price_median")).flatMap { $0 > 0 ? $0 : nil }497        cities = c.strings(AnyKey("cities")).filter(Fmt.isPlausibleCity)498        citiesTotal = c.int(AnyKey("cities_total"))499        url = c.text(AnyKey("url"))500        source = c.text(AnyKey("source"))501        matchedBy = c.text(AnyKey("matched_by"))502        platformKind = c.text(AnyKey("kind"))503        rating = c.dbl(AnyKey("rating")).flatMap { $0 > 0 ? $0 : nil }504        reviews = c.int(AnyKey("reviews")).flatMap { $0 > 0 ? $0 : nil }505        brokersList = c.list(AnyKey("brokers_list")).filter { !$0.name.isEmpty }506    }507508    /// Paramètres de recherche qui listent ses propriétés. Le filtre `agency` du service est une égalité sur le509    /// bureau inscripteur : une bannière se liste donc par l'ensemble de ses sources, une plateforme par la510    /// sienne, une agence par sa source dédiée ou, à défaut, par son nom.511    var filters: SearchFilters {512        var f = SearchFilters()513        switch kind {514        case .platform:515            f.source = source ?? id516        case .franchise:517            if !sources.isEmpty { f.source = sources.joined(separator: ",") } else if let source { f.source = source } else { f.agency = name }518        case .agency:519            if listsBySource || matchedBy == "source", let source { f.source = source } else { f.agency = name }520        }521        return f522    }523}524525struct AgencyDirectory: Decodable, Sendable {526    struct Region: Decodable, Sendable, Identifiable, Hashable {527        var region: String528        var agencies: Int529        var id: String { region }530        init(from decoder: Decoder) throws {531            let c = try decoder.container(keyedBy: AnyKey.self)532            region = c.str(AnyKey("region")) ?? ""533            agencies = c.int(AnyKey("agencies")) ?? c.int(AnyKey("n")) ?? 0534        }535    }536    var total: Int537    var withListings: Int?538    var brokersTotal: Int?539    var listingsTotal: Int540    var regions: [Region]541    var franchises: [AgencyEntry]542    var platforms: [AgencyEntry]543    var agencies: [AgencyEntry]544545    init(from decoder: Decoder) throws {546        let c = try decoder.container(keyedBy: AnyKey.self)547        func entries(_ key: String, _ kind: AgencyEntry.Kind) -> [AgencyEntry] {548            c.list(AnyKey(key), AgencyEntry.self).map { e in549                var e = e550                e.kind = kind551                // une plateforme est identifiée par sa source552                if kind == .platform, e.source == nil { e.source = e.id }553                return e554            }555        }556        franchises = entries("franchises", .franchise)557        platforms = entries("platforms", .platform)558        agencies = entries("agencies", .agency)559        total = c.int(AnyKey("total")) ?? agencies.count560        withListings = c.int(AnyKey("with_listings"))561        brokersTotal = c.int(AnyKey("brokers_total"))562        listingsTotal = c.int(AnyKey("listings_total")) ?? 0563        regions = c.list(AnyKey("regions")).filter { !$0.region.isEmpty }564    }565566    /// Repli v1 : l'arbre bannière → bureaux, sans le registre ni les plateformes.567    init(tree: AgenciesTree) {568        franchises = tree.franchises.map { f in569            // source principale : celle qui porte le plus de propriétés de la bannière570            var counts: [String: Int] = [:]571            for o in f.offices { for src in o.sources { counts[src, default: 0] += o.count } }572            return AgencyEntry(kind: f.offices.count > 1 ? .franchise : .platform, name: f.name, activeListings: f.total,573                               offices: f.offices.count, source: counts.max { $0.value < $1.value }?.key)574        }575        platforms = []; agencies = []; regions = []576        total = franchises.count577        listingsTotal = tree.totalListings578    }579580    var all: [AgencyEntry] { franchises + platforms + agencies }581582    /// Rattache à chaque bannière ses sources, d'après l'arbre bannière → bureaux et les agences du registre.583    mutating func attachSources(from tree: AgenciesTree?) {584        for i in franchises.indices {585            let key = Fmt.slug(franchises[i].name)586            var found = Set(tree?.franchises.first { Fmt.slug($0.name) == key }?.sources ?? [])587            for a in agencies where Fmt.slug(a.franchise ?? "") == key { if let s = a.source { found.insert(s) } }588            franchises[i].sources = found.sorted()589        }590    }591}592593/// Page d'une ville (v2, `/api/seo/ville/{slug}`) : chiffres, types, quartiers, villes voisines.594struct CityPage: Decodable, Sendable {595    struct TypeRow: Decodable, Sendable, Identifiable, Hashable {596        var propertyType: String597        var n: Int598        var medianPrice: Double?599        var id: String { propertyType }600        init(from decoder: Decoder) throws {601            let c = try decoder.container(keyedBy: AnyKey.self)602            propertyType = c.str(AnyKey("property_type")) ?? ""603            n = c.int(AnyKey("n")) ?? 0604            medianPrice = c.dbl(AnyKey("median_price"))605        }606    }607    var city: String608    /// valeurs exactes du champ `city` à passer à la recherche (variantes d'écriture fusionnées)609    var cities: [String]610    var n: Int611    var medianPrice: Double?612    var minPrice: Double?613    var maxPrice: Double?614    var types: [TypeRow]615    var sectors: [FacetValue]616    var neighbors: [CityEntry]617618    init(from decoder: Decoder) throws {619        let c = try decoder.container(keyedBy: AnyKey.self)620        city = c.text(AnyKey("city")) ?? ""621        cities = c.strings(AnyKey("cities"))622        n = c.int(AnyKey("n")) ?? 0623        medianPrice = c.dbl(AnyKey("median_price"))624        minPrice = c.dbl(AnyKey("min_price"))625        maxPrice = c.dbl(AnyKey("max_price"))626        types = c.list(AnyKey("types")).filter { $0.n > 0 && !PropertyKind.normalize($0.propertyType).isEmpty }627        sectors = c.list(AnyKey("sectors"))628        neighbors = c.list(AnyKey("neighbors"), CityEntry.self).filter { Fmt.isPlausibleCity($0.name) && $0.count > 0 }629    }630}631632struct RegionCount: Decodable, Sendable, Identifiable, Hashable {633    var region: String634    var n: Int635    var id: String { region }636    init(from decoder: Decoder) throws {637        let c = try decoder.container(keyedBy: AnyKey.self)638        region = c.str(AnyKey("region")) ?? ""639        n = c.int(AnyKey("n")) ?? 0640    }641}642643/// Agence de courtage inscrite au registre de l'OACIQ.644struct Banniere: Decodable, Sendable, Identifiable, Hashable {645    struct Broker: Decodable, Sendable, Identifiable, Hashable {646        var name: String647        var city: String?648        var region: String?649        var id: String { "\(name)|\(city ?? "")" }650        init(from decoder: Decoder) throws {651            let c = try decoder.container(keyedBy: AnyKey.self)652            name = c.text(AnyKey("name")) ?? ""653            city = c.text(AnyKey("city"))654            region = c.text(AnyKey("region"))655        }656    }657    var id: String658    var name: String659    var regions: [String]660    var brokersN: Int661    /// identifiant de la source Immo-Ka qui couvre ses inscriptions, s'il y en a une662    var coveredBy: String?663    var site: String?664    var brokers: [Broker]665666    init(from decoder: Decoder) throws {667        let c = try decoder.container(keyedBy: AnyKey.self)668        guard let i = c.text(AnyKey("id")) else {669            throw DecodingError.dataCorrupted(.init(codingPath: decoder.codingPath, debugDescription: "agence sans id"))670        }671        id = i672        name = Fmt.titleCase(c.text(AnyKey("name")) ?? i)673        regions = c.strings(AnyKey("regions"))674        brokersN = c.int(AnyKey("brokers_n")) ?? 0675        coveredBy = c.text(AnyKey("covered_by"))676        site = c.text(AnyKey("site"))677        brokers = c.list(AnyKey("brokers")).filter { !$0.name.isEmpty }678    }679}680681struct BannieresDirectory: Decodable, Sendable {682    var total: Int683    var brokersTotal: Int684    var regions: [RegionCount]685    var bannieres: [Banniere]686    init(from decoder: Decoder) throws {687        let c = try decoder.container(keyedBy: AnyKey.self)688        bannieres = c.list(AnyKey("bannieres"))689        // `total` compte aussi l'entrée « Courtiers à leur compte » : le nombre d'agences est `agencies_total`690        total = c.int(AnyKey("agencies_total")) ?? c.int(AnyKey("total")) ?? bannieres.count691        brokersTotal = c.int(AnyKey("brokers_total")) ?? bannieres.reduce(0) { $0 + $1.brokersN }692        regions = c.list(AnyKey("regions")).filter { !$0.region.isEmpty }693    }694}695696/// Professionnel d'un annuaire (inspecteur en bâtiment, déménageur).697struct ProEntry: Decodable, Sendable, Identifiable, Hashable {698    var id: String699    var name: String700    var city: String701    var region: String702    var address: String?703    var phone: String?704    var website: String?705    var rating: Double?706    var reviews: Int?707    var lat: Double?708    var lng: Double?709710    init(from decoder: Decoder) throws {711        let c = try decoder.container(keyedBy: AnyKey.self)712        guard let n = c.text(AnyKey("name")) else {713            throw DecodingError.dataCorrupted(.init(codingPath: decoder.codingPath, debugDescription: "professionnel sans nom"))714        }715        name = n716        id = c.text(AnyKey("id")) ?? n717        city = c.text(AnyKey("city")) ?? ""718        region = c.text(AnyKey("region")) ?? ""719        address = c.text(AnyKey("address"))720        phone = c.text(AnyKey("phone"))721        website = c.text(AnyKey("website"))722        rating = c.dbl(AnyKey("rating")).flatMap { $0 > 0 ? $0 : nil }723        reviews = c.int(AnyKey("reviews")).flatMap { $0 > 0 ? $0 : nil }724        lat = c.dbl(AnyKey("lat")); lng = c.dbl(AnyKey("lng"))725    }726727    var phoneURL: URL? {728        guard let p = phone else { return nil }729        let d = p.filter(\.isNumber)730        return d.count >= 10 ? URL(string: "tel://\(d)") : nil731    }732}733734struct ProDirectory: Decodable, Sendable {735    var total: Int736    var regions: [RegionCount]737    var entries: [ProEntry]738    init(from decoder: Decoder) throws {739        let c = try decoder.container(keyedBy: AnyKey.self)740        // la v1 nomme la liste « movers » dans les deux annuaires741        var e: [ProEntry] = c.list(AnyKey("movers"))742        if e.isEmpty { e = c.list(AnyKey("inspecteurs")) }743        if e.isEmpty { e = c.list(AnyKey("items")) }744        entries = e745        total = c.int(AnyKey("total")) ?? e.count746        regions = c.list(AnyKey("regions")).filter { !$0.region.isEmpty }747    }748}749750// MARK: - Marché751752struct GlobalStats: Decodable, Sendable {753    struct Ecart: Decodable, Sendable, Identifiable, Hashable {754        var banniere: String755        var n: Int756        var median: Double757        var p25: Double?758        var p75: Double?759        var pctSur: Double?760        var pctJuste: Double?761        var pctSous: Double?762        var id: String { banniere }763        init(from decoder: Decoder) throws {764            let c = try decoder.container(keyedBy: AnyKey.self)765            banniere = c.str(AnyKey("banniere")) ?? ""766            n = c.int(AnyKey("n")) ?? 0767            median = c.dbl(AnyKey("median_delta_pct")) ?? 0768            p25 = c.dbl(AnyKey("p25")); p75 = c.dbl(AnyKey("p75"))769            pctSur = c.dbl(AnyKey("pct_sur10")); pctJuste = c.dbl(AnyKey("pct_juste")); pctSous = c.dbl(AnyKey("pct_sous5"))770        }771    }772    var total: Int773    var sources: Int?774    var cities: Int?775    var avgPrice: Double?776    var ensemble: Ecart?777    var bannieres: [Ecart]778779    init(from decoder: Decoder) throws {780        let c = try decoder.container(keyedBy: AnyKey.self)781        total = c.int(AnyKey("total")) ?? 0782        sources = c.int(AnyKey("sources"))783        cities = c.int(AnyKey("cities"))784        avgPrice = c.dbl(AnyKey("avg_price"))785        if let v = try? c.nestedContainer(keyedBy: AnyKey.self, forKey: AnyKey("vraiprix")) {786            ensemble = v.opt(AnyKey("ensemble"))787            bannieres = v.list(AnyKey("bannieres"))788        } else {789            bannieres = []790        }791    }792}793794/// Parts des verdicts du vrai prix parmi les propriétés évaluées (nombres d'inscriptions).795struct VerdictShares: Sendable, Equatable {796    var sous: Double797    var juste: Double798    var sur: Double799    /// écart médian entre prix demandé et valeur estimée, en pourcentage800    var median: Double?801    var n: Double { sous + juste + sur }802}803804/// Tableau de bord du marché : indicateurs, séries, répartitions, tableaux.805struct Dashboard: Decodable, Sendable {806    struct Point: Decodable, Sendable, Identifiable, Hashable {807        var t: String808        var v: Double809        var id: String { t }810        var date: Date? { Fmt.isoDay(t) }811        init(from decoder: Decoder) throws {812            let c = try decoder.container(keyedBy: AnyKey.self)813            t = c.str(AnyKey("t")) ?? ""814            guard let x = c.dbl(AnyKey("v")) else {815                throw DecodingError.dataCorrupted(.init(codingPath: decoder.codingPath, debugDescription: "point sans valeur"))816            }817            v = x818        }819    }820    struct KPI: Decodable, Sendable, Identifiable, Hashable {821        var id: String822        var label: String823        var value: Double824        var unit: String825        var deltaPct: Double?826        var spark: [Point]827        init(from decoder: Decoder) throws {828            let c = try decoder.container(keyedBy: AnyKey.self)829            id = c.str(AnyKey("id")) ?? UUID().uuidString830            label = c.str(AnyKey("label")) ?? ""831            guard let v = c.dbl(AnyKey("value")) else {832                throw DecodingError.dataCorrupted(.init(codingPath: decoder.codingPath, debugDescription: "indicateur sans valeur"))833            }834            value = v835            unit = c.str(AnyKey("unit")) ?? ""836            deltaPct = c.dbl(AnyKey("delta_pct"))837            spark = c.list(AnyKey("spark"))838        }839    }840    struct Series: Decodable, Sendable, Identifiable, Hashable {841        var id: String842        var title: String843        var unit: String844        var kind: String845        var points: [Point]846        init(from decoder: Decoder) throws {847            let c = try decoder.container(keyedBy: AnyKey.self)848            id = c.str(AnyKey("id")) ?? UUID().uuidString849            title = c.str(AnyKey("title")) ?? c.str(AnyKey("label")) ?? ""850            unit = c.str(AnyKey("unit")) ?? ""851            kind = c.str(AnyKey("kind")) ?? "line"852            points = c.list(AnyKey("points"))853        }854    }855    struct Item: Decodable, Sendable, Identifiable, Hashable {856        var label: String857        var value: Double858        var id: String { label }859        init(from decoder: Decoder) throws {860            let c = try decoder.container(keyedBy: AnyKey.self)861            label = c.str(AnyKey("label")) ?? ""862            value = c.dbl(AnyKey("value")) ?? 0863        }864    }865    struct Breakdown: Decodable, Sendable, Identifiable, Hashable {866        var id: String867        var title: String868        var items: [Item]869        init(from decoder: Decoder) throws {870            let c = try decoder.container(keyedBy: AnyKey.self)871            id = c.str(AnyKey("id")) ?? UUID().uuidString872            title = c.str(AnyKey("title")) ?? ""873            var i: [Item] = c.list(AnyKey("items"))874            if i.isEmpty { i = c.list(AnyKey("bins")) }875            items = i876        }877    }878    struct MultiSeries: Decodable, Sendable, Identifiable, Hashable {879        var id: String880        var title: String881        var unit: String882        var series: [Series]883        init(from decoder: Decoder) throws {884            let c = try decoder.container(keyedBy: AnyKey.self)885            id = c.str(AnyKey("id")) ?? UUID().uuidString886            title = c.str(AnyKey("title")) ?? ""887            unit = c.str(AnyKey("unit")) ?? ""888            series = c.list(AnyKey("series"))889        }890    }891    struct Table: Decodable, Sendable, Identifiable, Hashable {892        var id: String893        var title: String894        var columns: [String]895        var rows: [[String]]896        init(from decoder: Decoder) throws {897            let c = try decoder.container(keyedBy: AnyKey.self)898            id = c.str(AnyKey("id")) ?? UUID().uuidString899            title = c.str(AnyKey("title")) ?? ""900            columns = c.strings(AnyKey("columns"))901            // cellules mixtes (texte et nombres) ramenées à du texte902            rows = ((try? c.decode([[Cell]].self, forKey: AnyKey("rows"))) ?? []).map { $0.map(\.text) }903        }904        private struct Cell: Decodable {905            var text: String906            init(from decoder: Decoder) throws {907                let c = try decoder.singleValueContainer()908                if let s = try? c.decode(String.self) { text = s }909                else if let i = try? c.decode(Int.self) { text = Fmt.int(i) }910                else if let d = try? c.decode(Double.self) { text = Fmt.decimal(d) }911                else { text = "" }912            }913        }914    }915916    var updated: String?917    var periodLabel: String?918    var kpis: [KPI]919    var series: [Series]920    var breakdowns: [Breakdown]921    var distributions: [Breakdown]922    var multiseries: [MultiSeries]923    var tables: [Table]924    var regions: [Item]925926    init(from decoder: Decoder) throws {927        let c = try decoder.container(keyedBy: AnyKey.self)928        updated = c.text(AnyKey("updated"))929        if let p = try? c.nestedContainer(keyedBy: AnyKey.self, forKey: AnyKey("period")) { periodLabel = p.text(AnyKey("label")) }930        kpis = c.list(AnyKey("kpis"))931        series = c.list(AnyKey("series"))932        breakdowns = c.list(AnyKey("breakdowns"))933        distributions = c.list(AnyKey("distributions"))934        multiseries = c.list(AnyKey("multiseries"))935        tables = c.list(AnyKey("tables"))936        if let g = try? c.nestedContainer(keyedBy: AnyKey.self, forKey: AnyKey("geo")) { regions = g.list(AnyKey("items")) } else { regions = [] }937    }938939    func kpi(_ id: String) -> KPI? { kpis.first { $0.id == id } }940    func serie(_ id: String) -> Series? { series.first { $0.id == id } }941    func breakdown(_ id: String) -> Breakdown? { breakdowns.first { $0.id == id } }942    func distribution(_ id: String) -> Breakdown? { distributions.first { $0.id == id } }943    func table(_ id: String) -> Table? { tables.first { $0.id == id } }944}945946/// Ville de l'index : nom, inscriptions en ligne, prix médian (du tableau « top_villes » ou des pages par ville).947struct CityEntry: Sendable, Identifiable, Hashable, Decodable {948    var name: String949    var count: Int950    var medianPrice: Double?951    var slug: String { Fmt.slug(name) }952    var id: String { name }953954    init(name: String, count: Int, medianPrice: Double?) {955        self.name = name; self.count = count; self.medianPrice = medianPrice956    }957958    init(from decoder: Decoder) throws {959        let c = try decoder.container(keyedBy: AnyKey.self)960        guard let n = c.text(AnyKey("name")) ?? c.text(AnyKey("city")) ?? c.text(AnyKey("ville")) else {961            throw DecodingError.dataCorrupted(.init(codingPath: decoder.codingPath, debugDescription: "ville sans nom"))962        }963        name = n964        count = c.int(AnyKey("n")) ?? c.int(AnyKey("count")) ?? c.int(AnyKey("actives")) ?? 0965        medianPrice = c.dbl(AnyKey("median_price")) ?? c.dbl(AnyKey("prix_median"))966    }967}968969struct CitiesResponse: Decodable, Sendable {970    var cities: [CityEntry]971    init(from decoder: Decoder) throws {972        let c = try decoder.container(keyedBy: AnyKey.self)973        var l: [CityEntry] = c.list(AnyKey("villes"))974        if l.isEmpty { l = c.list(AnyKey("cities")) }975        cities = l976    }977}978979// MARK: - Taux hypothécaires980981struct MortgageRate: Decodable, Sendable, Identifiable, Hashable {982    var id: String983    var provider: String984    var institution: String985    var productName: String986    var rateType: String987    var termMonths: Int988    var kind: String989    var rate: Double990    var insuredStatus: String?991    var sourceURL: String?992    var lastChecked: Double?993    var validFrom: Double?994    var stale: Bool995    var medianRate: Double?996    var institutionsCount: Int?997998    init(from decoder: Decoder) throws {999        let c = try decoder.container(keyedBy: AnyKey.self)1000        guard let r = c.dbl(AnyKey("rate")), r > 0, r < 30 else {1001            throw DecodingError.dataCorrupted(.init(codingPath: decoder.codingPath, debugDescription: "taux absent"))1002        }1003        rate = r1004        provider = c.str(AnyKey("provider")) ?? ""1005        institution = c.str(AnyKey("institution")) ?? provider1006        productName = c.str(AnyKey("product_name")) ?? ""1007        rateType = c.str(AnyKey("rate_type")) ?? "fixed"1008        termMonths = c.int(AnyKey("term_months")) ?? 601009        kind = c.str(AnyKey("kind")) ?? ""1010        insuredStatus = c.text(AnyKey("insured_status"))1011        sourceURL = c.text(AnyKey("source_url"))1012        lastChecked = c.dbl(AnyKey("last_checked"))1013        validFrom = c.dbl(AnyKey("valid_from"))1014        stale = c.bool(AnyKey("stale")) ?? false1015        medianRate = c.dbl(AnyKey("median_rate"))1016        institutionsCount = c.int(AnyKey("institutions_count"))1017        id = c.str(AnyKey("id")) ?? "\(provider)|\(productName)|\(termMonths)|\(validFrom ?? 0)"1018    }10191020    var isFixed: Bool { rateType == "fixed" }1021    var kindLabel: String {1022        switch kind {1023        case "special": "Taux promotionnel"1024        case "posted": "Taux affiché"1025        case "prime": "Taux préférentiel"1026        default: kind.isEmpty ? "" : kind.capitalized1027        }1028    }1029}10301031struct MortgageBest: Decodable, Sendable {1032    var best: MortgageRate1033    var perInstitution: [MortgageRate]1034    init(from decoder: Decoder) throws {1035        best = try MortgageRate(from: decoder)1036        let c = try decoder.container(keyedBy: AnyKey.self)1037        perInstitution = c.list(AnyKey("per_institution")).sorted { $0.rate < $1.rate }1038    }1039}10401041struct MortgageRates: Decodable, Sendable {1042    var rates: [MortgageRate]1043    init(from decoder: Decoder) throws {1044        let c = try decoder.container(keyedBy: AnyKey.self)1045        var r: [MortgageRate] = c.list(AnyKey("rates"))1046        if r.isEmpty { r = c.list(AnyKey("history")) }1047        rates = r1048    }1049}10501051/// Synthèse du marché des taux : meilleur taux, médiane et variations par produit, taux préférentiels.1052struct MortgageIntelligence: Decodable, Sendable {1053    struct Product: Decodable, Sendable, Identifiable, Hashable {1054        var rateType: String1055        var termMonths: Int1056        var best: Double1057        var bestInstitution: String1058        var median: Double?1059        var institutionsCount: Int?1060        var var7d: Double?1061        var var30d: Double?1062        var var90d: Double?1063        var lowest6m: Double?1064        var id: String { "\(rateType)-\(termMonths)" }1065        init(from decoder: Decoder) throws {1066            let c = try decoder.container(keyedBy: AnyKey.self)1067            guard let b = c.dbl(AnyKey("best")), b > 0 else {1068                throw DecodingError.dataCorrupted(.init(codingPath: decoder.codingPath, debugDescription: "produit sans taux"))1069            }1070            best = b1071            rateType = c.str(AnyKey("rate_type")) ?? "fixed"1072            termMonths = c.int(AnyKey("term_months")) ?? 601073            bestInstitution = c.str(AnyKey("best_institution")) ?? ""1074            median = c.dbl(AnyKey("median"))1075            institutionsCount = c.int(AnyKey("institutions_count"))1076            var7d = c.dbl(AnyKey("var_7d")); var30d = c.dbl(AnyKey("var_30d")); var90d = c.dbl(AnyKey("var_90d"))1077            lowest6m = c.dbl(AnyKey("lowest_6m"))1078        }1079        var isFixed: Bool { rateType == "fixed" }1080        var label: String { "\(isFixed ? "Fixe" : "Variable") \(Fmt.term(termMonths))" }1081    }1082    struct Prime: Decodable, Sendable, Identifiable, Hashable {1083        var institution: String1084        var rate: Double1085        var id: String { institution }1086        init(from decoder: Decoder) throws {1087            let c = try decoder.container(keyedBy: AnyKey.self)1088            institution = c.str(AnyKey("institution")) ?? ""1089            rate = c.dbl(AnyKey("rate")) ?? 01090        }1091    }1092    var products: [Product]1093    var primeRates: [Prime]1094    init(from decoder: Decoder) throws {1095        let c = try decoder.container(keyedBy: AnyKey.self)1096        products = c.list(AnyKey("products")).sorted { ($0.isFixed ? 0 : 1, $0.termMonths) < ($1.isFixed ? 0 : 1, $1.termMonths) }1097        primeRates = c.list(AnyKey("prime_rates")).filter { $0.rate > 0 }1098    }1099    func product(fixed: Bool, term: Int) -> Product? { products.first { $0.isFixed == fixed && $0.termMonths == term } }1100}1101
Files main
Menu

Theme