Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : Vrai-Prix iOS9// File : VraiPrix/Features/Map/MapModel.swift10// Description : état de la carte — couche, filtres, chargement des points11// de la zone visible, regroupement hors du fil principal,12// plaques de municipalités aux petites échelles.13// Module : VraiPrix14// Repository : https://git.spboucher.ai/vrai-prix-ios-v315// Project Website : https://www.vrai-prix.com16// Created : 2026-11-2617// Last Modified : 2026-11-2818//19// =============================================================================20// AUTHOR & PROFESSIONAL AFFILIATION21// =============================================================================22//23// Author : Simon-Pierre Boucher24// Position : Professor of Finance25// Institution : Université du Québec en Outaouais (UQO)26// Department : Département des sciences administratives27// Organization : SP Boucher28//29// Website : https://spboucher.ai30// Git : https://git.spboucher.ai31//32// =============================================================================33// OFFICIAL CONTACT DIRECTORY34// =============================================================================35//36// General : info@spboucher.ai37// Professional : contact@spboucher.ai38// Direct : simon@spboucher.ai39// Research : research@spboucher.ai40// Development : dev@spboucher.ai41// Support : support@spboucher.ai42// Security/Admin : admin@spboucher.ai43// Notifications : notifications@spboucher.ai44//45// Preferred Contact: support@spboucher.ai46//47// =============================================================================48// COPYRIGHT & INTELLECTUAL PROPERTY49// =============================================================================50//51// Copyright (c) 202652// Simon-Pierre Boucher53//54// All rights reserved where applicable.55//56// This file is governed by the applicable project license,57// copyright notices, institutional agreements and relevant law.58//59// Unless expressly authorized by the applicable license or60// rights holder, copying, redistribution, sublicensing,61// publication and commercial exploitation are not permitted.62//63// Existing third-party rights and notices remain unaffected.64//65// =============================================================================66// CONFIDENTIALITY & SECURITY67// =============================================================================68//69// Classification : Public70// Distribution : Public repository; use is governed by the project license71// Security Contact : admin@spboucher.ai72//73// Access to this source does not independently grant permission74// to redistribute or disclose confidential materials.75//76// Do not embed credentials, private keys, access tokens,77// certificates or confidential personal information.78//79// =============================================================================80// LICENSE & MAINTENANCE81// =============================================================================82//83// License : None specified (no license file in this repository)84// Maintainer : Simon-Pierre Boucher85// Technical Contact: dev@spboucher.ai86//87// =============================================================================88// END OF SP BOUCHER SOURCE HEADER89// =============================================================================9091import CoreLocation92import MapKit93import Observation94import SwiftUI9596struct MapFilters: Equatable, Sendable {97 var months = 2498 var type = ""99 var min: Double?100 var max: Double?101102 static let periods: [(value: Int, label: String)] = [(6, "6 mois"), (12, "12 mois"), (24, "24 mois"), (60, "5 ans")]103104 static func types(for layer: MapLayer) -> [(key: String, label: String)] {105 switch layer {106 case .sales: SaleFilters.types107 case .units: [("", "Tous"), ("maison", "Maison"), ("condo", "Copropriété"), ("plex", "Plex"), ("immeuble", "Immeuble"), ("chalet", "Chalet"), ("terrain", "Terrain")]108 case .listings: ListingFilters.groups109 }110 }111112 var activeCount: Int { (type.isEmpty ? 0 : 1) + (min == nil ? 0 : 1) + (max == nil ? 0 : 1) }113114 func keeps(_ p: MapPoint) -> Bool {115 if !type.isEmpty, p.type != type { return false }116 if let min, (p.amount ?? 0) < min { return false }117 if let max, (p.amount ?? .infinity) > max { return false }118 return true119 }120}121122@MainActor123@Observable124final class MapModel {125 /// côté maximal d'une zone servie par /api/map126 static let maxSide = 0.5127128 var layer: MapLayer = .sales { didSet { if layer != oldValue { selection = nil; filters.type = ""; reset() } } }129 var filters = MapFilters() { didSet { if filters != oldValue { if filters.months != oldValue.months { reset() } else { recluster() } } } }130 var selection: MapPoint?131132 private(set) var items: [MapItem] = []133 private(set) var plaques: [Municipality] = []134 private(set) var loading = false135 private(set) var error: APIError?136 private(set) var truncated = false137 private(set) var visibleCount = 0138 /// la zone visible est trop grande pour servir des points : on montre les municipalités139 private(set) var zoomedOut = true140141 private var points: [MapPoint] = []142 private var fetched: (bounds: MapBounds, layer: MapLayer, months: Int, truncated: Bool)?143 private var bounds: MapBounds?144 private var municipalities: [Municipality] = []145 private var loadTask: Task<Void, Never>?146 private var clusterTask: Task<Void, Never>?147 var columns = 6148149 private func reset() {150 fetched = nil; points = []; items = []; visibleCount = 0151 if let b = bounds { regionChanged(b) }152 }153154 func regionChanged(_ b: MapBounds) {155 bounds = b156 zoomedOut = b.width > MapModel.maxSide || b.height > MapModel.maxSide157 if zoomedOut {158 loadTask?.cancel(); loading = false159 items = []; visibleCount = 0160 updatePlaques(b)161 return162 }163 plaques = []164 if let f = fetched, f.layer == layer, f.months == filters.months, f.bounds.contains(b), !f.truncated {165 recluster()166 return167 }168 recluster()169 loadTask?.cancel()170 let layer = layer, months = filters.months171 loadTask = Task {172 try? await Task.sleep(for: .milliseconds(280))173 if Task.isCancelled { return }174 loading = true175 defer { if !Task.isCancelled { loading = false } }176 // zone un peu plus large que l'écran : les petits déplacements ne rechargent rien177 let area = b.padded(0.25).clamped(maxSide: MapModel.maxSide)178 do {179 let (pts, cut) = try await MapModel.fetch(layer: layer, area: area, months: months)180 if Task.isCancelled { return }181 points = pts182 truncated = cut183 fetched = (area, layer, months, truncated)184 error = nil185 recluster()186 } catch is CancellationError {187 } catch {188 self.error = apiError(error)189 }190 }191 }192193 /// Points d'une emprise : par l'API v3 quand le service la sert (valeurs à régime, ventes qualifiées,194 /// inscriptions situées), sinon par `/api/map`.195 nonisolated private static func fetch(layer: MapLayer, area: MapBounds, months: Int) async throws -> ([MapPoint], Bool) {196 guard ServiceLevel.current == .v3 else {197 let r = try await APIClient.shared.mapPoints(layer: layer, bbox: area, months: layer == .sales ? months : nil,198 limit: layer == .units ? 900 : (layer == .sales ? 800 : 500))199 return (r.points, r.truncated ?? false)200 }201 switch layer {202 case .units:203 let r = try await APIClient.shared.v3Properties(bbox: area, limit: 900)204 return (r.items.map { MapPoint(v3: $0) }, r.truncated)205 case .sales:206 let r = try await APIClient.shared.v3Sales(bbox: area, months: min(months, 72), limit: 800)207 return (r.items.compactMap { MapPoint(v3: $0) }, r.truncated)208 case .listings:209 let r = try await APIClient.shared.v3Listings(bbox: area, limit: 500)210 return (r.items.compactMap { MapPoint(v3: $0) }, r.truncated)211 }212 }213214 private func recluster() {215 guard let b = bounds, !zoomedOut else { return }216 let pts = points.filter(filters.keeps), pinned = selection?.id, cols = columns217 clusterTask?.cancel()218 clusterTask = Task {219 let (out, n) = await Task.detached(priority: .userInitiated) {220 (Clusterer.cluster(pts, in: b, columns: cols, pinned: pinned), pts.filter { b.contains(lat: $0.lat, lng: $0.lng) }.count)221 }.value222 if Task.isCancelled { return }223 items = out224 visibleCount = n225 }226 }227228 func select(_ p: MapPoint?) {229 selection = p230 recluster()231 }232233 func loadMunicipalities() async {234 guard municipalities.isEmpty else { return }235 if let m = try? await APIClient.shared.municipalities() {236 municipalities = m237 if let b = bounds, zoomedOut { updatePlaques(b) }238 }239 }240241 /// Les plus grandes municipalités de la zone visible, sans chevauchement (grille grossière).242 private func updatePlaques(_ b: MapBounds) {243 var taken = Set<Int>()244 var out: [Municipality] = []245 let cw = b.width / 3, ch = b.height / 13246 for m in municipalities {247 guard let lat = m.lat, let lng = m.lng, b.contains(lat: lat, lng: lng) else { continue }248 let key = Int((lng - b.west) / cw) * 100 + Int((lat - b.south) / ch)249 if taken.insert(key).inserted { out.append(m) }250 if out.count >= 22 { break }251 }252 plaques = out253 }254255 var status: String {256 if zoomedOut { return "Rapprochez la carte pour voir les \(layer == .sales ? "ventes" : (layer == .units ? "estimations" : "propriétés à vendre"))." }257 let noun: String = switch layer {258 case .sales: visibleCount == 1 ? "vente" : "ventes"259 case .units: visibleCount == 1 ? "propriété" : "propriétés"260 case .listings: visibleCount == 1 ? "propriété à vendre" : "propriétés à vendre"261 }262 var s = "\(Fmt.int(visibleCount)) \(noun)"263 if layer == .sales { s += " · " + (MapFilters.periods.first { $0.value == filters.months }?.label ?? "") }264 if truncated { s += " · rapprochez pour tout voir" }265 return s266 }267}268269/// Position de l'appareil, demandée seulement au toucher du bouton. Elle ne quitte jamais l'appareil.270@MainActor271@Observable272final class LocationProvider: NSObject, CLLocationManagerDelegate {273 private let manager = CLLocationManager()274 var last: CLLocationCoordinate2D?275 var denied = false276 private var wanted = false277278 override init() {279 super.init()280 manager.delegate = self281 manager.desiredAccuracy = kCLLocationAccuracyHundredMeters282 }283284 func request() {285 wanted = true286 switch manager.authorizationStatus {287 case .notDetermined: manager.requestWhenInUseAuthorization()288 case .denied, .restricted: denied = true289 default: manager.requestLocation()290 }291 }292293 nonisolated func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) {294 let status = manager.authorizationStatus295 Task { @MainActor in296 if status == .denied || status == .restricted { self.denied = self.wanted }297 else if status != .notDetermined, self.wanted { self.manager.requestLocation() }298 }299 }300301 nonisolated func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {302 guard let c = locations.last?.coordinate else { return }303 Task { @MainActor in self.last = c; self.wanted = false }304 }305306 nonisolated func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {}307}308