Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : Immo-Ka iOS9// File : ImmoKa/Core/API/Endpoints.swift10// Description : points d'accès de l'API, typés. La recherche a deux11// chemins : la recherche unifiée de la v2 (`/api/search`)12// et, en repli, les routes de lecture de la v113// (`/api/listings`, `.geojson`).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 Foundation9394enum SearchSort: String, CaseIterable, Sendable, Codable, Identifiable {95 case pertinence, recent, prix, prixDesc = "prix_desc", deal, baisse, pi2, superficie, terrain96 var id: String { rawValue }97 var label: String {98 switch self {99 case .pertinence: "Pertinence"100 case .recent: "Plus récentes"101 case .prix: "Prix croissant"102 case .prixDesc: "Prix décroissant"103 case .deal: "Écart au prix attendu"104 case .baisse: "Baisses de prix"105 case .pi2: "Prix au pied carré"106 case .superficie: "Plus grandes"107 case .terrain: "Plus grands terrains"108 }109 }110 /// Paramètre `sort` de `/api/v3/search`.111 var v3: String { self == .deal ? "ecart" : rawValue }112 /// Paramètre `sort` de `/api/search` (v2), qui ne connaît que cinq tris.113 var v2: String {114 switch self {115 case .pertinence, .baisse: "recent"116 case .pi2: "prix"117 case .terrain: "superficie"118 default: rawValue119 }120 }121 /// Paramètre `sort` de `/api/listings` (v1).122 var v1: String {123 switch self {124 case .prix, .pi2: "price_asc"125 case .prixDesc: "price_desc"126 default: "recent"127 }128 }129}130131/// Points de carte correspondant à une recherche.132struct MapPointsResult: Sendable {133 var points: [MapPoint]134 var total: Int135 var unpositioned: Int136}137138extension APIClient {139 private func enc(_ uid: String) -> String {140 // les uid contiennent « : » et parfois « / » : chaque segment est encodé141 uid.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed.subtracting(CharacterSet(charactersIn: "/?#"))) ?? uid142 }143144 func facets(city: String? = nil) async throws -> Facets { try await get("api/facets", query: ["city": city]) }145 func stats() async throws -> GlobalStats { try await get("api/stats") }146147 /// Répartition des verdicts du vrai prix sur le marché (mêmes seuils que les fiches) et écart médian.148 func verdictShares() async throws -> VerdictShares {149 if await isV3() {150 // v3 : positions du prix demandé comptées par le service, écart médian du portrait de marché151 struct Positions: Decodable, Sendable {152 var sous = 0.0, dans = 0.0, sur = 0.0153 init(from decoder: Decoder) throws {154 let c = try decoder.container(keyedBy: AnyKey.self)155 guard let p = try? c.nestedContainer(keyedBy: AnyKey.self, forKey: AnyKey("positions")) else { return }156 sous = p.dbl(AnyKey("sous")) ?? 0; dans = p.dbl(AnyKey("dans")) ?? 0; sur = p.dbl(AnyKey("sur")) ?? 0157 }158 }159 async let m = try? market()160 let p: Positions = try await getV3("search/facets")161 let shares = VerdictShares(sous: p.sous, juste: p.dans, sur: p.sur, median: await m?.askGapMedian)162 guard shares.n > 0 else { throw APIError.notFound }163 return shares164 }165 async let d = dashboard()166 async let s = try? stats()167 let items = try await d.breakdown("fairvalue")?.items ?? []168 func value(_ word: String) -> Double { items.first { $0.label.lowercased().contains(word) }?.value ?? 0 }169 let shares = VerdictShares(sous: value("sous"), juste: value("dans"), sur: value("dessus"), median: await s?.ensemble?.median)170 guard shares.n > 0 else { throw APIError.notFound }171 return shares172 }173 func dashboard(period: String = "30j") async throws -> Dashboard { try await get("api/stats/dashboard", query: ["period": period]) }174 func sources() async throws -> SourcesResponse { try await get("api/sources") }175176 /// Noms d'affichage des sources (« remax_quebec » → « RE/MAX Québec »).177 func sourceNames() async throws -> [String: String] {178 if await isV2(), let names: [String: String] = try? await get("api/sources/names"), !names.isEmpty { return names }179 let all = try await sources().sources180 return Dictionary(all.map { ($0.id, $0.name) }, uniquingKeysWith: { a, _ in a })181 }182183 // MARK: Recherche184185 /// Paramètres de la recherche v2 : le type est élargi aux libellés non canoniques des courtiers, et la ville186 /// à ses variantes d'écriture (le filtre `city` du service est exact).187 private func queryV2(_ filters: SearchFilters) async -> [String: String?] {188 var q = filters.query189 if let t = filters.propertyType { q["property_type"] = PropertyKind.queryValue(t) }190 if let city = filters.city {191 if let known = cityVariants[city] { q["city"] = known }192 else if let page = await cityPage(city), !page.cities.isEmpty {193 let v = page.cities.joined(separator: ",")194 cityVariants[city] = v195 q["city"] = v196 } else {197 cityVariants[city] = city198 }199 }200 return q201 }202203 /// Page de résultats. `bbox` restreint à la zone visible de la carte.204 func search(_ filters: SearchFilters, sort: SearchSort = .recent, bbox: String? = nil,205 page: Int = 1, pageSize: Int = 24) async throws -> SearchResponse {206 // v3 : première page par la recherche à curseur (les pages suivantes passent par `searchV3` et son curseur)207 if page == 1, await isV3() {208 let r = try await searchV3(filters, sort: sort, bbox: bbox, limit: min(100, pageSize))209 // une agence nommée par sa bannière n'a pas d'égalité en v3 : la v2 la connaît encore210 if !(r.total == 0 && filters.agency != nil) {211 return SearchResponse(total: r.total, page: 1, pageSize: pageSize, listings: r.items)212 }213 }214 if await isV2() {215 var q = await queryV2(filters)216 q["sort"] = sort.v2217 q["bbox"] = bbox218 q["page"] = String(page)219 q["page_size"] = String(pageSize)220 q["include"] = "liste"221 return try await get("api/search", query: q)222 }223 // --- repli v1 ---224 if let bbox {225 // zone visible : la collection géolocalisée (champs allégés), triée ici226 var q = filters.query227 q["bbox"] = bbox228 q["limit"] = "4000"229 let key = q.sorted { $0.key < $1.key }.map { "\($0.key)=\($0.value ?? "")" }.joined(separator: "&")230 let geo: GeoCollection231 if let c = geoCache, c.key == key { geo = c.value } else {232 geo = try await get("api/listings.geojson", query: q)233 geoCache = (key, geo)234 }235 var all = filters.applyLocally(geo.listings)236 switch sort {237 case .prix: all.sort { ($0.plausiblePrice ?? .infinity) < ($1.plausiblePrice ?? .infinity) }238 case .prixDesc: all.sort { ($0.plausiblePrice ?? -1) > ($1.plausiblePrice ?? -1) }239 case .deal: all.sort { ($0.deviation ?? 9) < ($1.deviation ?? 9) }240 case .superficie: all.sort { ($0.areaSqft ?? 0) > ($1.areaSqft ?? 0) }241 case .pi2: all.sort { ($0.pricePerSqft ?? .infinity) < ($1.pricePerSqft ?? .infinity) }242 case .terrain: all.sort { ($0.lotSqft ?? 0) > ($1.lotSqft ?? 0) }243 // la collection n'a pas de date : on montre d'abord les propriétés avec photo et prix244 default: all.sort { ($0.images.isEmpty ? 1 : 0, $0.plausiblePrice == nil ? 1 : 0) < ($1.images.isEmpty ? 1 : 0, $1.plausiblePrice == nil ? 1 : 0) }245 }246 let start = min(all.count, (page - 1) * pageSize)247 let total = filters.needsLocalFilter ? all.count : max(geo.totalGeocoded, all.count)248 return SearchResponse(total: total, page: page, pageSize: pageSize,249 listings: Array(all[start..<min(all.count, start + pageSize)]))250 }251 var q = filters.query252 q["sort"] = sort.v1253 // le verdict n'est pas filtrable côté serveur en v1 : on ratisse plus large puis on filtre ici254 let widen = filters.needsLocalFilter || sort == .deal255 q["limit"] = String(widen ? pageSize * 8 : pageSize)256 q["offset"] = String((page - 1) * (widen ? pageSize * 8 : pageSize))257 let r: ListingsPage = try await get("api/listings", query: q)258 var out = filters.applyLocally(r.listings)259 if sort == .deal { out = out.filter { $0.deviation != nil }.sorted { ($0.deviation ?? 9) < ($1.deviation ?? 9) } }260 return SearchResponse(total: widen ? max(out.count, min(r.total, out.count * 8)) : r.total, page: page, pageSize: pageSize,261 listings: Array(out.prefix(widen ? pageSize * 2 : pageSize)))262 }263264 /// Tous les points de carte d'une recherche.265 func mapPoints(_ filters: SearchFilters) async throws -> MapPointsResult {266 if await isV2() {267 var q = await queryV2(filters)268 q["include"] = "tout"269 q["page"] = "1"270 q["page_size"] = "1"271 let r: SearchResponse = try await get("api/search", query: q)272 return MapPointsResult(points: r.points ?? [], total: r.total, unpositioned: r.unpositioned)273 }274 // --- repli v1 : la collection est plafonnée par appel ; on découpe le Québec en quadrants jusqu'à tout avoir ---275 let cap = 8000276 var q = filters.query277 q["limit"] = String(cap)278 var pending = [MapBounds(west: -80.5, south: 44.5, east: -56.5, north: 63)]279 var seen = Set<String>()280 var points: [MapPoint] = []281 var matching = 0282 var first = true283 var depth = 0284 while !pending.isEmpty, depth < 6 {285 let batch = pending286 pending = []287 let results = try await withThrowingTaskGroup(of: (MapBounds, GeoCollection).self) { group in288 for b in batch {289 var qq = q290 qq["bbox"] = b.bbox291 group.addTask { [qq] in (b, try await self.get("api/listings.geojson", query: qq, as: GeoCollection.self)) }292 }293 var out: [(MapBounds, GeoCollection)] = []294 for try await r in group { out.append(r) }295 return out296 }297 for (b, geo) in results {298 if first { matching = geo.totalMatching; first = false }299 if geo.totalGeocoded > geo.listings.count, depth < 5 {300 pending.append(contentsOf: b.quadrants)301 continue302 }303 for l in filters.applyLocally(geo.listings) where seen.insert(l.uid).inserted {304 guard let lat = l.lat, let lng = l.lng else { continue }305 points.append(MapPoint(uid: l.uid, lng: lng, lat: lat, price: l.price, verdict: l.verdict))306 }307 }308 depth += 1309 }310 let total = filters.needsLocalFilter ? points.count : max(matching, points.count)311 return MapPointsResult(points: points, total: total, unpositioned: max(0, total - points.count))312 }313314 // MARK: Fiche315316 /// Fiche de la v2 (riche : quartier, points d'intérêt, courtier). L'app appelle `fullListing`.317 func listing(_ uid: String) async throws -> Listing { try await get("api/listings/\(enc(uid))") }318 func pdfURL(_ uid: String) async -> URL? { await url("api/listings/\(enc(uid))/pdf") }319320 func inondation(lat: Double, lng: Double) async throws -> Inondation {321 try await get("api/inondation", query: ["lat": String(lat), "lng": String(lng)])322 }323 func air(lat: Double, lng: Double) async throws -> AirNearby {324 try await get("api/air", query: ["lat": String(lat), "lng": String(lng)])325 }326 func commerces(lat: Double, lng: Double) async throws -> Commerces {327 try await get("api/commerces", query: ["lat": String(lat), "lng": String(lng)])328 }329 func gaz(lat: Double, lng: Double) async throws -> GazNearby {330 try await get("api/gaz", query: ["lat": String(lat), "lng": String(lng)])331 }332 func hydro(address: String, uid: String, lat: Double?, lng: Double?) async throws -> HydroEstimate {333 try await get("api/hydro", query: ["adresse": address, "uid": uid, "lat": lat.map { String($0) }, "lng": lng.map { String($0) }])334 }335336 /// Propriétés comparables : même ville, même type, prix voisin (± 20 %).337 func comparables(for l: Listing) async throws -> [Listing] {338 guard let p = l.plausiblePrice, !l.city.isEmpty else { return [] }339 var f = SearchFilters()340 f.city = l.city341 f.propertyType = l.propertyType.isEmpty ? nil : l.propertyType342 f.priceMin = Int(p * 0.8)343 f.priceMax = Int(p * 1.2)344 let r = try await search(f, sort: .recent, page: 1, pageSize: 13)345 return Array(r.listings.filter { $0.uid != l.uid && $0.plausiblePrice != nil }.prefix(12))346 }347348 // MARK: Annuaires349350 func agencies() async throws -> AgenciesTree { try await get("api/agencies") }351352 /// Annuaire des bannières, agences et plateformes : enrichi en v2, reconstruit de l'arbre des bureaux en v1.353 func agencyDirectory() async throws -> AgencyDirectory {354 if await isV2() {355 async let tree = try? agencies()356 var d: AgencyDirectory = try await get("api/agences")357 d.attachSources(from: await tree)358 return d359 }360 return AgencyDirectory(tree: try await agencies())361 }362 /// Fiche d'une agence du registre (v2) avec la liste de ses courtiers.363 func agency(_ id: String) async throws -> AgencyEntry { try await get("api/agences/\(enc(id))") }364 /// Page d'une ville (v2 seulement).365 func cityPage(_ name: String) async -> CityPage? {366 guard await isV2() else { return nil }367 return try? await get("api/seo/ville/\(enc(Fmt.slug(name)))")368 }369 func bannieres() async throws -> BannieresDirectory { try await get("api/bannieres") }370 func banniere(_ id: String) async throws -> Banniere { try await get("api/bannieres/\(enc(id))") }371 func inspecteurs() async throws -> ProDirectory { try await get("api/inspecteurs") }372 func demenageurs() async throws -> ProDirectory { try await get("api/demenageurs") }373374 /// Villes de l'index : nom, inscriptions en ligne, prix médian.375 func cities() async throws -> [CityEntry] {376 if await isV2(), let r: CitiesResponse = try? await get("api/seo/villes"), !r.cities.isEmpty {377 return r.cities.filter { Fmt.isPlausibleCity($0.name) && $0.count > 0 }.sorted { $0.count > $1.count }378 }379 // repli : le tableau « Top villes » du tableau de bord (50 villes)380 let d = try await dashboard()381 return (d.table("top_villes")?.rows ?? []).compactMap { row in382 guard row.count >= 4, Fmt.isPlausibleCity(row[0]) else { return nil }383 let digits: (String) -> Double? = { Double($0.filter { $0.isNumber }) }384 return CityEntry(name: row[0], count: Int(digits(row[1]) ?? 0), medianPrice: digits(row[3]))385 }386 }387388 // MARK: Taux hypothécaires389390 func mortgageBest(fixed: Bool = true, term: Int = 60) async throws -> MortgageBest {391 try await get("api/mortgage/rates/best", query: ["rate_type": fixed ? "fixed" : "variable", "term_months": String(term)])392 }393 func mortgageRates() async throws -> MortgageRates { try await get("api/mortgage/rates") }394 func mortgageHistory(days: Int = 365) async throws -> MortgageRates {395 try await get("api/mortgage/rates/history", query: ["days": String(days)])396 }397 func mortgageIntelligence() async throws -> MortgageIntelligence { try await get("api/mortgage/intelligence") }398}399400/// Filtres de recherche (mêmes paramètres que le site).401struct SearchFilters: Codable, Sendable, Hashable {402 var city: String?403 var sector: String?404 var region: String?405 var propertyType: String?406 var source: String?407 /// bannière ou bureau (v2)408 var agency: String?409 var priceMin: Int?410 var priceMax: Int?411 var bedroomsMin: Int?412 var bathroomsMin: Int?413 var areaMin: Int?414 var lotMin: Int?415 var yearMin: Int?416 var deal: Verdict?417 var text: String?418 // --- v3 seulement (ignorés par les replis v2 et v1) ---419 /// phrase libre, interprétée par le service420 var nl: String?421 /// attributs exigés (oui observé) : parking, garage, pool, basement, fireplace, waterfront, view, ac, ev, accessible, elevator422 var with: [String]?423 var priceDrop: Bool?424 /// vues pour la première fois depuis N jours425 var newDays: Int?426 var yearMax: Int?427 /// taxes municipales et scolaires annuelles maximales428 var taxMax: Int?429 /// frais de copropriété mensuels maximaux430 var condoFeeMax: Int?431 /// nom du courtier inscripteur (contient)432 var broker: String?433434 /// Attributs filtrables de la v3, dans l'ordre d'usage.435 static let attributes: [(key: String, label: String, icon: String)] = [436 ("garage", "Garage", "door.garage.closed"), ("parking", "Stationnement", "parkingsign"),437 ("pool", "Piscine", "figure.pool.swim"), ("basement", "Sous-sol aménagé", "stairs"),438 ("fireplace", "Foyer ou poêle", "fireplace"), ("waterfront", "Bord de l'eau", "water.waves"),439 ("view", "Vue", "mountain.2"), ("ac", "Climatisation", "snowflake"), ("ev", "Borne de recharge", "bolt.car"),440 ("accessible", "Accès adapté", "figure.roll"), ("elevator", "Ascenseur", "arrow.up.arrow.down"),441 ]442443 /// Paramètres de `/api/v3/search`, `/search/map` et `/search/facets`.444 var queryV3: [String: String?] {445 let position: String? = switch deal { case .sous: "sous"; case .marche: "dans"; case .sur: "sur"; case nil: nil }446 return [447 "city": city, "area": sector, "region": region, "type": propertyType, "source": source, "agency": agency,448 "price_min": priceMin.map(String.init), "price_max": priceMax.map(String.init),449 "bedrooms_min": bedroomsMin.map(String.init), "bathrooms_min": bathroomsMin.map(String.init),450 "area_min": areaMin.map(String.init), "lot_min": lotMin.map(String.init),451 "year_min": yearMin.map(String.init), "year_max": yearMax.map(String.init),452 "position": position, "q": text, "nl": nl, "broker": broker,453 "with": (with ?? []).isEmpty ? nil : (with ?? []).sorted().joined(separator: ","),454 "price_drop": priceDrop == true ? "1" : nil,455 "new_days": newDays.map(String.init),456 "tax_max": taxMax.map(String.init), "condo_fee_max": condoFeeMax.map(String.init),457 ]458 }459460 var query: [String: String?] {461 [462 "city": city, "sector": sector, "region": region, "property_type": propertyType, "source": source, "agency": agency,463 "price_min": priceMin.map(String.init), "price_max": priceMax.map(String.init),464 "bedrooms_min": bedroomsMin.map(String.init), "bathrooms_min": bathroomsMin.map(String.init),465 "area_min": areaMin.map(String.init), "lot_min": lotMin.map(String.init),466 "year_min": yearMin.map(String.init),467 "deal": deal?.rawValue,468 "q": text,469 ]470 }471472 /// Filtres que la v1 ne connaît pas et que l'app applique elle-même aux réponses.473 var needsLocalFilter: Bool { deal != nil || lotMin != nil || yearMin != nil }474475 /// Filtrage local (repli v1) : verdict, terrain et année quand les champs sont présents dans la réponse.476 func applyLocally(_ list: [Listing]) -> [Listing] {477 guard needsLocalFilter else { return list }478 return list.filter { l in479 if let deal, l.verdict != deal { return false }480 if let lotMin, let lot = l.lotSqft, lot < Double(lotMin) { return false }481 if let yearMin, let y = l.yearBuilt, y < yearMin { return false }482 return true483 }484 }485486 /// Nombre de filtres actifs (hors lieu et texte).487 var activeCount: Int {488 [propertyType != nil, priceMin != nil, priceMax != nil, bedroomsMin != nil, bathroomsMin != nil,489 areaMin != nil, lotMin != nil, yearMin != nil, deal != nil, sector != nil, source != nil, region != nil, agency != nil,490 priceDrop == true, newDays != nil, yearMax != nil, taxMax != nil, condoFeeMax != nil].filter { $0 }.count + (with ?? []).count491 }492493 var hasPlace: Bool { city != nil || sector != nil || source != nil || region != nil || agency != nil || !(text ?? "").isEmpty || !(nl ?? "").isEmpty || broker != nil }494 var isEmpty: Bool { self == SearchFilters() }495496 /// Libellé court d'une recherche (recherches enregistrées, titre de la liste).497 var summary: String {498 var parts: [String] = []499 if let city { parts.append(city) } else if let broker { parts.append(broker) } else if let agency { parts.append(agency) } else if let region { parts.append(region) } else if let t = text ?? nl, !t.isEmpty { parts.append("« \(t) »") } else { parts.append("Tout le Québec") }500 if let propertyType { parts.append(propertyType) }501 if let priceMax { parts.append("≤ \(Fmt.compactMoney(Double(priceMax)))") }502 if let priceMin, priceMax == nil { parts.append("≥ \(Fmt.compactMoney(Double(priceMin)))") }503 if let bedroomsMin { parts.append("\(bedroomsMin)+ ch.") }504 if deal == .sous { parts.append("sous le prix attendu") }505 if priceDrop == true { parts.append("prix en baisse") }506 if let newDays { parts.append("\(newDays) derniers jours") }507 return parts.joined(separator: " · ")508 }509}510511extension MapBounds {512 /// Les quatre quarts de la zone.513 var quadrants: [MapBounds] {514 let mx = (west + east) / 2, my = (south + north) / 2515 return [MapBounds(west: west, south: south, east: mx, north: my), MapBounds(west: mx, south: south, east: east, north: my),516 MapBounds(west: west, south: my, east: mx, north: north), MapBounds(west: mx, south: my, east: east, north: north)]517 }518}519