SPB Git

Repository Public

EndpointsV3.swift 10.7 KB 230 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : Immo-Ka iOS9// File             : ImmoKa/Core/API/EndpointsV3.swift10// Description      : points d'accès typés de l'API `/api/v3` : recherche à11//                    curseur, carte par emprise, phrase libre, fiche, prix de12//                    vente attendu, comparables, coût de possession, marché,13//                    quartiers, courtiers, rapports.14// Module           : ImmoKa15// Repository       : https://git.spboucher.ai/immo-ka-ios-v316// Project Website  : https://www.immo-ka.com17// Created          : 2026-11-2818// Last Modified    : 2026-11-3019//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 Foundation9394/// Hypothèses du coût de possession saisies par l'utilisateur (les autres restent celles du service).95struct OwnershipAssumptions: Sendable, Hashable, Codable {96    /// mise de fonds en % du prix97    var downPct: Double?98    /// taux annuel en %99    var rate: Double?100    var amortization: Int?101102    var query: [String: String?] {103        ["down_pct": downPct.map { String($0) }, "rate": rate.map { String($0) }, "amortization": amortization.map(String.init)]104    }105    var isDefault: Bool { downPct == nil && rate == nil && amortization == nil }106}107108extension APIClient {109    func encV3(_ uid: String) -> String {110        uid.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed.subtracting(CharacterSet(charactersIn: "/?#"))) ?? uid111    }112113    // MARK: Recherche114115    /// Page de résultats de la v3. `cursor` : curseur opaque rendu par la page précédente.116    func searchV3(_ filters: SearchFilters, sort: SearchSort, bbox: String? = nil, cursor: String? = nil,117                  limit: Int = 24) async throws -> V3SearchResponse {118        var q = filters.queryV3119        q["sort"] = sort.v3120        q["bbox"] = bbox121        q["cursor"] = cursor122        q["limit"] = String(limit)123        return try await getV3("search", query: q)124    }125126    /// Points ou regroupements de la carte pour une emprise et un zoom.127    func mapV3(_ filters: SearchFilters, bbox: String?, zoom: Double) async throws -> V3MapResponse {128        var q = filters.queryV3129        q["bbox"] = bbox130        q["zoom"] = String(format: "%.1f", min(22, max(0, zoom)))131        return try await getV3("search/map", query: q)132    }133134    /// Ce que le service comprend d'une phrase (« maison 3 chambres à Gatineau sous 500 000 »).135    func parse(_ sentence: String) async throws -> V3Parse {136        try await getV3("search/parse", query: ["nl": String(sentence.prefix(400))])137    }138139    func suggestPlaces(_ text: String) async throws -> [PlaceSuggestion] {140        let r: ItemsEnvelope<PlaceSuggestion> = try await getV3("geo/suggest", query: ["q": String(text.prefix(80)), "limit": "8"])141        return r.items.filter { !$0.name.isEmpty }142    }143144    // MARK: Fiche145146    func listingV3(_ uid: String) async throws -> Listing { try await getV3("listings/\(encV3(uid))") }147148    /// Fiche complète. En v3 : la fiche v3 fait foi (statut, prix de vente attendu, 410 des inscriptions retirées) ;149    /// la fiche v2, si elle répond, la complète de ce que la v3 ne sert pas (quartier, points d'intérêt, courtier).150    func fullListing(_ uid: String) async throws -> Listing {151        guard await isV3() else { return try await listing(uid) }152        do {153            async let rich = try? listing(uid)154            let v3 = try await listingV3(uid)155            guard let r = await rich else { return v3 }156            return r.merging(v3: v3)157        } catch APIError.regrouped(let kept) where kept != uid {158            // inscription regroupée avec une autre (page d'un courtier, vieux lien) : la fiche gardée, une seule fois159            async let rich = try? listing(kept)160            let v3 = try await listingV3(kept)161            guard let r = await rich else { return v3 }162            return r.merging(v3: v3)163        }164    }165166    func valuation(_ uid: String) async throws -> Valuation { try await getV3("valuation/\(encV3(uid))") }167    func comparablesV3(_ uid: String, k: Int = 8) async throws -> Comparables {168        try await getV3("comparables/\(encV3(uid))", query: ["k": String(k)])169    }170    func ownership(_ uid: String, assumptions: OwnershipAssumptions = .init()) async throws -> Ownership {171        try await getV3("ownership/\(encV3(uid))", query: assumptions.query)172    }173    func links(_ uid: String) async throws -> ListingLinks { try await getV3("listings-links/\(encV3(uid))") }174175    /// Rapport PDF d'une propriété (ouvert dans Safari : route lourde, limitée à 20 par minute).176    func reportURL(_ uid: String, assumptions: OwnershipAssumptions = .init()) async -> URL? {177        guard await isV3() else { return await pdfURL(uid) }178        return await url("api/v3/reports/listing/\(encV3(uid))", query: assumptions.query)179    }180    func comparisonReportURL(_ uids: [String]) async -> URL? {181        guard await isV3(), uids.count >= 2 else { return nil }182        return await url("api/v3/reports/comparison", query: ["uids": uids.prefix(8).joined(separator: ",")])183    }184    func marketReportURL(place: String?, kind: String?) async -> URL? {185        guard await isV3() else { return nil }186        return await url("api/v3/reports/market", query: ["place": place, "kind": kind])187    }188189    // MARK: Marché190191    func market(place: String? = nil, kind: String? = nil, family: String? = nil) async throws -> MarketPortrait {192        try await getV3("market", query: ["place": place, "kind": kind, "family": family])193    }194    /// Série d'un indicateur d'inscriptions (`price_median`, `n_active`, `n_new`…), par semaine.195    func marketSeries(indicator: String, place: String? = nil, kind: String? = nil, family: String? = nil) async throws -> MarketSeries {196        try await getV3("market/series", query: ["indicator": indicator, "place": place, "kind": kind, "family": family, "freq": "W"])197    }198    /// Ventes réelles par trimestre.199    func marketSales(place: String? = nil, kind: String? = nil, family: String? = nil) async throws -> MarketSeries {200        try await getV3("market/sales", query: ["place": place, "kind": kind, "family": family, "freq": "Q"])201    }202    /// Indice Immo-Ka des prix de vente (base 100 au premier trimestre de 2021), avec son intervalle à 95 %.203    func priceIndex(place: String? = nil, kind: String? = nil, family: String = "unifamiliale") async throws -> MarketSeries {204        try await getV3("indices", query: ["place": place, "kind": kind, "family": family])205    }206207    // MARK: Quartiers208209    /// Lieux ayant un portrait : les municipalités, ou les arrondissements, quartiers et secteurs d'une ville.210    func neighborhoods(city: String? = nil, limit: Int = 200) async throws -> [NeighborhoodEntry] {211        let r: ItemsEnvelope<NeighborhoodEntry> = try await getV3("neighborhoods", query: ["city": city, "limit": String(limit)])212        return r.items.filter { !$0.slug.isEmpty && !$0.name.isEmpty }213    }214    func neighborhood(slug: String, city: String? = nil) async throws -> NeighborhoodPortrait {215        try await getV3("neighborhoods/\(encV3(slug))", query: ["city": city])216    }217218    // MARK: Courtiers219220    /// Recherche de courtiers par partie du nom (deux caractères au moins) ou par agence.221    func brokers(q: String? = nil, agency: String? = nil, offset: Int = 0) async throws -> ItemsEnvelope<BrokerEntry> {222        try await getV3("brokers", query: ["q": q, "agency": agency, "limit": "30", "offset": offset > 0 ? String(offset) : nil])223    }224225    /// Un courtier de l'annuaire et ses propriétés à vendre (`/api/v3/brokers/{id}`).226    func broker(_ id: String) async throws -> BrokerDetail {227        try await getV3("brokers/\(encV3(id))")228    }229}230
Files main
Menu

Theme