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] = []7172 struct Fact: Hashable, Codable { var label: String; var value: String }73}7475// MARK: - Univers7677struct Universe: Identifiable {78 let id: String79 let wordmark: String // « Lou·Ka »80 let name: String // « Lou-KA »81 let tagline: String82 let accentHex: String83 let symbol: String // SF Symbol84 let domain: String85 let unit: String // « logements », « offres »…86 /// Chemin de la liste (nil = univers sans liste native, ex. groupe-ka)87 let listPath: String?88 let itemsKey: String89 let searchParam: String90 let statTotalKeys: [String] // clés du total dans /api/stats91 let map: (@Sendable ([String: JSONValue]) -> KAItem?)?9293 var accent: Color { Color(hex: accentHex) }94 var baseURL: URL { URL(string: "https://\(domain)")! }95}9697enum Ecosystem {98 static let hubURL = URL(string: "https://www.groupe-ka.com")!99 static let signupURL = URL(string: "https://www.groupe-ka.com/connexion")!100 static let statusURL = URL(string: "https://www.groupe-ka.com/status")!101 static let contacts: [(email: String, role: String)] = [102 ("contact@groupe-ka.com", "Projets, partenariats & données"),103 ("info@groupe-ka.com", "Médias & questions générales"),104 ("admin@groupe-ka.com", "Légal, vie privée & Loi 25"),105 ]106 static let legal: [(label: String, path: String)] = [107 ("Conditions d'utilisation", "/conditions"),108 ("Politique de confidentialité", "/confidentialite"),109 ("Renseignements personnels (Loi 25)", "/loi-25"),110 ("Transparence des robots", "/bots"),111 ]112 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."113114 static func universe(_ id: String) -> Universe? { all.first { $0.id == id } }115116 // Aides de mapping communes117 private static func base(_ o: [String: JSONValue], universe: String, idKeys: [String] = ["uid"]) -> KAItem {118 var id: String?119 for k in idKeys { if let v = o[k]?.text { id = v; break } }120 // galerie : champ `images` (liste) ou `image` — jusqu'à 10, http seulement121 var gallery: [URL] = (o["images"]?.array ?? [])122 .compactMap { $0.text }123 .filter { $0.hasPrefix("http") }124 .prefix(10)125 .compactMap(URL.init(string:))126 if gallery.isEmpty,127 let single = o.str("image", "image_url", "photo", "thumbnail").flatMap(URL.init(string:)) {128 gallery = [single]129 }130 let image = gallery.first131 return KAItem(132 id: "\(universe):\(id ?? UUID().uuidString)",133 universeID: universe,134 title: o.str("title", "name", "display_name") ?? "Sans titre",135 subtitle: nil, priceLabel: nil,136 city: o.str("city"),137 url: o.str("url").flatMap(URL.init(string:)),138 imageURL: image,139 imageURLs: gallery,140 latitude: o.num("lat", "latitude"),141 longitude: o.num("lng", "lon", "longitude"),142 detail: o.str("description", "menu_summary", "bio").map { $0.strippingHTML.trimmingCharacters(in: .whitespacesAndNewlines) },143 facts: []144 )145 }146147 // MARK: les 12 univers (+ le hub, sans liste)148 static let all: [Universe] = [149 Universe(id: "lou-ka", wordmark: "Lou·Ka", name: "Lou-KA",150 tagline: "Tous les logements à louer", accentHex: "#ff6a00",151 symbol: "key.fill", domain: "www.lou-ka.com", unit: "logements",152 listPath: "/api/listings", itemsKey: "listings", searchParam: "q",153 statTotalKeys: ["total"],154 map: { o in155 var it = base(o, universe: "lou-ka")156 it.subtitle = [o.str("unit_type"), o.str("address")].compactMap { $0 }.joined(separator: " · ")157 if let p = o.num("price"), p > 50 { it.priceLabel = p.money0 + "/mois" }158 it.facts = [159 o.str("unit_type").map { .init(label: "Taille", value: $0) },160 o.str("address").map { .init(label: "Adresse", value: $0) },161 o.str("available_by").map { .init(label: "Disponible", value: $0) },162 o.num("area_sqft").flatMap { $0 > 50 ? KAItem.Fact(label: "Superficie", value: "\(Int($0)) pi²") : nil },163 o.str("source").map { .init(label: "Gestionnaire", value: $0) },164 ].compactMap { $0 }165 return it166 }),167 Universe(id: "immo-ka", wordmark: "Immo·Ka", name: "Immo-KA",168 tagline: "Toutes les propriétés à vendre", accentHex: "#e23744",169 symbol: "house.fill", domain: "www.immo-ka.com", unit: "propriétés",170 listPath: "/api/listings", itemsKey: "listings", searchParam: "q",171 statTotalKeys: ["total"],172 map: { o in173 var it = base(o, universe: "immo-ka")174 it.subtitle = [o.str("property_type"), o.str("region")].compactMap { $0 }.joined(separator: " · ")175 if let p = o.num("price"), p > 1000 { it.priceLabel = p.money0 }176 it.facts = [177 o.num("bedrooms").map { .init(label: "Chambres", value: String(Int($0))) },178 o.num("bathrooms").map { .init(label: "Salles de bain", value: String(Int($0))) },179 o.num("area_sqft").flatMap { $0 > 50 ? KAItem.Fact(label: "Superficie", value: "\(Int($0)) pi²") : nil },180 o.str("address").map { .init(label: "Adresse", value: $0) },181 o.str("source").map { .init(label: "Source", value: $0) },182 ].compactMap { $0 }183 return it184 }),185 Universe(id: "vrai-prix", wordmark: "Vrai-Prix", name: "Vrai-Prix",186 tagline: "La valeur réelle de chaque propriété", accentHex: "#ff5148",187 symbol: "chart.line.uptrend.xyaxis", domain: "www.vrai-prix.com", unit: "propriétés estimées",188 listPath: nil, itemsKey: "", searchParam: "q",189 statTotalKeys: ["units_total"], map: nil),190 Universe(id: "auto-ka", wordmark: "Auto·Ka", name: "Auto-KA",191 tagline: "Les voitures usagées du Québec", accentHex: "#ff5a2a",192 symbol: "car.fill", domain: "www.auto-ka.com", unit: "véhicules",193 listPath: "/api/vehicles", itemsKey: "vehicles", searchParam: "q",194 statTotalKeys: ["total"],195 map: { o in196 var it = base(o, universe: "auto-ka")197 it.subtitle = [o.num("year").map { String(Int($0)) }, o.str("mileage_label")].compactMap { $0 }.joined(separator: " · ")198 it.priceLabel = o.str("price_label") ?? o.num("price").map(\.money0)199 it.facts = [200 o.str("make").map { .init(label: "Marque", value: $0) },201 o.str("model").map { .init(label: "Modèle", value: $0) },202 o.str("transmission").map { .init(label: "Boîte", value: $0) },203 o.str("fuel").map { .init(label: "Carburant", value: $0) },204 o.str("drivetrain").map { .init(label: "Rouage", value: $0) },205 o.str("body_type").map { .init(label: "Carrosserie", value: $0) },206 o.str("dealer_name").map { .init(label: "Concessionnaire", value: $0) },207 o.str("mileage_label").map { .init(label: "Kilométrage", value: $0) },208 ].compactMap { $0 }209 return it210 }),211 Universe(id: "fabri-ka", wordmark: "Fabri·Ka", name: "Fabri-KA",212 tagline: "Les produits fabriqués au Québec", accentHex: "#c4532e",213 symbol: "shippingbox.fill", domain: "www.fabri-ka.com", unit: "produits",214 listPath: "/api/products", itemsKey: "items", searchParam: "q",215 statTotalKeys: ["totals.products", "total"],216 map: { o in217 var it = base(o, universe: "fabri-ka")218 it.subtitle = o.str("store_id", "store")219 it.priceLabel = o.str("price_label") ?? o.num("price").map(\.money2)220 it.facts = [o.str("category").map { .init(label: "Catégorie", value: $0) }].compactMap { $0 }221 return it222 }),223 Universe(id: "food-ka", wordmark: "Food·Ka", name: "Food-KA",224 tagline: "Les prix d'épicerie, suivis à la source", accentHex: "#1f9d55",225 symbol: "cart.fill", domain: "www.food-ka.com", unit: "produits",226 listPath: "/api/products", itemsKey: "products", searchParam: "q",227 statTotalKeys: ["total"],228 map: { o in229 var it = base(o, universe: "food-ka")230 it.subtitle = [o.str("brand"), o.str("size_label")].compactMap { $0 }.joined(separator: " · ")231 let onSale: Bool = { if case .bool(true) = o["on_sale"] ?? .null { return true }; return false }()232 if let p = o.num("price"), p > 0.2 {233 if onSale, let reg = o.num("regular_price"), reg > p {234 it.priceLabel = "\(p.money2) 🏷️ (rég. \(reg.money2))"235 } else { it.priceLabel = p.money2 }236 }237 it.facts = [238 o.str("category").map { .init(label: "Catégorie", value: $0) },239 o.num("unit_price").flatMap { $0 > 0.001 ? KAItem.Fact(label: "Prix unitaire", value: $0.money2) : nil },240 onSale ? KAItem.Fact(label: "Solde", value: "Oui 🏷️") : nil,241 ].compactMap { $0 }242 return it243 }),244 Universe(id: "resto-ka", wordmark: "Resto·Ka", name: "Resto-KA",245 tagline: "Chaque resto, chaque plat, chaque prix", accentHex: "#f08c00",246 symbol: "fork.knife", domain: "www.resto-ka.com", unit: "restaurants",247 listPath: "/api/restaurants", itemsKey: "restaurants", searchParam: "q",248 statTotalKeys: ["restaurants", "total"],249 map: { o in250 var it = base(o, universe: "resto-ka")251 let cuisines = o["cuisines"]?.text252 it.subtitle = [cuisines, o.str("price_range")].compactMap { $0 }.joined(separator: " · ")253 it.facts = [254 o.str("address").map { .init(label: "Adresse", value: $0) },255 o.str("chain").map { .init(label: "Chaîne", value: $0) },256 ].compactMap { $0 }257 return it258 }),259 Universe(id: "sorti-ka", wordmark: "Sorti·Ka", name: "Sorti-KA",260 tagline: "Toutes les sorties, dans les 17 régions", accentHex: "#d6336c",261 symbol: "ticket.fill", domain: "www.sorti-ka.com", unit: "événements",262 listPath: "/api/events?upcoming=true", itemsKey: "events", searchParam: "q",263 statTotalKeys: ["total_active", "total"],264 map: { o in265 var it = base(o, universe: "sorti-ka")266 it.subtitle = [o.str("start_date"), o.str("venue")].compactMap { $0 }.joined(separator: " · ")267 it.facts = [268 o.str("start_date").map { .init(label: "Début", value: $0) },269 o.str("end_date").map { .init(label: "Fin", value: $0) },270 o.str("venue").map { .init(label: "Lieu", value: $0) },271 o.str("region").map { .init(label: "Région", value: $0) },272 (o["is_free"].flatMap { if case .bool(true) = $0 { return KAItem.Fact(label: "Entrée", value: "Gratuite 🎉") } ; return nil }),273 o.num("price_min").flatMap { $0 > 1 ? KAItem.Fact(label: "Billets dès", value: $0.money0) : nil },274 ].compactMap { $0 }275 return it276 }),277 Universe(id: "crea-ka", wordmark: "Créa·Ka", name: "Créa-KA",278 tagline: "Les créateurs d'ici, tous leurs liens", accentHex: "#7048e8",279 symbol: "sparkles", domain: "www.crea-ka.com", unit: "créateurs",280 listPath: "/api/creators", itemsKey: "items", searchParam: "q",281 statTotalKeys: ["creators", "total"],282 map: { o in283 var it = base(o, universe: "crea-ka", idKeys: ["cid", "uid", "display_name"])284 let plats = o["platforms"]?.array?.compactMap(\.object) ?? []285 let totalFollowers = plats.compactMap { $0.num("followers") }.reduce(0, +)286 it.subtitle = [o["niches"]?.text,287 totalFollowers > 0 ? totalFollowers.compact + " abonnés" : nil]288 .compactMap { $0 }.joined(separator: " · ")289 if it.url == nil { it.url = plats.first?.str("url").flatMap(URL.init(string:)) }290 it.facts = plats.prefix(6).compactMap { pl in291 guard let name = pl.str("platform") else { return nil }292 let f = pl.num("followers").map { $0.compact } ?? ""293 return KAItem.Fact(label: name.capitalized, value: f.isEmpty ? "@" + (pl.str("handle") ?? "") : f + " abonnés")294 }295 it.links = plats.prefix(6).compactMap { pl in296 guard let name = pl.str("platform"), let url = pl.str("url") else { return nil }297 return KAItem.Fact(label: name.capitalized, value: url)298 }299 return it300 }),301 Universe(id: "job-ka", wordmark: "Job·Ka", name: "Job-KA",302 tagline: "Tous les emplois des employeurs québécois", accentHex: "#0c8599",303 symbol: "briefcase.fill", domain: "www.job-ka.com", unit: "offres d'emploi",304 listPath: "/api/jobs", itemsKey: "jobs", searchParam: "q",305 statTotalKeys: ["total"],306 map: { o in307 var it = base(o, universe: "job-ka")308 it.subtitle = [o.str("employer"), o.str("city")].compactMap { $0 }.joined(separator: " · ")309 let sMin = o.num("salary_year_min"), sMax = o.num("salary_year_max")310 if let a = sMin, a > 20000 {311 it.priceLabel = (sMax != nil && sMax! > a) ? "\(a.money0)–\(sMax!.money0)/an" : a.money0 + "/an"312 } else if let h = o.num("salary_hour_min"), h > 10 {313 it.priceLabel = h.money2 + "/h"314 }315 it.facts = [316 o.str("employer").map { .init(label: "Employeur", value: $0) },317 o.str("work_mode").map { .init(label: "Mode de travail", value: $0) },318 o.str("employment_type").map { .init(label: "Type", value: $0) },319 o.str("ats").map { .init(label: "Plateforme carrière", value: $0) },320 o.str("date_posted").map { .init(label: "Publiée le", value: String($0.prefix(10))) },321 ].compactMap { $0 }322 return it323 }),324 Universe(id: "trouve-ka", wordmark: "Trouve·Ka", name: "Trouve-KA",325 tagline: "Le moteur de recherche du web québécois", accentHex: "#1c7ed6",326 symbol: "magnifyingglass", domain: "www.trouve-ka.com", unit: "pages indexées",327 listPath: "/api/search", itemsKey: "results", searchParam: "q",328 statTotalKeys: ["pages_indexed"],329 map: { o in330 var it = base(o, universe: "trouve-ka", idKeys: ["url"])331 it.title = (o.str("title") ?? "Page web").strippingHTML332 it.subtitle = o.str("snippet")?.strippingHTML333 it.facts = [o.str("domain").map { .init(label: "Domaine", value: $0) }].compactMap { $0 }334 return it335 }),336 Universe(id: "api-ka", wordmark: "API·Ka", name: "API-KA",337 tagline: "La donnée de l'écosystème, par API", accentHex: "#3b5bdb",338 symbol: "terminal.fill", domain: "www.api-ka.com", unit: "appels API",339 listPath: nil, itemsKey: "", searchParam: "q",340 statTotalKeys: ["total"], map: nil),341 ]342}343344// MARK: - petites extensions345346extension Double {347 /// 17 100 000 → « 17,1 M », 5 200 → « 5,2 k »348 var compact: String {349 if self >= 1_000_000 { return String(format: "%.1f M", self / 1_000_000).replacingOccurrences(of: ".", with: ",") }350 if self >= 10_000 { return String(format: "%.0f k", self / 1_000) }351 if self >= 1_000 { return String(format: "%.1f k", self / 1_000).replacingOccurrences(of: ".", with: ",") }352 return String(Int(self))353 }354 var money0: String {355 let f = NumberFormatter(); f.numberStyle = .currency356 f.locale = Locale(identifier: "fr_CA"); f.maximumFractionDigits = 0357 return f.string(from: NSNumber(value: self)) ?? "\(Int(self)) $"358 }359 var money2: String {360 let f = NumberFormatter(); f.numberStyle = .currency361 f.locale = Locale(identifier: "fr_CA"); f.maximumFractionDigits = 2362 return f.string(from: NSNumber(value: self)) ?? "\(self) $"363 }364}365366extension String {367 var strippingHTML: String {368 replacingOccurrences(of: "<[^>]+>", with: "", options: .regularExpression)369 .replacingOccurrences(of: "&", with: "&")370 .replacingOccurrences(of: " ", with: " ")371 }372}373374extension Color {375 init(hex: String) {376 var h = hex.trimmingCharacters(in: .alphanumerics.inverted)377 if h.count == 3 { h = h.map { "\($0)\($0)" }.joined() }378 let v = UInt64(h, radix: 16) ?? 0379 self.init(.sRGB,380 red: Double((v >> 16) & 0xFF) / 255,381 green: Double((v >> 8) & 0xFF) / 255,382 blue: Double(v & 0xFF) / 255)383 }384}385