SPB Git

Repository Public

AppModel.swift 16.5 KB 341 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : Immo-Ka iOS9// File             : ImmoKa/App/AppModel.swift10// Description      : état global — onglets, navigation, liens profonds, noms11//                    des sources, réglages.12// Module           : ImmoKa13// Repository       : https://git.spboucher.ai/immo-ka-ios-v314// Project Website  : https://www.immo-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 Observation91import SwiftUI9293enum AppTab: String, Hashable, CaseIterable, Sendable {94    case discover, explore, favorites, pros, market95}9697/// Destinations de navigation partagées par tous les onglets.98enum Route: Hashable, Sendable {99    case listing(String)100    /// bannière ou agence du réseau Immo-Ka (nom) et ses propriétés101    case agency(String)102    /// agence inscrite au registre de l'OACIQ103    case banniere(String)104    case city(String)105    case cities106    case inspectors107    case movers108    case registry109    case compare110    case recent111    case rates112    case calculator113    case vraiPrixGuide114    case about115    case privacy116    case terms117    case settings118    // --- v3 ---119    /// portrait d'un lieu ; `city` lève l'ambiguïté d'un nom de quartier120    case neighborhood(slug: String, city: String?)121    /// villes ayant un portrait (city nil) ou quartiers d'une ville122    case neighborhoods(city: String?, name: String?)123    case brokers124    /// marché d'un lieu (slug, nature, nom)125    case market(slug: String, kind: String, name: String)126    // --- 3.1.0 ---127    /// page d'un courtier de l'annuaire (identifiant de `/api/v3/brokers/{id}`, le même que `broker_id` des comptes)128    case broker(id: String, name: String)129    case account130    case messages131    case conversation(String)132}133134enum Appearance: String, CaseIterable, Identifiable, Sendable {135    case system, light, dark136    var id: String { rawValue }137    var label: String {138        switch self {139        case .system: "Selon le système"140        case .light: "Clair"141        case .dark: "Sombre"142        }143    }144    var scheme: ColorScheme? {145        switch self {146        case .system: nil147        case .light: .light148        case .dark: .dark149        }150    }151}152153@MainActor154@Observable155final class AppModel {156    var tab: AppTab = .discover157    var paths: [AppTab: NavigationPath] = [:]158    /// Recherche à appliquer à l'onglet Explorer (depuis l'accueil, une ville, une recherche enregistrée).159    var pendingSearch: PendingSearch?160    var toast: String?161    /// Feuille du compte (connexion, création) ; `accountStart` : étape ouverte d'emblée (captures).162    var accountSheet = false163    var accountStart: [AccountFlow.Step] = []164    /// Feuille de rédaction d'un message à un courtier.165    var compose: ComposeTarget?166167    private(set) var sourceNames: [String: String] = [:]168169    var appearance: Appearance {170        didSet { UserDefaults.standard.set(appearance.rawValue, forKey: "appearance") }171    }172173    struct PendingSearch: Equatable {174        /// nom à afficher pour le lieu (bannière ou agence dont on liste les propriétés)175        var title: String?176        var filters: SearchFilters177        var sort: SearchSort = .recent178        var id = UUID()179    }180181    init() {182        appearance = Appearance(rawValue: UserDefaults.standard.string(forKey: "appearance") ?? "") ?? .light183        // onglet de départ imposé par argument de lancement (tests, captures)184        if let t = UserDefaults.standard.string(forKey: "IKTab"), let tab = AppTab(rawValue: t) { self.tab = tab }185        // destination ouverte au lancement (tests, captures) : « propriete/<uid> », « agence/<nom> », « ville/<nom> »186        if let o = UserDefaults.standard.string(forKey: "IKOpen") {187            // « chemin?critères » : le chemin et la requête sont encodés séparément188            let parts = o.split(separator: "?", maxSplits: 1).map(String.init)189            var raw = "immoka://" + (parts[0].addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? parts[0])190            if parts.count > 1 { raw += "?" + (parts[1].addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? parts[1]) }191            if let u = URL(string: raw) { handle(url: u) }192        }193        if let c = UserDefaults.standard.string(forKey: "IKCity") {194            var f = SearchFilters(); f.city = c195            pendingSearch = PendingSearch(filters: f)196            tab = .explore197        }198        if let r = UserDefaults.standard.string(forKey: "IKRoute") {199            let map: [String: Route] = ["compare": .compare, "cities": .cities, "movers": .movers, "inspectors": .inspectors,200                                        "registry": .registry, "recent": .recent, "rates": .rates, "calculator": .calculator,201                                        "vraiprix": .vraiPrixGuide, "brokers": .brokers, "neighborhoods": .neighborhoods(city: nil, name: nil), "about": .about, "privacy": .privacy, "terms": .terms, "settings": .settings, "account": .account, "messages": .messages]202            if let route = map[r] { open(route) }203        }204        #if DEBUG205        // -IKAccount signin|signup|code|forgot|reset : ouvre la feuille du compte à cette étape (captures d'écran)206        if let a = UserDefaults.standard.string(forKey: "IKAccount") {207            let demo = "lea.tremblay@exemple.com"208            let cell = AccountIdentifier.phone("418 555-0123")209            let steps: [String: [AccountFlow.Step]] = ["signin": [], "signup": [.signUp], "code": [.signUp, .code(.email(demo), display: demo)],210                                                       "forgot": [.forgot(.email, prefill: "")], "reset": [.forgot(.email, prefill: demo), .reset(.email(demo), display: demo)],211                                                       "code-sms": [.signUp, .code(cell, display: cell.display)], "forgot-sms": [.forgot(.phone, prefill: "")],212                                                       "reset-sms": [.forgot(.phone, prefill: "418 555-0123"), .reset(cell, display: cell.display)]]213            if let s = steps[a] { accountStart = s; accountSheet = true }214        }215        #endif216    }217218    func path(for tab: AppTab) -> Binding<NavigationPath> {219        Binding(get: { self.paths[tab] ?? NavigationPath() }, set: { self.paths[tab] = $0 })220    }221222    /// Ouvre une destination dans l'onglet courant.223    func open(_ route: Route) {224        var p = paths[tab] ?? NavigationPath()225        p.append(route)226        paths[tab] = p227    }228229    /// Lance une recherche dans l'onglet Explorer.230    func explore(_ filters: SearchFilters, sort: SearchSort = .recent, title: String? = nil) {231        pendingSearch = PendingSearch(title: title, filters: filters, sort: sort)232        paths[.explore] = NavigationPath()233        tab = .explore234    }235236    func showToast(_ text: String) {237        toast = text238        Task { @MainActor in239            try? await Task.sleep(for: .seconds(2.4))240            if toast == text { toast = nil }241        }242    }243244    func sourceName(_ id: String) -> String { sourceNames[id] ?? Fmt.prettySource(id) }245246    /// Bannière d'une source (les bureaux d'une même franchise sont regroupés, comme dans l'annuaire).247    func franchiseName(for source: String) -> String {248        if source == "remax_quebec" || source.hasPrefix("remax_ag_") { return "RE/MAX" }249        if source == "via_capitale" || source.hasPrefix("via_ag_") { return "Via Capitale" }250        if source == "century21" || source.hasPrefix("c21_ag_") { return "Century 21" }251        if source == "royal_lepage" { return "Royal LePage" }252        if source == "sutton" { return "Groupe Sutton" }253        if source.hasPrefix("kw_") { return "Keller Williams" }254        if source == "duproprio" { return "DuProprio" }255        return sourceName(source)256    }257258    func loadSourceNames() async {259        guard sourceNames.isEmpty else { return }260        if let names = try? await APIClient.shared.sourceNames() { sourceNames = names }261    }262263    /// Identifiant de propriété porté par un lien (universel ou `immoka://`), sinon nil.264    nonisolated static func listingUID(from url: URL) -> String? {265        var parts = url.pathComponents.filter { $0 != "/" }266        if url.scheme == "immoka", let host = url.host(percentEncoded: false), !host.isEmpty { parts.insert(host, at: 0) }267        guard parts.count >= 2, parts[0] == "propriete" || parts[0] == "p" else { return nil }268        return url.scheme == "immoka" ? parts.dropFirst().joined(separator: "/") : parts[1]269    }270271    /// Identifiant de conversation porté par un lien `/compte/messages/{id}` ou `/pro/messages/{id}`, sinon nil.272    nonisolated static func conversationID(from url: URL) -> String? {273        var parts = url.pathComponents.filter { $0 != "/" }274        if url.scheme == "immoka", let host = url.host(percentEncoded: false), !host.isEmpty { parts.insert(host, at: 0) }275        guard parts.count == 3, parts[0] == "compte" || parts[0] == "pro", parts[1] == "messages", !parts[2].isEmpty else { return nil }276        return parts[2]277    }278279    /// Liens profonds : `immoka://propriete/<uid>`, `immoka://ville/<nom>`, `immoka://agence/<nom>`, `immoka://taux`280    /// et les liens universels équivalents de www.immo-ka.com.281    func handle(url: URL) {282        var parts = url.pathComponents.filter { $0 != "/" }283        if url.scheme == "immoka", let host = url.host(percentEncoded: false), !host.isEmpty { parts.insert(host, at: 0) }284        guard let first = parts.first else { return }285        let rest = parts.dropFirst().joined(separator: "/").removingPercentEncoding ?? parts.dropFirst().joined(separator: "/")286        let web = url.scheme == "https" || url.scheme == "http"287        switch first {288        // lien universel : /propriete/<uid>/<slug> — l'identifiant est le premier segment, le reste est décoratif289        case "propriete" where web && parts.count >= 2: open(.listing(parts[1]))290        case "propriete" where !rest.isEmpty, "p" where !rest.isEmpty: open(.listing(rest))291        case "a-vendre" where parts.count >= 2:292            open(.city(parts[1].contains("-") || parts[1] == parts[1].lowercased() ? parts[1].replacingOccurrences(of: "-", with: " ").capitalized : parts[1]))293        case "quartier" where parts.count >= 3: tab = .market; open(.neighborhood(slug: parts[2], city: parts[1]))294        case "quartier" where parts.count == 2: tab = .market; open(.neighborhood(slug: parts[1], city: nil))295        case "quartiers": tab = .market; open(.neighborhoods(city: nil, name: nil))296        case "comparer": tab = .favorites; open(.compare)297        case "vrai-prix": tab = .market; open(.vraiPrixGuide)298        case "indice": tab = .market299        case "villes": tab = .pros; open(.cities)300        // page d'un courtier : /courtier/<identifiant de l'annuaire>301        case "courtier" where parts.count >= 2 && parts[1].allSatisfy(\.isNumber) && !parts[1].isEmpty:302            tab = .pros; open(.broker(id: parts[1], name: ""))303        case "courtier": tab = .pros; open(.brokers)304        // compte et messagerie ; liens des courriels d'avis : /compte/messages/{id}, /pro/messages/{id} pour un courtier305        case "compte" where parts.count == 1: tab = .favorites; open(.account)306        case "compte" where parts.count == 2 && parts[1] == "messages", "pro" where parts.count == 2 && parts[1] == "messages":307            tab = .favorites; open(.messages)308        case "compte" where parts.count == 3 && parts[1] == "messages", "pro" where parts.count == 3 && parts[1] == "messages":309            guard let id = AppModel.conversationID(from: url) else { return }310            tab = .favorites; open(.conversation(id))311        case "inspecteurs": tab = .pros; open(.inspectors)312        case "demenageurs": tab = .pros; open(.movers)313        case "agence" where !rest.isEmpty: tab = .pros; open(.agency(rest))314        case "ville" where !rest.isEmpty:315            let name = rest.split(separator: "/").first.map(String.init) ?? rest316            // un slug (« trois-rivieres ») est rendu lisible ; un nom exact est gardé tel quel317            open(.city(name.contains("-") && name == name.lowercased() ? name.replacingOccurrences(of: "-", with: " ").capitalized : name))318        case "recherche", "carte":319            // critères portés par l'adresse (site, raccourcis, widgets) : mêmes noms que l'API v3320            let q = Dictionary((URLComponents(url: url, resolvingAgainstBaseURL: false)?.queryItems ?? []).compactMap { i in321                i.value.flatMap { $0.isEmpty ? nil : (i.name, $0) }322            }, uniquingKeysWith: { a, _ in a })323            var f = SearchFilters()324            f.city = q["city"]; f.sector = q["area"]; f.region = q["region"]; f.propertyType = q["type"]325            f.priceMin = q["price_min"].flatMap(Int.init); f.priceMax = q["price_max"].flatMap(Int.init)326            f.bedroomsMin = q["bedrooms_min"].flatMap(Int.init); f.nl = q["nl"]; f.text = q["q"]327            f.newDays = q["new_days"].flatMap(Int.init)328            if f.isEmpty { tab = .explore } else { explore(f) }329        case "courtiers", "agences": tab = .pros330        case "taux": tab = .market; open(.rates)331        // marché d'une ville (widget « Marché local ») : immoka://marche/<slug>332        case "marche" where parts.count >= 2:333            tab = .market334            open(.market(slug: parts[1], kind: "municipalite", name: parts[1].replacingOccurrences(of: "-", with: " ").capitalized))335        case "marche", "stats": tab = .market336        case "favoris": tab = .favorites337        default: break338        }339    }340}341
Files main
Menu

Theme