SPB Git

Repository Public

WidgetData.swift 10.8 KB 240 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : Immo-Ka iOS9// File             : ImmoKaWidgets/WidgetData.swift10// Description      : données des widgets, lues dans l'API v3 de production.11//                    Autonome (aucun code partagé avec l'app) : l'extension12//                    reste petite. Rien n'est inventé : sans réponse, le widget13//                    le dit.14// Module           : ImmoKaWidgets15// Repository       : https://git.spboucher.ai/immo-ka-ios-v316// Project Website  : https://www.immo-ka.com17// Created          : 2026-11-2818// Last Modified    : 2026-11-2819//20// =============================================================================21// AUTHOR & PROFESSIONAL AFFILIATION22// =============================================================================23//24// Author           : Simon-Pierre Boucher25// Position         : Professor of Finance26// Institution      : Université du Québec en Outaouais (UQO)27// Department       : Département des sciences administratives28// Organization     : SP Boucher29//30// Website          : https://spboucher.ai31// Git              : https://git.spboucher.ai32//33// =============================================================================34// OFFICIAL CONTACT DIRECTORY35// =============================================================================36//37// General          : info@spboucher.ai38// Professional     : contact@spboucher.ai39// Direct           : simon@spboucher.ai40// Research         : research@spboucher.ai41// Development      : dev@spboucher.ai42// Support          : support@spboucher.ai43// Security/Admin   : admin@spboucher.ai44// Notifications    : notifications@spboucher.ai45//46// Preferred Contact: support@spboucher.ai47//48// =============================================================================49// COPYRIGHT & INTELLECTUAL PROPERTY50// =============================================================================51//52// Copyright (c) 202653// Simon-Pierre Boucher54//55// All rights reserved where applicable.56//57// This file is governed by the applicable project license,58// copyright notices, institutional agreements and relevant law.59//60// Unless expressly authorized by the applicable license or61// rights holder, copying, redistribution, sublicensing,62// publication and commercial exploitation are not permitted.63//64// Existing third-party rights and notices remain unaffected.65//66// =============================================================================67// CONFIDENTIALITY & SECURITY68// =============================================================================69//70// Classification   : Public71// Distribution     : Public repository; use is governed by the project license72// Security Contact : admin@spboucher.ai73//74// Access to this source does not independently grant permission75// to redistribute or disclose confidential materials.76//77// Do not embed credentials, private keys, access tokens,78// certificates or confidential personal information.79//80// =============================================================================81// LICENSE & MAINTENANCE82// =============================================================================83//84// License          : None specified (no license file in this repository)85// Maintainer       : Simon-Pierre Boucher86// Technical Contact: dev@spboucher.ai87//88// =============================================================================89// END OF SP BOUCHER SOURCE HEADER90// =============================================================================9192import Foundation9394enum WidgetFormat {95    static let locale = Locale(identifier: "fr_CA")9697    /// « 425 000 $ »98    static func money(_ v: Double) -> String {99        v.formatted(.number.precision(.fractionLength(0)).locale(locale)) + " $"100    }101102    /// « 425 k$ », « 1,25 M$ » : pour une étiquette étroite seulement.103    static func compact(_ v: Double) -> String {104        if v >= 1_000_000 {105            let m = (v / 10_000).rounded() / 100106            return m.formatted(.number.precision(.fractionLength(0...2)).locale(locale)) + " M$"107        }108        return (v / 1000).rounded().formatted(.number.precision(.fractionLength(0)).locale(locale)) + " k$"109    }110111    static func int(_ n: Int) -> String { n.formatted(.number.locale(locale)) }112113    /// Identifiant d'URL d'une ville : « Trois-Rivières » → « trois-rivieres ».114    static func slug(_ s: String) -> String {115        let folded = s.folding(options: [.diacriticInsensitive, .caseInsensitive], locale: locale).lowercased()116        let mapped = folded.map { $0.isLetter || $0.isNumber ? $0 : "-" }117        return String(mapped).split(separator: "-").joined(separator: "-")118    }119120    /// « 2026-11-28 » → « 28 nov. »121    static func shortDay(_ iso: String?) -> String? {122        guard let iso else { return nil }123        let p = iso.prefix(10).split(separator: "-").compactMap { Int($0) }124        guard p.count == 3 else { return nil }125        var c = DateComponents(); c.year = p[0]; c.month = p[1]; c.day = p[2]126        guard let d = Calendar(identifier: .gregorian).date(from: c) else { return nil }127        return d.formatted(.dateTime.day().month(.abbreviated).locale(locale))128    }129}130131/// Une inscription récente, réduite à ce qu'un widget montre.132struct WidgetListing: Decodable, Sendable, Identifiable, Hashable {133    var uid: String134    var address: String135    var city: String136    var type: String137    var price: Double?138    var id: String { uid }139140    private enum K: String, CodingKey { case uid, address, title, city, ptype, price }141    init(uid: String, address: String, city: String, type: String, price: Double?) {142        self.uid = uid; self.address = address; self.city = city; self.type = type; self.price = price143    }144    init(from decoder: Decoder) throws {145        let c = try decoder.container(keyedBy: K.self)146        uid = try c.decode(String.self, forKey: .uid)147        let a = (try? c.decodeIfPresent(String.self, forKey: .address)) ?? nil148        let t = (try? c.decodeIfPresent(String.self, forKey: .title)) ?? nil149        address = (a?.isEmpty == false ? a : t) ?? "Propriété à vendre"150        city = ((try? c.decodeIfPresent(String.self, forKey: .city)) ?? nil) ?? ""151        type = ((try? c.decodeIfPresent(String.self, forKey: .ptype)) ?? nil) ?? ""152        let p = (try? c.decodeIfPresent(Double.self, forKey: .price)) ?? nil153        // prix plausible seulement : sinon « prix sur demande »154        price = p.flatMap { $0 >= 10_000 && $0 <= 150_000_000 ? $0 : nil }155    }156157    var url: URL {158        var c = URLComponents(); c.scheme = "immoka"; c.host = "propriete"; c.path = "/" + uid159        return c.url ?? URL(string: "immoka://recherche")!160    }161}162163struct NewListingsData: Sendable, Hashable {164    /// nil : tout le Québec165    var city: String?166    var items: [WidgetListing]167    /// inscriptions vues pour la première fois depuis sept jours ; nil : inconnu168    var newThisWeek: Int?169    var total: Int?170}171172struct MarketData: Sendable, Hashable {173    var place: String174    var slug: String?175    var askMedian: Double?176    var inventory: Int?177    var new30d: Int?178    var asOf: String?179    /// variation sur un an de l'indice des prix de vente (unifamiliale), si le service le publie pour ce lieu180    var indexYoY: Double?181}182183enum WidgetAPIError: Error { case http(Int), notFound, offline }184185enum WidgetAPI {186    static let base = URL(string: "https://www.immo-ka.com/api/v3/")!187188    static func get(_ path: String, _ query: [String: String?]) async throws -> Data {189        var c = URLComponents(url: base.appending(path: path), resolvingAgainstBaseURL: false)!190        let items = query.compactMap { k, v in v.flatMap { $0.isEmpty ? nil : URLQueryItem(name: k, value: $0) } }.sorted { $0.name < $1.name }191        if !items.isEmpty { c.queryItems = items }192        var req = URLRequest(url: c.url!)193        req.timeoutInterval = 15194        req.setValue("application/json", forHTTPHeaderField: "Accept")195        do {196            let (d, r) = try await URLSession.shared.data(for: req)197            let code = (r as? HTTPURLResponse)?.statusCode ?? 0198            if code == 404 { throw WidgetAPIError.notFound }199            guard (200..<300).contains(code) else { throw WidgetAPIError.http(code) }200            return d201        } catch let e as WidgetAPIError { throw e } catch { throw WidgetAPIError.offline }202    }203204    private struct SearchPage: Decodable { var total: Int?; var items: [WidgetListing] }205    private struct Facets: Decodable {206        var new7: Int?207        private enum K: String, CodingKey { case new_7_days }208        init(from decoder: Decoder) throws { new7 = try? decoder.container(keyedBy: K.self).decodeIfPresent(Int.self, forKey: .new_7_days) }209    }210211    static func decodeSearch(_ data: Data) throws -> (total: Int?, items: [WidgetListing]) {212        let p = try JSONDecoder().decode(SearchPage.self, from: data)213        return (p.total, p.items)214    }215216    static func newListings(city: String?) async throws -> NewListingsData {217        let c = city.flatMap { $0.trimmingCharacters(in: .whitespaces).isEmpty ? nil : $0 }218        let page = try decodeSearch(try await get("search", ["city": c, "sort": "recent", "limit": "6", "family": "unifamiliale,condo,plex,maison_de_ville,jumele,chalet"]))219        let facets = try? JSONDecoder().decode(Facets.self, from: try await get("search/facets", ["city": c]))220        return NewListingsData(city: c, items: page.items, newThisWeek: facets?.new7, total: page.total)221    }222223    static func decodeMarket(_ data: Data, slug: String?) throws -> MarketData {224        guard let root = try JSONSerialization.jsonObject(with: data) as? [String: Any] else { throw WidgetAPIError.http(0) }225        let place = (root["place"] as? [String: Any])?["name"] as? String ?? "Québec"226        let l = root["listings"] as? [String: Any] ?? [:]227        func value(_ k: String) -> Double? { ((l[k] as? [String: Any])?["value"] as? NSNumber)?.doubleValue }228        let index = (root["index"] as? [[String: Any]])?.first { $0["family"] as? String == "unifamiliale" }229        return MarketData(place: place, slug: slug, askMedian: value("ask_median"), inventory: value("inventory").map { Int($0) },230                          new30d: value("new_30d").map { Int($0) }, asOf: l["as_of"] as? String,231                          indexYoY: (index?["yoy_pct"] as? NSNumber)?.doubleValue)232    }233234    static func market(city: String?) async throws -> MarketData {235        let slug = city.map { WidgetFormat.slug($0) }.flatMap { $0.isEmpty ? nil : $0 }236        let data = try await get("market", ["place": slug, "kind": slug == nil ? nil : "municipalite"])237        return try decodeMarket(data, slug: slug)238    }239}240
Files main
Menu

Theme