SPB Git

Repository Public

Endpoints.swift 18.1 KB 399 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : Lou-Ka iOS9// File             : LouKa/Core/API/Endpoints.swift10// Description      : points d'accès de l'API v2 encore utilisés (blocs de la11//                    fiche, annuaires), filtres et tris.12// Module           : LouKa13// Repository       : https://git.spboucher.ai/lou-ka-ios-v314// Project Website  : https://www.lou-ka.com15// Created          : 2026-11-2516// Last Modified    : 2026-11-3017//18// =============================================================================19// AUTHOR & PROFESSIONAL AFFILIATION20// =============================================================================21//22// Author           : Simon-Pierre Boucher23// Position         : Professor of Finance24// Institution      : Université du Québec en Outaouais (UQO)25// Department       : Département des sciences administratives26// Organization     : SP Boucher27//28// Website          : https://spboucher.ai29// Git              : https://git.spboucher.ai30//31// =============================================================================32// OFFICIAL CONTACT DIRECTORY33// =============================================================================34//35// General          : info@spboucher.ai36// Professional     : contact@spboucher.ai37// Direct           : simon@spboucher.ai38// Research         : research@spboucher.ai39// Development      : dev@spboucher.ai40// Support          : support@spboucher.ai41// Security/Admin   : admin@spboucher.ai42// Notifications    : notifications@spboucher.ai43//44// Preferred Contact: support@spboucher.ai45//46// =============================================================================47// COPYRIGHT & INTELLECTUAL PROPERTY48// =============================================================================49//50// Copyright (c) 202651// Simon-Pierre Boucher52//53// All rights reserved where applicable.54//55// This file is governed by the applicable project license,56// copyright notices, institutional agreements and relevant law.57//58// Unless expressly authorized by the applicable license or59// rights holder, copying, redistribution, sublicensing,60// publication and commercial exploitation are not permitted.61//62// Existing third-party rights and notices remain unaffected.63//64// =============================================================================65// CONFIDENTIALITY & SECURITY66// =============================================================================67//68// Classification   : Public69// Distribution     : Public repository; use is governed by the project license70// Security Contact : admin@spboucher.ai71//72// Access to this source does not independently grant permission73// to redistribute or disclose confidential materials.74//75// Do not embed credentials, private keys, access tokens,76// certificates or confidential personal information.77//78// =============================================================================79// LICENSE & MAINTENANCE80// =============================================================================81//82// License          : None specified (no license file in this repository)83// Maintainer       : Simon-Pierre Boucher84// Technical Contact: dev@spboucher.ai85//86// =============================================================================87// END OF SP BOUCHER SOURCE HEADER88// =============================================================================8990import Foundation9192/// Tris de la recherche (API v3). Les valeurs brutes « deal » et « ka » sont celles de la v2, gardées pour93/// relire les recherches enregistrées par l'app 2.0.0.94enum SearchSort: String, CaseIterable, Sendable, Codable, Identifiable {95    case pertinence, recent, prix, prixDesc = "prix_desc", deal, ka, superficie, pi2, baisse, distance96    var id: String { rawValue }97    var label: String {98        switch self {99        case .pertinence: "Pertinence"100        case .recent: "Plus récents"101        case .prix: "Loyer croissant"102        case .prixDesc: "Loyer décroissant"103        case .deal: "Sous l'estimation"104        case .ka: "Meilleur quartier"105        case .superficie: "Plus grands"106        case .pi2: "Moins cher au pi²"107        case .baisse: "Baisses de prix"108        case .distance: "Plus proches"109        }110    }111    /// Valeur attendue par `/api/v3/search`.112    var apiValue: String {113        switch self {114        case .deal: "occasion"115        case .ka: "quartier"116        default: rawValue117        }118    }119    /// Tris offerts dans le menu ; « Plus proches » exige un point de référence (`near`).120    static func available(near: Bool) -> [SearchSort] { allCases.filter { $0 != .distance || near } }121}122123extension APIClient {124    func enc(_ uid: String) -> String {125        // les uid contiennent « : » et parfois « / » : chaque segment est encodé126        uid.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed.subtracting(CharacterSet(charactersIn: "/?#"))) ?? uid127    }128129    func version() async throws -> APIVersion { try await get("api/version") }130    func stats() async throws -> GlobalStats { try await get("api/stats") }131    func lights() async throws -> LightsResponse { try await get("api/lights") }132    func sourceNames() async throws -> [String: String] { try await get("api/sources/names") }133    func facets(city: String? = nil) async throws -> Facets { try await get("api/facets", query: ["city": city]) }134135    func listing(_ uid: String) async throws -> Listing { try await get("api/listings/\(enc(uid))") }136    func fairValue(_ uid: String) async throws -> FairValueDetail { try await get("api/fairvalue/\(enc(uid))") }137    func coutReel(_ uid: String) async throws -> CoutReel { try await get("api/listings/\(enc(uid))/cout-reel") }138    func historique(_ uid: String) async throws -> Historique { try await get("api/listings/\(enc(uid))/historique") }139    func pdfURL(_ uid: String) async -> URL? { await url("api/listings/\(enc(uid))/pdf") }140141    func rdl(lat: Double, lng: Double) async throws -> RdlNearby {142        try await get("api/rdl", query: ["lat": String(lat), "lng": String(lng), "radius": "600", "limit": "30"])143    }144    func tal(address: String, city: String?) async throws -> TalHistory {145        try await get("api/tal", query: ["address": address, "city": city])146    }147    func inondation(lat: Double, lng: Double) async throws -> Inondation {148        try await get("api/inondation", query: ["lat": String(lat), "lng": String(lng)])149    }150    func air(lat: Double, lng: Double) async throws -> AirNearby {151        try await get("api/air", query: ["lat": String(lat), "lng": String(lng)])152    }153    func hydro(address: String, uid: String, lat: Double?, lng: Double?) async throws -> HydroEstimate {154        try await get("api/hydro", query: ["adresse": address, "uid": uid, "lat": lat.map { String($0) }, "lng": lng.map { String($0) }])155    }156157    func managers() async throws -> ManagersDirectory { try await get("api/managers") }158    func manager(_ id: String) async throws -> ManagerProfile { try await get("api/managers/\(enc(id))") }159    func villes() async throws -> VillesResponse { try await get("api/seo/villes") }160    func ville(slug: String, type: String? = nil) async throws -> VilleDetail {161        try await get("api/seo/ville/\(enc(slug))", query: ["type": type])162    }163    func movers() async throws -> MoversResponse { try await get("api/demenageurs") }164    func marketStats() async throws -> MarketStats { try await get("api/stats/detailed") }165    func scoresStats() async throws -> ScoresStats { try await get("api/scores/stats") }166}167168/// Attributs à trois états de l'API v3 (paramètre `with`).169enum Feature: String, CaseIterable, Sendable, Identifiable {170    case parking, parkingIncl = "parking_incl", ev, balcony, terrace, elevator, accessible, ac171    case heatIncl = "heat_incl", elecIncl = "elec_incl", hotwaterIncl = "hotwater_incl", internetIncl = "internet_incl"172    case appliances, washer, dishwasher, pool, gym, storage173    var id: String { rawValue }174    var label: String {175        switch self {176        case .parking: "Stationnement"177        case .parkingIncl: "Stationnement inclus"178        case .ev: "Borne de recharge"179        case .balcony: "Balcon"180        case .terrace: "Terrasse"181        case .elevator: "Ascenseur"182        case .accessible: "Accès universel"183        case .ac: "Climatisation"184        case .heatIncl: "Chauffage inclus"185        case .elecIncl: "Électricité incluse"186        case .hotwaterIncl: "Eau chaude incluse"187        case .internetIncl: "Internet inclus"188        case .appliances: "Électroménagers"189        case .washer: "Laveuse"190        case .dishwasher: "Lave-vaisselle"191        case .pool: "Piscine"192        case .gym: "Salle d'entraînement"193        case .storage: "Rangement"194        }195    }196    var icon: String {197        switch self {198        case .parking, .parkingIncl: "parkingsign"199        case .ev: "bolt.car"200        case .balcony: "sun.max"201        case .terrace: "sun.horizon"202        case .elevator: "arrow.up.arrow.down"203        case .accessible: "figure.roll"204        case .ac: "snowflake"205        case .heatIncl: "flame"206        case .elecIncl: "bolt"207        case .hotwaterIncl: "drop"208        case .internetIncl: "wifi"209        case .appliances: "refrigerator"210        case .washer: "washer"211        case .dishwasher: "dishwasher"212        case .pool: "figure.pool.swim"213        case .gym: "dumbbell"214        case .storage: "archivebox"215        }216    }217    static let included: [Feature] = [.heatIncl, .elecIncl, .hotwaterIncl, .internetIncl, .parkingIncl]218    static let building: [Feature] = [.parking, .ev, .elevator, .accessible, .pool, .gym, .storage]219    static let unit: [Feature] = [.balcony, .terrace, .ac, .appliances, .washer, .dishwasher]220}221222/// Grandeurs de l'API v3 : 0 chambre, 1 studio, 2 = 2½ … 8 = 8½ et plus.223enum Rooms {224    static let all = Array(0...8)225    static func label(_ r: Int) -> String {226        switch r {227        case 0: "Chambre"228        case 1: "Studio"229        case 8: "8½ et plus"230        default: "\(r)½"231        }232    }233    /// « 4½ » ou « Studio » (forme de la v2) → nombre de pièces.234    static func from(unitType: String) -> Int? {235        let t = unitType.lowercased()236        if t.hasPrefix("studio") { return 1 }237        if t.hasPrefix("chambre") { return 0 }238        guard let d = t.first?.wholeNumberValue, t.contains("½") else { return nil }239        return min(8, d)240    }241}242243/// Filtres de recherche (paramètres de `/api/v3/search`). Les champs de la v2 sont gardés : les recherches244/// enregistrées par l'app 2.0.0 se relisent telles quelles ; les nouveaux champs sont optionnels.245struct SearchFilters: Codable, Sendable, Hashable {246    var city: String?247    var sector: String?248    var unitType: String?249    var source: String?250    var priceMin: Int?251    var priceMax: Int?252    var deal: Verdict?253    /// nil, 0 (maintenant), 30, 60 jours254    var availableWithinDays: Int?255    var pets: Bool = false256    /// nil : indifférent · true : meublé (l'API v3 ne sait pas exiger « non meublé »)257    var furnished: Bool?258    var scoreMin: Int?259    var areaMin: Int?260    var text: String?261    // --- v3 ---262    var region: String?263    var rooms: [Int]?264    var kinds: [String]?265    var areaMax: Int?266    var bedroomsMin: Int?267    var bathroomsMin: Int?268    var features: [String]?269    var priceDrop: Bool?270    var newDays: Int?271    var builtAfter: Int?272    /// Point de référence « lat,lng » et rayon en kilomètres (Autour de moi).273    var near: String?274    var radiusKm: Double?275276    /// Grandeurs effectives : champ v3, sinon la grandeur unique d'une recherche v2.277    var effectiveRooms: [Int] { rooms ?? unitType.flatMap(Rooms.from(unitType:)).map { [$0] } ?? [] }278    /// Genres effectifs : champ v3, sinon le genre d'une recherche v2 (« Loft », « Maison », « Condo »).279    var effectiveKinds: [String] {280        if let kinds { return kinds }281        guard let u = unitType?.lowercased(), ["loft", "maison", "condo"].contains(u) else { return [] }282        return [u]283    }284285    /// Paramètres de `/api/v3/search`, `/search/map` et `/search/facets`.286    var query: [String: String?] {287        let r = effectiveRooms, k = effectiveKinds288        return [289            "region": region, "city": city, "area": sector, "source": source,290            "rooms": r.isEmpty ? nil : r.sorted().map(String.init).joined(separator: ","),291            "kind": k.isEmpty ? nil : k.sorted().joined(separator: ","),292            "price_min": priceMin.map(String.init), "price_max": priceMax.map(String.init),293            "area_min": areaMin.map(String.init), "area_max": areaMax.map(String.init),294            "bedrooms_min": bedroomsMin.map(String.init), "bathrooms_min": bathroomsMin.map(String.init),295            "verdict": deal?.rawValue,296            "avail_by": availableWithinDays.map { $0 <= 0 ? "now" : Fmt.isoInDays($0) },297            "pets": pets ? "1" : nil,298            "furnished": furnished == true ? "1" : nil,299            "price_drop": priceDrop == true ? "1" : nil,300            "with": (features ?? []).isEmpty ? nil : features!.sorted().joined(separator: ","),301            "ks_min": scoreMin.map(String.init),302            "new_days": newDays.map(String.init),303            "built_after": builtAfter.map(String.init),304            "near": near, "radius_km": near == nil ? nil : radiusKm.map { String(format: "%.1f", $0) },305            "q": text,306        ]307    }308309    /// Nombre de filtres actifs (hors lieu et texte).310    var activeCount: Int {311        [!effectiveRooms.isEmpty, !effectiveKinds.isEmpty, priceMin != nil, priceMax != nil, deal != nil, availableWithinDays != nil,312         pets, furnished == true, scoreMin != nil, areaMin != nil, areaMax != nil, bedroomsMin != nil, bathroomsMin != nil,313         priceDrop == true, newDays != nil, builtAfter != nil].filter { $0 }.count + (features?.count ?? 0)314    }315316    var hasPlace: Bool { region != nil || city != nil || sector != nil || source != nil || near != nil || !(text ?? "").isEmpty }317    var isEmpty: Bool { self == SearchFilters() }318319    /// Garde le lieu et le texte, efface le reste.320    var placeOnly: SearchFilters {321        var f = SearchFilters()322        f.region = region; f.city = city; f.sector = sector; f.source = source; f.text = text; f.near = near; f.radiusKm = radiusKm323        return f324    }325326    func has(_ f: Feature) -> Bool { features?.contains(f.rawValue) ?? false }327    mutating func toggle(_ f: Feature) {328        var set = features ?? []329        if let i = set.firstIndex(of: f.rawValue) { set.remove(at: i) } else { set.append(f.rawValue) }330        features = set.isEmpty ? nil : set331    }332    mutating func toggle(rooms r: Int) {333        var set = effectiveRooms334        if let i = set.firstIndex(of: r) { set.remove(at: i) } else { set.append(r) }335        unitType = nil336        rooms = set.isEmpty ? nil : set.sorted()337    }338    mutating func toggle(kind k: String) {339        var set = effectiveKinds340        if let i = set.firstIndex(of: k) { set.remove(at: i) } else { set.append(k) }341        if let u = unitType?.lowercased(), ["loft", "maison", "condo"].contains(u) { unitType = nil }342        kinds = set.isEmpty ? nil : set.sorted()343    }344345    /// Applique les paramètres renvoyés par `/api/v3/search/parse` (phrase libre interprétée par le serveur).346    /// Les paramètres que l'app ne sait pas représenter sont renvoyés pour être signalés, jamais ignorés en silence.347    @discardableResult348    mutating func apply(params: [String: String]) -> [String] {349        var unknown: [String] = []350        for (k, v) in params {351            switch k {352            case "region": region = v353            case "city": city = v354            case "area": sector = v355            case "source": source = v356            case "rooms": unitType = nil; rooms = v.split(separator: ",").compactMap { Int($0) }.sorted()357            case "kind": kinds = v.split(separator: ",").map(String.init).sorted()358            case "price_min": priceMin = Int(Double(v) ?? 0)359            case "price_max": priceMax = Int(Double(v) ?? 0)360            case "area_min": areaMin = Int(Double(v) ?? 0)361            case "area_max": areaMax = Int(Double(v) ?? 0)362            case "bedrooms_min": bedroomsMin = Int(Double(v) ?? 0)363            case "bathrooms_min": bathroomsMin = Int(Double(v) ?? 0)364            case "verdict": deal = Verdict(rawValue: v)365            case "avail_by":366                if v == "now" { availableWithinDays = 0 } else if let d = Fmt.daysUntil(iso: v) { availableWithinDays = max(0, d) }367            case "pets": pets = v == "1"368            case "furnished": furnished = v == "1" ? true : nil369            case "price_drop": priceDrop = v == "1" ? true : nil370            case "with": features = v.split(separator: ",").map(String.init).filter { Feature(rawValue: $0) != nil }.sorted()371            case "ks_min": scoreMin = Int(Double(v) ?? 0)372            case "new_days": newDays = Int(v)373            case "built_after": builtAfter = Int(v)374            case "q": text = v.isEmpty ? nil : v375            case "near": near = v.isEmpty ? nil : v376            case "radius_km": radiusKm = Double(v)377            default: unknown.append(k)378            }379        }380        return unknown381    }382383    /// Libellé court d'une recherche (recherches enregistrées, titre de la liste).384    var summary: String {385        var parts: [String] = []386        if let sector { parts.append(sector) }387        if let city { parts.append(city) } else if let region { parts.append(region) }388        else if near != nil { parts.append("Autour de moi") }389        else if let t = text, !t.isEmpty { parts.append("« \(t) »") } else if sector == nil { parts.append("Tout le Québec") }390        let r = effectiveRooms391        if !r.isEmpty { parts.append(r.map(Rooms.label).joined(separator: ", ")) }392        if let priceMax { parts.append("≤ \(Fmt.int(priceMax)) $") }393        if deal == .sous { parts.append("sous l'estimation") }394        if pets { parts.append("animaux") }395        if let n = features?.count, n > 0 { parts.append(Fmt.plural(n, "attribut", "attributs")) }396        return parts.joined(separator: " · ")397    }398}399
Files main
Menu

Theme