Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : Vrai-Prix iOS9// File : VraiPrix/App/AppModel.swift10// Description : état global — onglets, navigation, liens profonds,11// réglages d'apparence, arguments de lancement.12// Module : VraiPrix13// Repository : https://git.spboucher.ai/vrai-prix-ios-v314// Project Website : https://www.vrai-prix.com15// Created : 2026-11-2616// Last Modified : 2026-11-2817//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 CoreLocation91import Observation92import SwiftUI9394enum AppTab: String, Hashable, CaseIterable, Sendable {95 case home, map, sales, market, library96}9798/// Destinations de navigation partagées par tous les onglets.99enum Route: Hashable, Sendable {100 case property(String)101 case listing(String)102 case municipality(String)103 case municipalities104 case registry(SaleFilters)105 case index106 case marketTest107 case listings(ListingFilters)108 case cost(id: String, title: String)109 case methodology110 case manual111 case compare112 case recents113 case settings114 case about115 case privacy116 case terms117 // --- écrans propres à l'API v3 ---118 case sale(String)119 case territory(String)120 case streetUnits(id: String, name: String)121 case indexSeries(territory: String, genre: String)122 case rankings123 case territories124 case listingsV3(ListingQuery)125 case registryV3(SaleQuery)126}127128enum Appearance: String, CaseIterable, Identifiable, Sendable {129 case system, light, dark130 var id: String { rawValue }131 var label: String {132 switch self {133 case .system: "Selon le système"134 case .light: "Clair"135 case .dark: "Sombre"136 }137 }138 var scheme: ColorScheme? {139 switch self {140 case .system: nil141 case .light: .light142 case .dark: .dark143 }144 }145}146147@MainActor148@Observable149final class AppModel {150 var tab: AppTab = .home151 var paths: [AppTab: NavigationPath] = [:]152 var toast: String?153 /// Demande de recentrage de la carte (depuis une fiche, une municipalité).154 var mapFocus: MapFocus?155 let motion: MotionCenter156 /// Ce que sert le service : l'app entière reste sur l'API 2 tant que la v3 n'est pas en production.157 private(set) var level: ServiceLevel = ServiceLevel.current158 var isV3: Bool { level == .v3 }159160 /// Sonde le service ; un changement de niveau ramène chaque onglet à sa racine (les écrans ne sont pas les mêmes).161 func refreshLevel() async {162 let l = await APIClient.shared.probeLevel()163 guard l != level else { return }164 level = l165 paths = [:]166 // un lien ouvert au lancement, avant la sonde, est rejoué sur les écrans du bon niveau167 if let r = replay, Date().timeIntervalSince(r.at) < 15 { handle(url: r.url, trigger: r.trigger) }168 }169 private var replay: (url: URL, trigger: PlumbTrigger, at: Date)?170171 struct MapFocus: Equatable {172 var lat: Double173 var lng: Double174 var layer: MapLayer175 /// étendue en degrés de latitude176 var span: Double = 0.012177 var id = UUID()178 }179180 var appearance: Appearance {181 didSet { UserDefaults.standard.set(appearance.rawValue, forKey: "appearance") }182 }183184 /// arguments de lancement utiles aux tests et aux captures185 let launchAnchor: String?186 let launchSheet: String?187 let launchQuery: String?188 /// recherche demandée par un raccourci ou un lien (`vraiprix://recherche?q=…`) ; l'onglet Estimer la consomme189 var pendingQuery: String?190191 init(motion: MotionCenter) {192 self.motion = motion193 let d = UserDefaults.standard194 appearance = Appearance(rawValue: d.string(forKey: "appearance") ?? "") ?? .system195 launchAnchor = d.string(forKey: "VPAnchor")196 launchSheet = d.string(forKey: "VPSheet")197 launchQuery = d.string(forKey: "VPQuery")198 if let t = d.string(forKey: "VPTab"), let tab = AppTab(rawValue: t) { self.tab = tab }199 // destination ouverte au lancement : « propriete/<id> », « a-vendre/<uid> », « municipalite/<slug> »200 if let o = d.string(forKey: "VPOpen"), let u = URL(string: "vraiprix://" + (o.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? o)) {201 // un geste demandé pour la capture (`-VPPlumb`, `-VPPlumbT`) joue même sur ce lien direct202 handle(url: u, trigger: (d.string(forKey: "VPPlumb") != nil || d.object(forKey: "VPPlumbT") != nil) ? .reveal : .direct)203 }204 if let r = d.string(forKey: "VPRoute") {205 let map: [String: Route] = ["rankings": .rankings, "territories": .territories, "listingsv3": .listingsV3(ListingQuery()),206 "indexv3": .indexSeries(territory: "qc", genre: "maison"),207 "municipalities": .municipalities, "registry": .registry(SaleFilters()), "index": .index,208 "markettest": .marketTest, "listings": .listings(ListingFilters()), "methodology": .methodology,209 "manual": .manual, "compare": .compare, "recents": .recents, "settings": .settings,210 "about": .about, "privacy": .privacy, "terms": .terms]211 if let route = map[r] { open(route) }212 }213 }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 /// Ouvre la fiche d'une unité ; `trigger` décide du geste d'aplomb.227 func openProperty(_ id: String, trigger: PlumbTrigger = .card) {228 motion.arm("unit:" + id, trigger)229 open(.property(id))230 }231232 func openListing(_ uid: String, trigger: PlumbTrigger = .card) {233 motion.arm("listing:" + uid, trigger)234 open(.listing(uid))235 }236237 func open(_ saved: SavedProperty) {238 switch saved.kind {239 case .unit: openProperty(saved.ref)240 case .listing: openListing(saved.ref)241 }242 }243244 /// Montre un lieu sur la carte.245 func showOnMap(lat: Double, lng: Double, layer: MapLayer = .sales, span: Double = 0.012) {246 mapFocus = MapFocus(lat: lat, lng: lng, layer: layer, span: span)247 paths[.map] = NavigationPath()248 tab = .map249 }250251 func showToast(_ text: String) {252 toast = text253 Task { @MainActor in254 try? await Task.sleep(for: .seconds(2.4))255 if toast == text { toast = nil }256 }257 }258259 /// Liens profonds : `vraiprix://propriete/<id>`, `vraiprix://a-vendre/<uid>`, `vraiprix://municipalite/<slug>`,260 /// et les chemins équivalents de www.vrai-prix.com (`/estimation/<id>`, `/a-vendre/<uid>`, `/municipalite/<slug>`).261 func handle(url: URL, trigger: PlumbTrigger = .direct) {262 replay = (url, trigger, .now)263 var parts = url.pathComponents.filter { $0 != "/" }264 if url.scheme == "vraiprix", let host = url.host(percentEncoded: false), !host.isEmpty { parts.insert(host, at: 0) }265 guard let first = parts.first else { return }266 let rest = parts.dropFirst().joined(separator: "/").removingPercentEncoding ?? parts.dropFirst().joined(separator: "/")267 switch first {268 case "estimation" where rest == "manuelle": tab = .home; open(.manual)269 case "propriete" where !rest.isEmpty, "estimation" where !rest.isEmpty: openProperty(rest, trigger: trigger)270 case "a-vendre" where !rest.isEmpty, "annonce" where !rest.isEmpty:271 // /a-vendre/{uid}/evaluer et /analyse-cout sont des pages du site : l'app ouvre la fiche de l'inscription272 let uid = rest.split(separator: "/").first.map(String.init) ?? rest273 openListing(uid.removingPercentEncoding ?? uid, trigger: trigger)274 case "recherche":275 tab = .home; paths[.home] = NavigationPath()276 pendingQuery = URLComponents(url: url, resolvingAgainstBaseURL: false)?.queryItems?.first { $0.name == "q" }?.value277 case "a-vendre": tab = .market; open(isV3 ? .listingsV3(ListingQuery()) : .listings(ListingFilters()))278 case "municipalite" where !rest.isEmpty:279 let slug = rest.split(separator: "/").first.map(String.init) ?? rest280 open(isV3 ? .territory(slug) : .municipality(slug))281 case "territoire" where !rest.isEmpty: tab = .market; if isV3 { open(.territory(rest)) }282 case "ventes" where !rest.isEmpty && isV3: tab = .sales; open(.sale(rest))283 case "comparer": tab = .library; open(.compare)284 case "estimation": tab = .home285 case "cout" where !rest.isEmpty: open(.cost(id: rest, title: "Propriété"))286 case "municipalites": tab = .market; open(.municipalities)287 case "ventes": tab = .sales288 case "carte": tab = .map289 case "stats", "marche": tab = .market290 case "methodologie": tab = .market; open(.methodology)291 case "favoris": tab = .library292 default: break293 }294 }295}296