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/MapScreen.swift10// Description : carte MapKit des ventes, des estimations et des propriétés11// à vendre — regroupements, étiquettes de prix dont la12// pointe est le plomb, filtres, fiche d'aperçu.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 MapKit92import SwiftUI9394struct MapScreen: View {95 @Environment(AppModel.self) private var model96 @Environment(\.horizontalSizeClass) private var sizeClass97 @State private var map = MapModel()98 @State private var location = LocationProvider()99 @State private var position: MapCameraPosition = .region(MapScreen.start)100 @State private var showFilters = false101102 /// Départ : le centre de Montréal, à une échelle où les ventes s'affichent.103 static let start = MKCoordinateRegion(center: .init(latitude: 45.5231, longitude: -73.5817), span: .init(latitudeDelta: 0.006, longitudeDelta: 0.006))104105 var body: some View {106 @Bindable var map = map107 Map(position: $position) {108 ForEach(map.items) { item in109 Annotation("", coordinate: item.coordinate, anchor: item.count > 1 ? .center : .bottom) {110 marker(item)111 }112 .annotationTitles(.hidden)113 }114 ForEach(map.plaques) { m in115 if let lat = m.lat, let lng = m.lng {116 Annotation("", coordinate: .init(latitude: lat, longitude: lng), anchor: .center) { plaque(m) }117 .annotationTitles(.hidden)118 }119 }120 if let c = location.last {121 Annotation("Ma position", coordinate: c, anchor: .center) {122 Circle().fill(Theme.brand).frame(width: 14, height: 14).overlay(Circle().strokeBorder(Theme.ivory, lineWidth: 2.5))123 }124 .annotationTitles(.hidden)125 }126 }127 .mapStyle(.standard(pointsOfInterest: .excludingAll))128 .mapControls { MapCompass(); MapScaleView() }129 .onMapCameraChange(frequency: .onEnd) { ctx in130 let r = ctx.region131 map.regionChanged(MapBounds(west: r.center.longitude - r.span.longitudeDelta / 2, south: r.center.latitude - r.span.latitudeDelta / 2,132 east: r.center.longitude + r.span.longitudeDelta / 2, north: r.center.latitude + r.span.latitudeDelta / 2))133 }134 .safeAreaInset(edge: .top, spacing: 0) { topBar }135 .overlay(alignment: .bottom) { bottom }136 .overlay(alignment: .bottomTrailing) { if map.selection == nil { locateButton } }137 .toolbar(.hidden, for: .navigationBar)138 .sheet(isPresented: $showFilters) { MapFiltersSheet(map: map).presentationDetents([.medium, .large]) }139 .task { await map.loadMunicipalities() }140 .task {141 map.columns = sizeClass == .regular ? 10 : 6142 applyLaunchArguments()143 }144 .onChange(of: model.mapFocus) { _, f in focus(f) }145 .onAppear { focus(model.mapFocus) }146 .onChange(of: location.last?.latitude) { _, _ in147 if let c = location.last { withAnimation { position = .region(MKCoordinateRegion(center: c, span: .init(latitudeDelta: 0.02, longitudeDelta: 0.02))) } }148 }149 .alert("Position non autorisée", isPresented: Binding(get: { location.denied }, set: { location.denied = $0 })) {150 Button("D'accord", role: .cancel) {}151 } message: {152 Text("Autorisez la position pour Vrai-Prix dans Réglages pour centrer la carte autour de vous.")153 }154 }155156 private func focus(_ f: AppModel.MapFocus?) {157 guard let f else { return }158 map.layer = f.layer159 position = .region(MKCoordinateRegion(center: .init(latitude: f.lat, longitude: f.lng), span: .init(latitudeDelta: f.span, longitudeDelta: f.span)))160 model.mapFocus = nil161 }162163 /// Captures et tests : `-VPMap lat,lng,étendue`, `-VPLayer sales|units|listings`, `-VPSelect YES`, `-VPSheet mapfilters`.164 private func applyLaunchArguments() {165 let d = UserDefaults.standard166 if let l = d.string(forKey: "VPLayer"), let layer = MapLayer(rawValue: l) { map.layer = layer }167 if let m = d.string(forKey: "VPMap") {168 let p = m.split(separator: ",").compactMap { Double($0) }169 if p.count >= 2 { position = .region(MKCoordinateRegion(center: .init(latitude: p[0], longitude: p[1]), span: .init(latitudeDelta: p.count > 2 ? p[2] : 0.03, longitudeDelta: p.count > 2 ? p[2] : 0.03))) }170 }171 if model.launchSheet == "mapfilters" { showFilters = true }172 if d.bool(forKey: "VPSelect") {173 Task {174 for _ in 0..<40 {175 try? await Task.sleep(for: .milliseconds(400))176 if let first = map.items.compactMap({ i -> MapPoint? in if case .single(let p) = i.kind { return p }; return nil }).first {177 map.select(first); break178 }179 }180 }181 }182 }183184 // MARK: Marqueurs185186 @ViewBuilder187 private func marker(_ item: MapItem) -> some View {188 switch item.kind {189 case .single(let p):190 let selected = map.selection?.id == p.id191 Button { Haptics.select(); withAnimation(.easeOut(duration: 0.22)) { map.select(selected ? nil : p) } } label: {192 PriceMarker(text: Fmt.compact(p.amount), selected: selected)193 }194 .buttonStyle(.plain)195 .zIndex(selected ? 2 : 0)196 .accessibilityLabel("\(p.title), \(Fmt.money(p.amount))")197 .accessibilityIdentifier("map-marker")198 case .cluster(let count, let median):199 Button {200 withAnimation(.easeInOut(duration: 0.35)) { zoom(to: item.coordinate, factor: 0.42) }201 } label: {202 VStack(spacing: 1) {203 Text(Fmt.int(count)).font(.system(size: 13, weight: .bold)).monospacedDigit().foregroundStyle(Theme.bg)204 if let median { Text(Fmt.compact(median)).font(.system(size: 10, weight: .medium)).monospacedDigit().foregroundStyle(Theme.bg.opacity(0.8)) }205 }206 .padding(.horizontal, 8).frame(minWidth: 42, minHeight: 36)207 // regroupement : plaque charbon ; l'outremer reste au plomb et à la sélection208 .background(Theme.ink, in: RoundedRectangle(cornerRadius: 7, style: .continuous))209 .overlay(RoundedRectangle(cornerRadius: 7, style: .continuous).strokeBorder(Theme.bg.opacity(0.9), lineWidth: 1.5))210 .frame(minWidth: 44, minHeight: 44)211 }212 .buttonStyle(.plain)213 .accessibilityLabel("\(count) \(map.layer == .sales ? "ventes" : "propriétés")\(median.map { ", médiane \(Fmt.money($0))" } ?? ""). Toucher pour rapprocher.")214 }215 }216217 private func plaque(_ m: Municipality) -> some View {218 Button {219 if let lat = m.lat, let lng = m.lng {220 withAnimation(.easeInOut(duration: 0.45)) {221 position = .region(MKCoordinateRegion(center: .init(latitude: lat, longitude: lng), span: .init(latitudeDelta: 0.06, longitudeDelta: 0.06)))222 }223 }224 } label: {225 Text(m.nom).font(.system(size: 12, weight: .semibold)).foregroundStyle(Theme.ink).lineLimit(1)226 .padding(.horizontal, 8).frame(minHeight: 28)227 .background(Theme.surface, in: RoundedRectangle(cornerRadius: 6, style: .continuous))228 .overlay(RoundedRectangle(cornerRadius: 6, style: .continuous).strokeBorder(Theme.line2, lineWidth: 1))229 .frame(minHeight: 44)230 }231 .buttonStyle(.plain)232 .accessibilityLabel("\(m.nom). Toucher pour rapprocher.")233 }234235 private func zoom(to c: CLLocationCoordinate2D, factor: Double) {236 guard let r = position.region else {237 position = .region(MKCoordinateRegion(center: c, span: .init(latitudeDelta: 0.02, longitudeDelta: 0.02))); return238 }239 position = .region(MKCoordinateRegion(center: c, span: .init(latitudeDelta: max(0.002, r.span.latitudeDelta * factor), longitudeDelta: max(0.002, r.span.longitudeDelta * factor))))240 }241242 // MARK: Barres243244 private var topBar: some View {245 @Bindable var map = map246 return VStack(spacing: 8) {247 HStack(spacing: 8) {248 SlidingSegmented(selection: $map.layer, options: MapLayer.allCases.map { ($0, $0.label) }, label: "Couche de la carte")249 Button { showFilters = true } label: {250 HStack(spacing: 5) {251 Image(systemName: "slider.horizontal.3")252 if map.filters.activeCount > 0 { Text(String(map.filters.activeCount)).font(.footnote.weight(.bold)).monospacedDigit() }253 }254 .foregroundStyle(map.filters.activeCount > 0 ? Theme.brand : Theme.ink)255 .frame(minWidth: 44, minHeight: 42)256 .padding(.horizontal, 4)257 .background(Theme.surface2, in: RoundedRectangle(cornerRadius: Theme.radiusSmall, style: .continuous))258 }259 .buttonStyle(.plain)260 .accessibilityLabel("Filtres\(map.filters.activeCount > 0 ? ", \(map.filters.activeCount) actifs" : "")")261 .accessibilityIdentifier("map-filters")262 }263 HStack(spacing: 8) {264 if map.loading { ProgressView().controlSize(.mini) }265 Text(map.error.map { $0.isOffline ? "Hors ligne : la carte demande une connexion." : "Les points n'ont pas pu être chargés." } ?? map.status)266 .font(.footnote).num().foregroundStyle(map.error == nil ? Theme.ink2 : Theme.bad)267 .lineLimit(2).fixedSize(horizontal: false, vertical: true)268 Spacer(minLength: 0)269 }270 .accessibilityIdentifier("map-status")271 }272 .padding(.horizontal, Theme.margin).padding(.top, 8).padding(.bottom, 10)273 .frame(maxWidth: 620)274 .frame(maxWidth: .infinity)275 .background(Theme.bg)276 .overlay(alignment: .bottom) { Hairline(color: Theme.line2) }277 }278279 private var locateButton: some View {280 Button { location.request() } label: {281 Image(systemName: "location").font(.body.weight(.medium)).foregroundStyle(Theme.ink)282 .frame(width: 46, height: 46)283 .solidControl(RoundedRectangle(cornerRadius: Theme.radiusSmall, style: .continuous))284 }285 .buttonStyle(.plain)286 .padding(.trailing, Theme.margin).padding(.bottom, 18)287 .accessibilityLabel("Centrer sur ma position")288 }289290 @ViewBuilder291 private var bottom: some View {292 if let p = map.selection {293 MapPreviewCard(point: p) { withAnimation(.easeOut(duration: 0.2)) { map.select(nil) } }294 .padding(.horizontal, Theme.margin).padding(.bottom, 12)295 .frame(maxWidth: 460)296 .frame(maxWidth: .infinity, alignment: sizeClass == .regular ? .leading : .center)297 .transition(.move(edge: .bottom).combined(with: .opacity))298 }299 }300}301302/// Fiche d'aperçu d'un point de la carte.303struct MapPreviewCard: View {304 let point: MapPoint305 let close: () -> Void306 @Environment(AppModel.self) private var model307308 var body: some View {309 VStack(alignment: .leading, spacing: 10) {310 HStack(alignment: .top, spacing: 12) {311 if point.layer == .listings {312 RemoteImage(source: point.image, maxPixel: 300).frame(width: 84, height: 64)313 .clipShape(RoundedRectangle(cornerRadius: 8, style: .continuous))314 }315 VStack(alignment: .leading, spacing: 3) {316 Text(headline).eyebrowStyle()317 if let v = point.v3?.value, point.layer == .units {318 ValueView(value: v, size: .card)319 } else {320 Text(Fmt.money(point.amount)).font(.display(22)).num().foregroundStyle(Theme.ink)321 }322 Text(point.title).font(.subheadline).foregroundStyle(Theme.ink).lineLimit(2)323 Text(point.subtitle).font(.footnote).foregroundStyle(Theme.ink3).lineLimit(1)324 }325 Spacer(minLength: 0)326 Button(action: close) {327 Image(systemName: "xmark").font(.footnote.weight(.bold)).foregroundStyle(Theme.ink2).frame(width: 44, height: 44)328 }329 .buttonStyle(.plain)330 .accessibilityLabel("Fermer l'aperçu")331 .padding(.top, -10).padding(.trailing, -10)332 }333 if let x = point.v3 {334 if point.layer == .listings, let v = x.value, v.amounts != nil {335 HStack(spacing: 8) {336 PositionPlate(position: x.position, gapPct: x.gapPct, size: .line)337 Text("valeur " + (ValueFmt.amount(v) ?? "")).font(.footnote).num().foregroundStyle(Theme.ink3).lineLimit(1).minimumScaleFactor(0.8)338 }339 }340 if point.layer == .sales, x.marketSale == false { PlainTag(text: "Hors marché", tone: Theme.high, dashed: true) }341 if let note = point.note {342 Text(Fmt.capitalized(note)).font(.footnote).foregroundStyle(Theme.ink3).fixedSize(horizontal: false, vertical: true)343 }344 } else if let r = point.reading, point.layer != .units {345 HStack(spacing: 8) {346 VerdictTag(verdict: r.verdict, gapPct: r.gapPct)347 Text("valeur estimée " + Fmt.money(point.est)).font(.footnote).num().foregroundStyle(Theme.ink3).lineLimit(1).minimumScaleFactor(0.8)348 }349 } else if let note = point.note {350 Text(note).font(.footnote).foregroundStyle(Theme.ink3).fixedSize(horizontal: false, vertical: true)351 }352 if canOpen {353 Button(point.layer == .listings ? "Voir la propriété à vendre" : (point.v3?.saleID != nil ? "Voir cette vente" : (point.v3 != nil ? "Voir la fiche de cette propriété" : "Voir l'estimation de cette propriété")), action: open)354 .buttonStyle(PrimaryButtonStyle())355 .accessibilityIdentifier("map-open")356 }357 }358 .padding(14)359 .background(Theme.surface, in: RoundedRectangle(cornerRadius: Theme.radius, style: .continuous))360 .overlay(RoundedRectangle(cornerRadius: Theme.radius, style: .continuous).strokeBorder(Theme.line2, lineWidth: 1))361 .shadow(color: .black.opacity(0.14), radius: 14, y: 5)362 .accessibilityElement(children: .contain)363 }364365 private var headline: String {366 switch point.layer {367 case .sales: "Vendue le " + Fmt.day(point.date)368 case .units: point.v3?.value?.status == .ordre ? "Ordre de grandeur" : (point.v3 != nil && point.amount == nil ? "Propriété du rôle" : "Valeur estimée")369 case .listings: "Prix demandé"370 }371 }372373 private var canOpen: Bool { point.unitID != nil || point.v3?.saleID != nil }374375 private func open() {376 if let sale = point.v3?.saleID { model.open(.sale(sale)); return }377 guard let id = point.unitID else { return }378 if point.layer == .listings { model.openListing(id) } else { model.openProperty(id) }379 }380}381382struct MapFiltersSheet: View {383 @Bindable var map: MapModel384 @Environment(\.dismiss) private var dismiss385386 var body: some View {387 NavigationStack {388 ScrollView {389 VStack(alignment: .leading, spacing: 22) {390 if map.layer == .sales {391 group("Période") {392 SlidingSegmented(selection: $map.filters.months, options: MapFilters.periods.map { ($0.value, $0.label) }, label: "Période des ventes")393 }394 }395 group("Type de propriété") {396 FlowChips(options: MapFilters.types(for: map.layer), selection: $map.filters.type)397 }398 group(map.layer == .sales ? "Prix vendu" : (map.layer == .units ? "Valeur estimée" : "Prix demandé")) {399 PriceRangeFields(min: $map.filters.min, max: $map.filters.max)400 }401 Text("Les filtres de type et de prix s'appliquent aux points chargés dans la zone visible.")402 .font(.footnote).foregroundStyle(Theme.ink3)403 }404 .padding(Theme.margin)405 }406 .background(Theme.bg)407 .navigationTitle("Filtres")408 .navigationBarTitleDisplayMode(.inline)409 .toolbar {410 ToolbarItem(placement: .topBarLeading) {411 Button("Réinitialiser") { map.filters = MapFilters(months: map.filters.months) }.disabled(map.filters.activeCount == 0)412 }413 ToolbarItem(placement: .confirmationAction) { Button("Terminé") { dismiss() }.fontWeight(.semibold) }414 }415 }416 }417418 private func group<C: View>(_ title: String, @ViewBuilder _ content: () -> C) -> some View {419 VStack(alignment: .leading, spacing: 10) {420 Text(title).eyebrowStyle()421 content()422 }423 }424}425426/// Pastilles de choix unique qui passent à la ligne.427struct FlowChips: View {428 let options: [(key: String, label: String)]429 @Binding var selection: String430431 var body: some View {432 FlowLayout(spacing: 8) {433 ForEach(options, id: \.key) { o in434 FilterChip(label: o.label, active: selection == o.key) { selection = o.key }435 }436 }437 }438}439440/// Disposition en lignes qui passent à la ligne quand la largeur manque.441struct FlowLayout: Layout {442 var spacing: CGFloat = 8443444 func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize {445 arrange(proposal.width ?? .infinity, subviews).size446 }447448 func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) {449 let a = arrange(bounds.width, subviews)450 for (i, f) in a.frames.enumerated() {451 subviews[i].place(at: CGPoint(x: bounds.minX + f.minX, y: bounds.minY + f.minY), proposal: ProposedViewSize(f.size))452 }453 }454455 private func arrange(_ width: CGFloat, _ subviews: Subviews) -> (frames: [CGRect], size: CGSize) {456 var frames: [CGRect] = []457 var x: CGFloat = 0, y: CGFloat = 0, rowH: CGFloat = 0, maxX: CGFloat = 0458 for s in subviews {459 let sz = s.sizeThatFits(ProposedViewSize(width: width, height: nil))460 if x > 0, x + sz.width > width { x = 0; y += rowH + spacing; rowH = 0 }461 frames.append(CGRect(origin: CGPoint(x: x, y: y), size: sz))462 x += sz.width + spacing; rowH = max(rowH, sz.height); maxX = max(maxX, x - spacing)463 }464 return (frames, CGSize(width: maxX, height: y + rowH))465 }466}467468/// Deux champs de montant (minimum, maximum).469struct PriceRangeFields: View {470 @Binding var min: Double?471 @Binding var max: Double?472473 var body: some View {474 HStack(spacing: 10) {475 field("Minimum", $min)476 Text("à").font(.subheadline).foregroundStyle(Theme.ink3)477 field("Maximum", $max)478 }479 }480481 private func field(_ label: String, _ value: Binding<Double?>) -> some View {482 HStack(spacing: 4) {483 TextField(label, value: value, format: .number.grouping(.automatic).precision(.fractionLength(0)))484 .keyboardType(.numberPad)485 .font(.body).monospacedDigit()486 .accessibilityLabel(label + " en dollars")487 Text("$").font(.body).foregroundStyle(Theme.ink3)488 }489 .padding(.horizontal, 12)490 .frame(minHeight: 48)491 .background(Theme.surface, in: RoundedRectangle(cornerRadius: Theme.radiusSmall, style: .continuous))492 .overlay(RoundedRectangle(cornerRadius: Theme.radiusSmall, style: .continuous).strokeBorder(Theme.line2, lineWidth: 1))493 }494}495