1// Auteur : Simon-Pierre Boucher — contact@spboucher.ai2// Ecosystem.swift — la source de vérité des 13 univers Groupe-KA dans l'app :3// identité (nom, accent, symbole, tagline) + configuration d'API (endpoint de4// liste, clé des items, mapping JSON → KAItem). Ajouter un univers = ajouter5// une entrée ici, rien d'autre (voir docs/ARCHITECTURE.md).6import SwiftUI78// MARK: - JSON générique (les API des univers ont chacune leur forme)910enum JSONValue: Decodable {11 case string(String), number(Double), bool(Bool)12 case object([String: JSONValue]), array([JSONValue]), null1314 init(from decoder: Decoder) throws {15 let c = try decoder.singleValueContainer()16 if c.decodeNil() { self = .null }17 else if let b = try? c.decode(Bool.self) { self = .bool(b) }18 else if let n = try? c.decode(Double.self) { self = .number(n) }19 else if let s = try? c.decode(String.self) { self = .string(s) }20 else if let a = try? c.decode([JSONValue].self) { self = .array(a) }21 else { self = .object(try c.decode([String: JSONValue].self)) }22 }2324 var string: String? { if case .string(let s) = self { return s }; return nil }25 var number: Double? { if case .number(let n) = self { return n }; return nil }26 var array: [JSONValue]? { if case .array(let a) = self { return a }; return nil }27 var object: [String: JSONValue]? { if case .object(let o) = self { return o }; return nil }28 /// Texte « au mieux » (string, nombre formaté, liste jointe)29 var text: String? {30 switch self {31 case .string(let s): return s.isEmpty ? nil : s32 case .number(let n): return n == n.rounded() ? String(Int(n)) : String(n)33 case .array(let a): let parts = a.compactMap(\.text); return parts.isEmpty ? nil : parts.joined(separator: ", ")34 default: return nil35 }36 }37}3839extension [String: JSONValue] {40 func str(_ keys: String...) -> String? {41 for k in keys { if let v = self[k]?.text { return v } }42 return nil43 }44 func num(_ keys: String...) -> Double? {45 for k in keys { if let v = self[k]?.number { return v } }46 return nil47 }48}4950// MARK: - L'élément universel5152struct KAItem: Identifiable, Hashable, Codable {53 var id: String54 var universeID: String55 var title: String56 var subtitle: String?57 var priceLabel: String?58 var city: String?59 var url: URL?60 var imageURL: URL?61 /// Galerie complète (les sites en ont souvent plusieurs)62 var imageURLs: [URL] = []63 var latitude: Double?64 var longitude: Double?65 /// Description longue (fiche)66 var detail: String?67 /// Paires libres affichées sur la fiche (« Année : 2021 », « Salaire : 65 000 $ »…)68 var facts: [Fact]69 /// Liens riches (boutons) — ex. les comptes d'un créateur70 var links: [Fact] = []71 /// Étiquettes de la fiche complète (commodités, caractéristiques, cuisines…)72 /// — optionnelles : les favoris/historique sérialisés avant leur ajout73 /// doivent continuer à se décoder74 var tags: [String]? = nil75 /// Résumé « en bref » de la fiche (digest du site)76 var brief: String? = nil7778 struct Fact: Hashable, Codable { var label: String; var value: String }79}8081// MARK: - Univers8283struct Universe: Identifiable {84 let id: String85 let wordmark: String // « Lou·Ka »86 let name: String // « Lou-KA »87 let tagline: String88 let accentHex: String89 let symbol: String // SF Symbol90 let domain: String91 let unit: String // « logements », « offres »…92 /// Chemin de la liste (nil = univers sans liste native, ex. groupe-ka)93 let listPath: String?94 let itemsKey: String95 let searchParam: String96 let statTotalKeys: [String] // clés du total dans /api/stats97 let map: (@Sendable ([String: JSONValue]) -> KAItem?)?9899 var accent: Color { Color(hex: accentHex) }100 var baseURL: URL { URL(string: "https://\(domain)")! }101}102103enum Ecosystem {104 static let hubURL = URL(string: "https://www.groupe-ka.com")!105 static let signupURL = URL(string: "https://www.groupe-ka.com/connexion")!106 static let statusURL = URL(string: "https://www.groupe-ka.com/status")!107 static let contacts: [(email: String, role: String)] = [108 ("contact@groupe-ka.com", "Projets, partenariats & données"),109 ("info@groupe-ka.com", "Médias & questions générales"),110 ("admin@groupe-ka.com", "Légal, vie privée & Loi 25"),111 ]112 static let legal: [(label: String, path: String)] = [113 ("Conditions d'utilisation", "/conditions"),114 ("Politique de confidentialité", "/confidentialite"),115 ("Renseignements personnels (Loi 25)", "/loi-25"),116 ("Transparence des robots", "/bots"),117 ]118 static let disclaimer = "Groupe KA est un agrégateur de contenu : nous ne vendons rien, ne louons rien et ne sommes partie à aucune transaction. Données lues à la source — rien d'inventé, tout est traçable."119120 static func universe(_ id: String) -> Universe? { all.first { $0.id == id } }121122 // Aides de mapping communes123 private static func base(_ o: [String: JSONValue], universe: String, idKeys: [String] = ["uid"]) -> KAItem {124 var id: String?125 for k in idKeys { if let v = o[k]?.text { id = v; break } }126 // galerie : champ `images` (liste) ou `image` — jusqu'à 10, http seulement127 var gallery: [URL] = (o["images"]?.array ?? [])128 .compactMap { $0.text }129 .filter { $0.hasPrefix("http") }130 .prefix(10)131 .compactMap(URL.init(string:))132 if gallery.isEmpty,133 let single = o.str("image", "image_url", "photo", "thumbnail").flatMap(URL.init(string:)) {134 gallery = [single]135 }136 let image = gallery.first137 return KAItem(138 id: "\(universe):\(id ?? UUID().uuidString)",139 universeID: universe,140 title: o.str("title", "name", "display_name") ?? "Sans titre",141 subtitle: nil, priceLabel: nil,142 city: o.str("city"),143 url: o.str("url").flatMap(URL.init(string:)),144 imageURL: image,145 imageURLs: gallery,146 latitude: o.num("lat", "latitude"),147 longitude: o.num("lng", "lon", "longitude"),148 detail: o.str("description", "menu_summary", "bio").map { $0.strippingHTML.trimmingCharacters(in: .whitespacesAndNewlines) },149 facts: []150 )151 }152153 // MARK: les 12 univers (+ le hub, sans liste)154 static let all: [Universe] = [155 Universe(id: "lou-ka", wordmark: "Lou·Ka", name: "Lou-KA",156 tagline: "Tous les logements à louer", accentHex: "#ff6a00",157 symbol: "key.fill", domain: "www.lou-ka.com", unit: "logements",158 listPath: "/api/listings", itemsKey: "listings", searchParam: "q",159 statTotalKeys: ["total"],160 map: { o in161 var it = base(o, universe: "lou-ka")162 it.subtitle = [o.str("unit_type"), o.str("address")].compactMap { $0 }.joined(separator: " · ")163 if let p = o.num("price"), p > 50 { it.priceLabel = p.money0 + "/mois" }164 it.facts = [165 o.str("unit_type").map { .init(label: "Taille", value: $0) },166 o.str("address").map { .init(label: "Adresse", value: $0) },167 o.str("available_by").map { .init(label: "Disponible", value: $0) },168 o.num("area_sqft").flatMap { $0 > 50 ? KAItem.Fact(label: "Superficie", value: "\(Int($0)) pi²") : nil },169 o.str("source").map { .init(label: "Gestionnaire", value: $0) },170 ].compactMap { $0 }171 return it172 }),173 Universe(id: "immo-ka", wordmark: "Immo·Ka", name: "Immo-KA",174 tagline: "Toutes les propriétés à vendre", accentHex: "#e23744",175 symbol: "house.fill", domain: "www.immo-ka.com", unit: "propriétés",176 listPath: "/api/listings", itemsKey: "listings", searchParam: "q",177 statTotalKeys: ["total"],178 map: { o in179 var it = base(o, universe: "immo-ka")180 it.subtitle = [o.str("property_type"), o.str("region")].compactMap { $0 }.joined(separator: " · ")181 if let p = o.num("price"), p > 1000 { it.priceLabel = p.money0 }182 it.facts = [183 o.num("bedrooms").map { .init(label: "Chambres", value: String(Int($0))) },184 o.num("bathrooms").map { .init(label: "Salles de bain", value: String(Int($0))) },185 o.num("area_sqft").flatMap { $0 > 50 ? KAItem.Fact(label: "Superficie", value: "\(Int($0)) pi²") : nil },186 o.str("address").map { .init(label: "Adresse", value: $0) },187 o.str("source").map { .init(label: "Source", value: $0) },188 ].compactMap { $0 }189 return it190 }),191 Universe(id: "vrai-prix", wordmark: "Vrai-Prix", name: "Vrai-Prix",192 tagline: "La valeur réelle de chaque propriété", accentHex: "#ff5148",193 symbol: "chart.line.uptrend.xyaxis", domain: "www.vrai-prix.com", unit: "propriétés estimées",194 listPath: nil, itemsKey: "", searchParam: "q",195 statTotalKeys: ["units_total"], map: nil),196 Universe(id: "auto-ka", wordmark: "Auto·Ka", name: "Auto-KA",197 tagline: "Les voitures usagées du Québec", accentHex: "#ff5a2a",198 symbol: "car.fill", domain: "www.auto-ka.com", unit: "véhicules",199 listPath: "/api/vehicles", itemsKey: "vehicles", searchParam: "q",200 statTotalKeys: ["total"],201 map: { o in202 var it = base(o, universe: "auto-ka")203 it.subtitle = [o.num("year").map { String(Int($0)) }, o.str("mileage_label")].compactMap { $0 }.joined(separator: " · ")204 it.priceLabel = o.str("price_label") ?? o.num("price").map(\.money0)205 it.facts = [206 o.str("make").map { .init(label: "Marque", value: $0) },207 o.str("model").map { .init(label: "Modèle", value: $0) },208 o.str("transmission").map { .init(label: "Boîte", value: $0) },209 o.str("fuel").map { .init(label: "Carburant", value: $0) },210 o.str("drivetrain").map { .init(label: "Rouage", value: $0) },211 o.str("body_type").map { .init(label: "Carrosserie", value: $0) },212 o.str("dealer_name").map { .init(label: "Concessionnaire", value: $0) },213 o.str("mileage_label").map { .init(label: "Kilométrage", value: $0) },214 ].compactMap { $0 }215 return it216 }),217 Universe(id: "fabri-ka", wordmark: "Fabri·Ka", name: "Fabri-KA",218 tagline: "Les produits fabriqués au Québec", accentHex: "#c4532e",219 symbol: "shippingbox.fill", domain: "www.fabri-ka.com", unit: "produits",220 listPath: "/api/products", itemsKey: "items", searchParam: "q",221 statTotalKeys: ["totals.products", "total"],222 map: { o in223 var it = base(o, universe: "fabri-ka")224 it.subtitle = o.str("store_id", "store")225 it.priceLabel = o.str("price_label") ?? o.num("price").map(\.money2)226 it.facts = [o.str("category").map { .init(label: "Catégorie", value: $0) }].compactMap { $0 }227 return it228 }),229 Universe(id: "food-ka", wordmark: "Food·Ka", name: "Food-KA",230 tagline: "Les prix d'épicerie, suivis à la source", accentHex: "#1f9d55",231 symbol: "cart.fill", domain: "www.food-ka.com", unit: "produits",232 listPath: "/api/products", itemsKey: "products", searchParam: "q",233 statTotalKeys: ["total"],234 map: { o in235 var it = base(o, universe: "food-ka")236 it.subtitle = [o.str("brand"), o.str("size_label")].compactMap { $0 }.joined(separator: " · ")237 let onSale: Bool = { if case .bool(true) = o["on_sale"] ?? .null { return true }; return false }()238 if let p = o.num("price"), p > 0.2 {239 if onSale, let reg = o.num("regular_price"), reg > p {240 it.priceLabel = "\(p.money2) 🏷️ (rég. \(reg.money2))"241 } else { it.priceLabel = p.money2 }242 }243 it.facts = [244 o.str("category").map { .init(label: "Catégorie", value: $0) },245 o.num("unit_price").flatMap { $0 > 0.001 ? KAItem.Fact(label: "Prix unitaire", value: $0.money2) : nil },246 onSale ? KAItem.Fact(label: "Solde", value: "Oui 🏷️") : nil,247 ].compactMap { $0 }248 return it249 }),250 Universe(id: "resto-ka", wordmark: "Resto·Ka", name: "Resto-KA",251 tagline: "Chaque resto, chaque plat, chaque prix", accentHex: "#f08c00",252 symbol: "fork.knife", domain: "www.resto-ka.com", unit: "restaurants",253 listPath: "/api/restaurants", itemsKey: "restaurants", searchParam: "q",254 statTotalKeys: ["restaurants", "total"],255 map: { o in256 var it = base(o, universe: "resto-ka")257 let cuisines = o["cuisines"]?.text258 it.subtitle = [cuisines, o.str("price_range")].compactMap { $0 }.joined(separator: " · ")259 it.facts = [260 o.str("address").map { .init(label: "Adresse", value: $0) },261 o.str("chain").map { .init(label: "Chaîne", value: $0) },262 ].compactMap { $0 }263 return it264 }),265 Universe(id: "sorti-ka", wordmark: "Sorti·Ka", name: "Sorti-KA",266 tagline: "Toutes les sorties, dans les 17 régions", accentHex: "#d6336c",267 symbol: "ticket.fill", domain: "www.sorti-ka.com", unit: "événements",268 listPath: "/api/events?upcoming=true", itemsKey: "events", searchParam: "q",269 statTotalKeys: ["total_active", "total"],270 map: { o in271 var it = base(o, universe: "sorti-ka")272 it.subtitle = [o.str("start_date"), o.str("venue")].compactMap { $0 }.joined(separator: " · ")273 it.facts = [274 o.str("start_date").map { .init(label: "Début", value: $0) },275 o.str("end_date").map { .init(label: "Fin", value: $0) },276 o.str("venue").map { .init(label: "Lieu", value: $0) },277 o.str("region").map { .init(label: "Région", value: $0) },278 (o["is_free"].flatMap { if case .bool(true) = $0 { return KAItem.Fact(label: "Entrée", value: "Gratuite 🎉") } ; return nil }),279 o.num("price_min").flatMap { $0 > 1 ? KAItem.Fact(label: "Billets dès", value: $0.money0) : nil },280 ].compactMap { $0 }281 return it282 }),283 Universe(id: "crea-ka", wordmark: "Créa·Ka", name: "Créa-KA",284 tagline: "Les créateurs d'ici, tous leurs liens", accentHex: "#7048e8",285 symbol: "sparkles", domain: "www.crea-ka.com", unit: "créateurs",286 listPath: "/api/creators", itemsKey: "items", searchParam: "q",287 statTotalKeys: ["creators", "total"],288 map: { o in289 var it = base(o, universe: "crea-ka", idKeys: ["cid", "uid", "display_name"])290 let plats = o["platforms"]?.array?.compactMap(\.object) ?? []291 let totalFollowers = plats.compactMap { $0.num("followers") }.reduce(0, +)292 it.subtitle = [o["niches"]?.text,293 totalFollowers > 0 ? totalFollowers.compact + " abonnés" : nil]294 .compactMap { $0 }.joined(separator: " · ")295 if it.url == nil { it.url = plats.first?.str("url").flatMap(URL.init(string:)) }296 it.facts = plats.prefix(6).compactMap { pl in297 guard let name = pl.str("platform") else { return nil }298 let f = pl.num("followers").map { $0.compact } ?? ""299 return KAItem.Fact(label: name.capitalized, value: f.isEmpty ? "@" + (pl.str("handle") ?? "") : f + " abonnés")300 }301 it.links = plats.prefix(6).compactMap { pl in302 guard let name = pl.str("platform"), let url = pl.str("url") else { return nil }303 return KAItem.Fact(label: name.capitalized, value: url)304 }305 return it306 }),307 Universe(id: "job-ka", wordmark: "Job·Ka", name: "Job-KA",308 tagline: "Tous les emplois des employeurs québécois", accentHex: "#0c8599",309 symbol: "briefcase.fill", domain: "www.job-ka.com", unit: "offres d'emploi",310 listPath: "/api/jobs", itemsKey: "jobs", searchParam: "q",311 statTotalKeys: ["total"],312 map: { o in313 var it = base(o, universe: "job-ka")314 it.subtitle = [o.str("employer"), o.str("city")].compactMap { $0 }.joined(separator: " · ")315 let sMin = o.num("salary_year_min"), sMax = o.num("salary_year_max")316 if let a = sMin, a > 20000 {317 it.priceLabel = (sMax != nil && sMax! > a) ? "\(a.money0)–\(sMax!.money0)/an" : a.money0 + "/an"318 } else if let h = o.num("salary_hour_min"), h > 10 {319 it.priceLabel = h.money2 + "/h"320 }321 it.facts = [322 o.str("employer").map { .init(label: "Employeur", value: $0) },323 o.str("work_mode").map { .init(label: "Mode de travail", value: $0) },324 o.str("employment_type").map { .init(label: "Type", value: $0) },325 o.str("ats").map { .init(label: "Plateforme carrière", value: $0) },326 o.str("date_posted").map { .init(label: "Publiée le", value: String($0.prefix(10))) },327 ].compactMap { $0 }328 return it329 }),330 Universe(id: "trouve-ka", wordmark: "Trouve·Ka", name: "Trouve-KA",331 tagline: "Le moteur de recherche du web québécois", accentHex: "#1c7ed6",332 symbol: "magnifyingglass", domain: "www.trouve-ka.com", unit: "pages indexées",333 listPath: "/api/search", itemsKey: "results", searchParam: "q",334 statTotalKeys: ["pages_indexed"],335 map: { o in336 var it = base(o, universe: "trouve-ka", idKeys: ["url"])337 it.title = (o.str("title") ?? "Page web").strippingHTML338 it.subtitle = o.str("snippet")?.strippingHTML339 it.facts = [o.str("domain").map { .init(label: "Domaine", value: $0) }].compactMap { $0 }340 return it341 }),342 Universe(id: "api-ka", wordmark: "API·Ka", name: "API-KA",343 tagline: "La donnée de l'écosystème, par API", accentHex: "#3b5bdb",344 symbol: "terminal.fill", domain: "www.api-ka.com", unit: "appels API",345 listPath: nil, itemsKey: "", searchParam: "q",346 statTotalKeys: ["total"], map: nil),347 ]348}349350// MARK: - petites extensions351352extension Double {353 /// 17 100 000 → « 17,1 M », 5 200 → « 5,2 k »354 var compact: String {355 if self >= 1_000_000 { return String(format: "%.1f M", self / 1_000_000).replacingOccurrences(of: ".", with: ",") }356 if self >= 10_000 { return String(format: "%.0f k", self / 1_000) }357 if self >= 1_000 { return String(format: "%.1f k", self / 1_000).replacingOccurrences(of: ".", with: ",") }358 return String(Int(self))359 }360 var money0: String {361 let f = NumberFormatter(); f.numberStyle = .currency362 f.locale = Locale(identifier: "fr_CA"); f.maximumFractionDigits = 0363 return f.string(from: NSNumber(value: self)) ?? "\(Int(self)) $"364 }365 var money2: String {366 let f = NumberFormatter(); f.numberStyle = .currency367 f.locale = Locale(identifier: "fr_CA"); f.maximumFractionDigits = 2368 return f.string(from: NSNumber(value: self)) ?? "\(self) $"369 }370}371372extension String {373 var strippingHTML: String {374 replacingOccurrences(of: "<[^>]+>", with: "", options: .regularExpression)375 .replacingOccurrences(of: "&", with: "&")376 .replacingOccurrences(of: " ", with: " ")377 }378}379380extension Color {381 init(hex: String) {382 var h = hex.trimmingCharacters(in: .alphanumerics.inverted)383 if h.count == 3 { h = h.map { "\($0)\($0)" }.joined() }384 let v = UInt64(h, radix: 16) ?? 0385 self.init(.sRGB,386 red: Double((v >> 16) & 0xFF) / 255,387 green: Double((v >> 8) & 0xFF) / 255,388 blue: Double(v & 0xFF) / 255)389 }390}391