SPB Git

Repository Public

AppModel.swift 15.3 KB 353 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : Lou-Ka iOS9// File             : LouKa/App/AppModel.swift10// Description      : état global — onglets, navigation, liens profonds, noms11//                    des sources, réglages.12// Module           : LouKa13// Repository       : https://git.spboucher.ai/lou-ka-ios-v314// Project Website  : https://www.lou-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, managers, market95}9697/// Destinations de navigation partagées par tous les onglets.98enum Route: Hashable, Sendable {99    case listing(String)100    case manager(String)101    case city(slug: String, name: String)102    case managers103    case cities104    case movers105    case compare106    case neighborhoods(city: String?)107    case neighborhood(slug: String, city: String?, name: String)108    case building(id: String)109    case marketPlace(slug: String, kind: String, name: String)110    case fairValueGuide111    case scoresGuide112    case about113    case privacy114    case terms115    case settings116    case account117    case messages118    case conversation(String)119}120121enum Appearance: String, CaseIterable, Identifiable, Sendable {122    case system, light, dark123    var id: String { rawValue }124    var label: String {125        switch self {126        case .system: "Selon le système"127        case .light: "Clair"128        case .dark: "Sombre"129        }130    }131    var scheme: ColorScheme? {132        switch self {133        case .system: nil134        case .light: .light135        case .dark: .dark136        }137    }138}139140@MainActor141@Observable142final class AppModel {143    var tab: AppTab = .discover144    var paths: [AppTab: NavigationPath] = [:]145    /// Recherche à appliquer à l'onglet Explorer (depuis l'accueil, une ville, une recherche enregistrée).146    var pendingSearch: PendingSearch?147    var toast: String?148    /// Feuille du compte (connexion, création) ; `accountStart` : étape ouverte d'emblée (captures).149    var accountSheet = false150    var accountStart: [AccountFlow.Step] = []151    /// Feuille de rédaction d'un message à un gestionnaire.152    var compose: ComposeTarget?153154    private(set) var sourceNames: [String: String] = [:]155156    var appearance: Appearance {157        didSet { UserDefaults.standard.set(appearance.rawValue, forKey: "appearance") }158    }159160    /// Pondérations personnelles du score de quartier (somme = 1).161    var scoreWeights: [String: Double] {162        didSet { UserDefaults.standard.set(scoreWeights, forKey: "scoreWeights") }163    }164165    /// Hypothèses de coût réel de l'utilisateur (coût réel, comparateur, rapports PDF).166    var costAssumptions: CostAssumptions = CostAssumptions.load() {167        didSet { costAssumptions.save() }168    }169170    struct PendingSearch: Equatable {171        var filters: SearchFilters172        var sort: SearchSort = .pertinence173        /// Phrase libre à faire interpréter par le serveur (raccourci Siri, Spotlight, lien).174        var phrase: String?175        var id = UUID()176    }177    /// Demande d'ouverture de la recherche (champ de l'accueil).178    var searchRequest: UUID?179180    init() {181        appearance = Appearance(rawValue: UserDefaults.standard.string(forKey: "appearance") ?? "") ?? .light182        let saved = UserDefaults.standard.dictionary(forKey: "scoreWeights") as? [String: Double]183        scoreWeights = (saved?.count == ScoreSet.defaultWeights.count ? saved : nil) ?? ScoreSet.defaultWeights184        // onglet de départ imposé par argument de lancement (tests, captures)185        if let t = UserDefaults.standard.string(forKey: "LKTab"), let tab = AppTab(rawValue: t) { self.tab = tab }186        // destination ouverte au lancement (tests, captures) : « logement/<uid> », « g/<id> », « ville/<slug> »187        if let o = UserDefaults.standard.string(forKey: "LKOpen"), let u = URL(string: "louka://" + (o.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? o)) {188            handle(url: u)189        }190        if let q = UserDefaults.standard.string(forKey: "LKPhrase") { explore(phrase: q) }191        if let c = UserDefaults.standard.string(forKey: "LKCity") {192            var f = SearchFilters(); f.city = c193            pendingSearch = PendingSearch(filters: f)194            tab = .explore195        }196        if let r = UserDefaults.standard.string(forKey: "LKRoute") {197            let map: [String: Route] = ["quartiers": .neighborhoods(city: nil), "compare": .compare, "cities": .cities, "movers": .movers, "fairvalue": .fairValueGuide,198                                        "scores": .scoresGuide, "about": .about, "privacy": .privacy, "terms": .terms, "settings": .settings, "account": .account, "messages": .messages]199            if let route = map[r] { open(route) }200        }201        #if DEBUG202        // -LKAccount signin|signup|code|forgot|reset : ouvre la feuille du compte à cette étape (captures d'écran)203        if let a = UserDefaults.standard.string(forKey: "LKAccount") {204            let demo = "lea.tremblay@exemple.com"205            let cell = AccountIdentifier.phone("418 555-0123")206            let steps: [String: [AccountFlow.Step]] = ["signin": [], "signup": [.signUp], "code": [.signUp, .code(.email(demo), display: demo)],207                                                       "forgot": [.forgot(.email, prefill: "")], "reset": [.forgot(.email, prefill: demo), .reset(.email(demo), display: demo)],208                                                       "code-sms": [.signUp, .code(cell, display: cell.display)], "forgot-sms": [.forgot(.phone, prefill: "")],209                                                       "reset-sms": [.forgot(.phone, prefill: "418 555-0123"), .reset(cell, display: cell.display)]]210            if let s = steps[a] { accountStart = s; accountSheet = true }211        }212        #endif213    }214215    func path(for tab: AppTab) -> Binding<NavigationPath> {216        Binding(get: { self.paths[tab] ?? NavigationPath() }, set: { self.paths[tab] = $0 })217    }218219    /// Ouvre une destination dans l'onglet courant.220    func open(_ route: Route) {221        var p = paths[tab] ?? NavigationPath()222        p.append(route)223        paths[tab] = p224    }225226    /// Lance une recherche dans l'onglet Explorer.227    func explore(_ filters: SearchFilters, sort: SearchSort = .pertinence) {228        pendingSearch = PendingSearch(filters: filters, sort: sort)229        paths[.explore] = NavigationPath()230        tab = .explore231    }232233    /// Lance une recherche par phrase libre dans l'onglet Explorer.234    func explore(phrase: String) {235        pendingSearch = PendingSearch(filters: SearchFilters(), phrase: phrase)236        paths[.explore] = NavigationPath()237        tab = .explore238    }239240    /// Ouvre la feuille de recherche de l'onglet Explorer.241    func requestSearch() {242        paths[.explore] = NavigationPath()243        tab = .explore244        searchRequest = UUID()245    }246247    func showToast(_ text: String) {248        toast = text249        Task { @MainActor in250            try? await Task.sleep(for: .seconds(2.4))251            if toast == text { toast = nil }252        }253    }254255    func sourceName(_ id: String) -> String { sourceNames[id] ?? Fmt.prettySource(id) }256257    func loadSourceNames() async {258        guard sourceNames.isEmpty else { return }259        if let names = try? await APIClient.shared.sourceNames() { sourceNames = names }260    }261262    /// Liens profonds `louka://…` et liens universels de www.lou-ka.com : mêmes chemins que le site263    /// (`/logement/<uid>`, `/recherche?…`, `/ville/<slug>`, `/quartier/<ville>/<quartier>`, `/immeuble/<id>`,264    /// `/g/<source>`, `/marche`, `/quartiers`, `/favoris`, `/comparer`, `/juste-valeur`, `/scores`).265    func handle(url: URL) {266        guard let link = DeepLink(url: url) else { return }267        switch link {268        case .listing(let uid): open(.listing(uid))269        case .manager(let id): open(.manager(id))270        case .city(let slug): open(.city(slug: slug, name: DeepLink.title(slug)))271        case .neighborhood(let city, let slug):272            if let slug { open(.neighborhood(slug: slug, city: city, name: DeepLink.title(slug))) }273            else { open(.neighborhood(slug: city, city: nil, name: DeepLink.title(city))) }274        case .building(let id): open(.building(id: id))275        case .search(let params, let phrase):276            if let phrase { explore(phrase: phrase) } else {277                var f = SearchFilters(); f.apply(params: params)278                let sort = params["sort"].flatMap { v in SearchSort.allCases.first { $0.apiValue == v } } ?? .pertinence279                explore(f, sort: sort)280            }281        case .tab(let t): tab = t282        case .route(let r, let t): tab = t; open(r)283        }284    }285}286287/// Destination décrite par une adresse (logique pure, testée).288enum DeepLink: Equatable {289    case listing(String)290    case manager(String)291    case city(String)292    case neighborhood(city: String, slug: String?)293    case building(String)294    case search(params: [String: String], phrase: String?)295    case tab(AppTab)296    case route(Route, AppTab)297298    static let hosts: Set<String> = ["www.lou-ka.com", "lou-ka.com"]299300    static func title(_ slug: String) -> String { slug.replacingOccurrences(of: "-", with: " ").capitalized }301302    init?(url: URL) {303        var parts = url.pathComponents.filter { $0 != "/" }304        if url.scheme == "louka" {305            if let host = url.host(percentEncoded: false), !host.isEmpty { parts.insert(host, at: 0) }306        } else if url.scheme == "https" || url.scheme == "http" {307            guard let h = url.host()?.lowercased(), DeepLink.hosts.contains(h) else { return nil }308        } else {309            return nil310        }311        guard let first = parts.first else { self = .tab(.discover); return }312        let rest = parts.dropFirst().joined(separator: "/").removingPercentEncoding ?? parts.dropFirst().joined(separator: "/")313        var params: [String: String] = [:]314        for item in URLComponents(url: url, resolvingAgainstBaseURL: false)?.queryItems ?? [] {315            if let v = item.value, !v.isEmpty { params[item.name] = v }316        }317        switch first {318        case "logement" where !rest.isEmpty: self = .listing(rest)319        case "g" where !rest.isEmpty: self = .manager(rest)320        case "ville" where !rest.isEmpty: self = .city(rest.split(separator: "/").first.map(String.init) ?? rest)321        case "quartier" where !rest.isEmpty:322            let seg = rest.split(separator: "/").map(String.init)323            self = .neighborhood(city: seg[0], slug: seg.count > 1 ? seg[1] : nil)324        case "immeuble" where !rest.isEmpty: self = .building(rest)325        case "recherche":326            let phrase = params.removeValue(forKey: "nl")327            self = .search(params: params, phrase: phrase)328        case "gestionnaires": self = .tab(.managers)329        case "marche" where !rest.isEmpty:330            self = .route(.marketPlace(slug: rest, kind: params["kind"] ?? "municipalite", name: DeepLink.title(rest)), .market)331        case "marche", "stats", "indice": self = .tab(.market)332        case "favoris", "espace": self = .tab(.favorites)333        case "compte" where rest.isEmpty: self = .route(.account, .favorites)334        // lien des courriels d'avis : /compte/messages/{id} ; /pro/messages/{id} pour un gestionnaire335        case "compte" where rest == "messages", "pro" where rest == "messages": self = .route(.messages, .favorites)336        case "compte" where rest.hasPrefix("messages/"), "pro" where rest.hasPrefix("messages/"):337            let id = String(rest.dropFirst("messages/".count))338            guard !id.isEmpty, !id.contains("/") else { return nil }339            self = .route(.conversation(id), .favorites)340        case "comparer": self = .route(.compare, .favorites)341        case "quartiers": self = .route(.neighborhoods(city: nil), .market)342        case "villes": self = .route(.cities, .managers)343        case "demenageurs": self = .route(.movers, .managers)344        case "juste-valeur": self = .route(.fairValueGuide, .market)345        case "scores", "ka-scores": self = .route(.scoresGuide, .market)346        case "a-propos": self = .route(.about, .market)347        case "confidentialite": self = .route(.privacy, .market)348        case "conditions": self = .route(.terms, .market)349        default: return nil350        }351    }352}353
Files main
Menu

Theme