Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : Lou-Ka iOS9// File : Shared/LouKaShared.swift10// Description : socle commun à l'app et à l'extension de widgets — lecture11// minimale de l'API v3 (lieux, nouvelles annonces, marché),12// entité « lieu » des App Intents, formats du Québec. Aucune13// donnée n'est inventée : une valeur absente reste absente.14// Module : Shared15// Repository : https://git.spboucher.ai/lou-ka-ios-v316// Project Website : https://www.lou-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 AppIntents93import Foundation9495enum SharedFmt {96 static let locale = Locale(identifier: "fr_CA")97 static func int(_ n: Int) -> String { n.formatted(.number.locale(locale).grouping(.automatic)) }98 static func money(_ d: Double?) -> String { d.map { "\(int(Int($0.rounded()))) $" } ?? "—" }99 /// Pour cent déjà en points : −1,73 → « −1,7 % ».100 static func points(_ x: Double) -> String {101 let v = abs(x).formatted(.number.precision(.fractionLength(0...1)).locale(locale))102 return "\(abs(x) < 0.05 ? "" : x > 0 ? "+" : "−")\(v) %"103 }104 static func month(iso: String?) -> String? {105 guard let p = iso?.prefix(10).split(separator: "-").compactMap({ Int($0) }), p.count >= 2 else { return nil }106 var c = DateComponents(); c.year = p[0]; c.month = p[1]; c.day = 1107 return Calendar(identifier: .gregorian).date(from: c)?.formatted(.dateTime.month(.wide).locale(locale))108 }109}110111/// Lecture minimale de l'API publique de Lou-Ka (lecture seule, sans compte, sans identifiant d'appareil).112enum SharedAPI {113 static let base = URL(string: "https://www.lou-ka.com/api/v3")!114115 struct PlaceRef: Sendable, Hashable {116 var slug: String117 var kind: String118 var name: String119 var parent: String?120 var listings: Int?121 }122123 struct NewListing: Sendable, Hashable, Identifiable {124 var uid: String125 var price: Double?126 var unit: String127 var place: String128 var firstSeen: Double?129 var id: String { uid }130 var url: URL {131 var allowed = CharacterSet.urlPathAllowed; allowed.remove(charactersIn: "/?#")132 return URL(string: "louka://logement/" + (uid.addingPercentEncoding(withAllowedCharacters: allowed) ?? uid)) ?? URL(string: "louka://")!133 }134 }135136 struct NewListings: Sendable {137 var total: Int138 var items: [NewListing]139 }140141 struct MarketBrief: Sendable {142 var placeName: String143 var median: Double?144 var active: Int?145 var changePct: Double?146 var previousMonth: String?147 var currentMonth: String?148 var index: Double?149 var asOf: String?150 }151152 static func json(_ path: String, _ query: [String: String?]) async throws -> [String: Any] {153 var comps = URLComponents(url: base.appending(path: path), resolvingAgainstBaseURL: false)!154 let items = query.compactMap { k, v in v.map { URLQueryItem(name: k, value: $0) } }.sorted { $0.name < $1.name }155 if !items.isEmpty { comps.queryItems = items }156 var req = URLRequest(url: comps.url!)157 req.timeoutInterval = 15158 req.setValue("application/json", forHTTPHeaderField: "Accept")159 let (data, resp) = try await URLSession.shared.data(for: req)160 guard (resp as? HTTPURLResponse)?.statusCode == 200, let o = try JSONSerialization.jsonObject(with: data) as? [String: Any] else {161 throw URLError(.badServerResponse)162 }163 return o164 }165166 static func placeRef(_ o: [String: Any]) -> PlaceRef? {167 guard let slug = o["slug"] as? String, let kind = o["kind"] as? String, let name = o["name"] as? String else { return nil }168 let parent = (o["parent"] as? String) ?? ((o["parent"] as? [String: Any])?["name"] as? String)169 return PlaceRef(slug: slug, kind: kind, name: name, parent: parent, listings: o["n_listings"] as? Int)170 }171172 static func suggest(_ q: String) async throws -> [PlaceRef] {173 let o = try await json("geo/suggest", ["q": String(q.prefix(80)), "limit": "10"])174 return ((o["items"] as? [[String: Any]]) ?? []).compactMap(placeRef)175 }176177 static func topPlaces() async throws -> [PlaceRef] {178 let o = try await json("geo/places", ["kind": "municipalite", "min_listings": "300"])179 return ((o["items"] as? [[String: Any]]) ?? []).compactMap(placeRef).sorted { ($0.listings ?? 0) > ($1.listings ?? 0) }180 }181182 /// Paramètres de recherche d'un lieu (mêmes règles que l'app).183 static func searchParams(_ p: PlaceRef?) -> [String: String?] {184 guard let p else { return [:] }185 switch p.kind {186 case "region": return ["region": p.name]187 case "municipalite": return ["city": p.name]188 default: return ["area": p.name, "city": p.parent]189 }190 }191192 /// Logements vus pour la première fois depuis `days` jours, du plus récent au plus ancien.193 static func newListings(place: PlaceRef?, rooms: Int?, days: Int = 3, limit: Int = 6) async throws -> NewListings {194 var q = searchParams(place)195 q["new_days"] = String(days); q["sort"] = "recent"; q["limit"] = String(limit)196 q["rooms"] = rooms.map(String.init)197 let o = try await json("search", q)198 let items = ((o["items"] as? [[String: Any]]) ?? []).compactMap { i -> NewListing? in199 guard let uid = i["uid"] as? String else { return nil }200 let sector = (i["sector"] as? String) ?? "", city = (i["city"] as? String) ?? ""201 return NewListing(uid: uid, price: i["price"] as? Double, unit: (i["unit_type"] as? String) ?? "",202 place: sector.isEmpty || sector == city ? city : "\(sector), \(city)", firstSeen: i["first_seen"] as? Double)203 }204 return NewListings(total: (o["total"] as? Int) ?? items.count, items: items)205 }206207 /// Portrait court du marché affiché d'un lieu : médiane, annonces présentes, variation à sources constantes.208 static func market(place: PlaceRef?) async throws -> MarketBrief {209 let o = try await json("market", ["place": place?.slug, "kind": place?.kind])210 let ind = ((o["current"] as? [String: Any])?["indicators"] as? [String: Any]) ?? [:]211 func value(_ k: String) -> Double? { (ind[k] as? [String: Any])?["value"] as? Double }212 let month = (o["comparison"] as? [String: Any])?["month"] as? [String: Any]213 let change = ((month?["const"] as? [String: Any])?["rent_median"] as? [String: Any])?["change_pct"] as? Double214 return MarketBrief(placeName: ((o["place"] as? [String: Any])?["name"] as? String) ?? place?.name ?? "Québec",215 median: value("rent_median"), active: value("n_active").map { Int($0) }, changePct: change,216 previousMonth: SharedFmt.month(iso: (month?["previous_period"] as? [String: Any])?["period_start"] as? String),217 currentMonth: SharedFmt.month(iso: (month?["current_period"] as? [String: Any])?["period_start"] as? String),218 index: (o["index"] as? [String: Any])?["value"] as? Double, asOf: o["as_of"] as? String)219 }220}221222// MARK: - Entité « lieu »223224/// Un lieu canonique de Lou-Ka (région, ville, arrondissement, quartier), choisi dans un widget ou un raccourci.225struct PlaceEntity: AppEntity, Hashable {226 static let typeDisplayRepresentation = TypeDisplayRepresentation(name: "Lieu")227 static let defaultQuery = PlaceQuery()228229 /// « nature:identifiant|nom|parent » : l'entité se relit sans appel réseau.230 var id: String231 var name: String232 var kind: String233 var slug: String234 var parent: String?235236 init(_ p: SharedAPI.PlaceRef) {237 name = p.name; kind = p.kind; slug = p.slug; parent = p.parent238 id = "\(p.kind):\(p.slug)|\(p.name)|\(p.parent ?? "")"239 }240241 init?(id: String) {242 let parts = id.split(separator: "|", omittingEmptySubsequences: false).map(String.init)243 guard parts.count >= 2, let colon = parts[0].firstIndex(of: ":") else { return nil }244 self.id = id245 kind = String(parts[0][..<colon]); slug = String(parts[0][parts[0].index(after: colon)...])246 name = parts[1]; parent = parts.count > 2 && !parts[2].isEmpty ? parts[2] : nil247 }248249 var ref: SharedAPI.PlaceRef { .init(slug: slug, kind: kind, name: name, parent: parent, listings: nil) }250251 var kindLabel: String {252 switch kind {253 case "region": "Région"254 case "municipalite": "Ville"255 case "arrondissement": "Arrondissement"256 case "quartier": "Quartier"257 default: "Secteur"258 }259 }260261 var displayRepresentation: DisplayRepresentation {262 DisplayRepresentation(title: "\(name)", subtitle: "\(kind == "region" || kind == "municipalite" ? kindLabel : [kindLabel, parent].compactMap { $0 }.joined(separator: " · "))")263 }264}265266struct PlaceQuery: EntityStringQuery {267 func entities(for identifiers: [String]) async throws -> [PlaceEntity] { identifiers.compactMap(PlaceEntity.init(id:)) }268 func entities(matching string: String) async throws -> [PlaceEntity] { try await SharedAPI.suggest(string).map(PlaceEntity.init) }269 func suggestedEntities() async throws -> [PlaceEntity] { try await SharedAPI.topPlaces().prefix(15).map(PlaceEntity.init) }270}271272/// Grandeur d'un logement, pour les widgets et les raccourcis.273enum RoomsOption: String, AppEnum {274 case studio, r3, r4, r5, r6275 static let typeDisplayRepresentation = TypeDisplayRepresentation(name: "Grandeur")276 static let caseDisplayRepresentations: [RoomsOption: DisplayRepresentation] = [277 .studio: "Studio", .r3: "3½", .r4: "4½", .r5: "5½", .r6: "6½",278 ]279 var rooms: Int {280 switch self {281 case .studio: 1282 case .r3: 3283 case .r4: 4284 case .r5: 5285 case .r6: 6286 }287 }288 var label: String { rooms == 1 ? "Studio" : "\(rooms)½" }289}290291// MARK: - Configuration des widgets292293struct NewListingsConfiguration: WidgetConfigurationIntent {294 static let title: LocalizedStringResource = "Nouvelles annonces"295 static let description = IntentDescription("Les logements vus pour la première fois depuis trois jours, dans le lieu de votre choix.")296 @Parameter(title: "Lieu") var place: PlaceEntity?297 @Parameter(title: "Grandeur") var rooms: RoomsOption?298}299300struct LocalMarketConfiguration: WidgetConfigurationIntent {301 static let title: LocalizedStringResource = "Marché local"302 static let description = IntentDescription("Le loyer affiché médian d'un lieu et sa variation d'un mois à l'autre, à sources constantes.")303 @Parameter(title: "Lieu") var place: PlaceEntity?304}305