Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : Vrai-Prix iOS9// File : VraiPrix/Features/V3/TerritoryV3.swift10// Description : territoires de l'API v3, de la province à la rue :11// portrait (parc, valeurs, ventes réelles, prix demandés,12// indice applicable et le territoire qui le porte), enfants,13// territoires proches ; unités d'une rue ; recherche et14// choix d'un territoire. Aucun quartier : il n'existe pas15// dans les données.16// Module : VraiPrix17// Repository : https://git.spboucher.ai/vrai-prix-ios-v318// Project Website : https://www.vrai-prix.com19// Created : 2026-11-2820// Last Modified : 2026-11-2821//22// =============================================================================23// AUTHOR & PROFESSIONAL AFFILIATION24// =============================================================================25//26// Author : Simon-Pierre Boucher27// Position : Professor of Finance28// Institution : Université du Québec en Outaouais (UQO)29// Department : Département des sciences administratives30// Organization : SP Boucher31//32// Website : https://spboucher.ai33// Git : https://git.spboucher.ai34//35// =============================================================================36// OFFICIAL CONTACT DIRECTORY37// =============================================================================38//39// General : info@spboucher.ai40// Professional : contact@spboucher.ai41// Direct : simon@spboucher.ai42// Research : research@spboucher.ai43// Development : dev@spboucher.ai44// Support : support@spboucher.ai45// Security/Admin : admin@spboucher.ai46// Notifications : notifications@spboucher.ai47//48// Preferred Contact: support@spboucher.ai49//50// =============================================================================51// COPYRIGHT & INTELLECTUAL PROPERTY52// =============================================================================53//54// Copyright (c) 202655// Simon-Pierre Boucher56//57// All rights reserved where applicable.58//59// This file is governed by the applicable project license,60// copyright notices, institutional agreements and relevant law.61//62// Unless expressly authorized by the applicable license or63// rights holder, copying, redistribution, sublicensing,64// publication and commercial exploitation are not permitted.65//66// Existing third-party rights and notices remain unaffected.67//68// =============================================================================69// CONFIDENTIALITY & SECURITY70// =============================================================================71//72// Classification : Public73// Distribution : Public repository; use is governed by the project license74// Security Contact : admin@spboucher.ai75//76// Access to this source does not independently grant permission77// to redistribute or disclose confidential materials.78//79// Do not embed credentials, private keys, access tokens,80// certificates or confidential personal information.81//82// =============================================================================83// LICENSE & MAINTENANCE84// =============================================================================85//86// License : None specified (no license file in this repository)87// Maintainer : Simon-Pierre Boucher88// Technical Contact: dev@spboucher.ai89//90// =============================================================================91// END OF SP BOUCHER SOURCE HEADER92// =============================================================================9394import SwiftUI9596struct TerritoryView: View {97 let id: String98 @Environment(AppModel.self) private var model99 @State private var state: Loadable<TerritoryV3> = .loading100101 var body: some View {102 ScrollView {103 Group {104 switch state {105 case .loading: LoadingState(label: "Chargement du portrait").padding(.top, 40)106 case .failed(let e): ErrorState(error: e, subject: "Ce territoire") { Task { await load(force: true) } }.padding(.top, 40)107 case .loaded(let t, let stale): content(t, stale: stale)108 }109 }110 .pageColumn()111 .padding(.bottom, 40)112 }113 .background(Theme.bg)114 .navigationTitle(state.value?.ref.title ?? "Territoire")115 .navigationBarTitleDisplayMode(.inline)116 .task { await load(force: false) }117 }118119 private func load(force: Bool) async {120 if state.value != nil, !force { return }121 do { let f = try await APIClient.shared.v3Territory(id); state = .loaded(f.value, stale: f.stale) }122 catch is CancellationError {}123 catch { state = .failed(apiError(error)) }124 }125126 @ViewBuilder127 private func content(_ t: TerritoryV3, stale: Bool) -> some View {128 let isStreet = t.ref.niveau == "rue"129 VStack(alignment: .leading, spacing: 0) {130 if stale { StaleNotice().padding(.top, 8) }131 // fil d'Ariane : les ancêtres, de la province au parent132 if !t.fil.isEmpty {133 ScrollView(.horizontal, showsIndicators: false) {134 HStack(spacing: 6) {135 ForEach(Array(t.fil.enumerated()), id: \.element.id) { i, a in136 if i > 0 { Image(systemName: "chevron.right").font(.caption2).foregroundStyle(Theme.ink3) }137 Button(a.title) { model.open(.territory(a.id)) }138 .font(.footnote.weight(.medium)).foregroundStyle(Theme.brand).frame(minHeight: 44)139 }140 }141 }142 .padding(.top, 2)143 }144 VStack(alignment: .leading, spacing: 5) {145 Text(t.niveauLibelle.map(Fmt.capitalized) ?? t.ref.levelLabel).eyebrowStyle()146 Text(t.ref.title).font(.editorial(28)).foregroundStyle(Theme.ink).fixedSize(horizontal: false, vertical: true)147 .accessibilityAddTraits(.isHeader).accessibilityIdentifier("territory-title")148 }149150 VStack(alignment: .leading, spacing: 26) {151 NatureBlock(title: "Valeurs estimées", nature: "estimations", period: t.valeursDate.map { "Valeurs fermes du modèle au \(Fmt.day($0))" }) {152 FigureGrid {153 Figure(label: "Propriétés à valeur ferme", value: Fmt.int(t.valeursN))154 Figure(label: "Valeur estimée médiane", value: t.valeursMediane.map { Fmt.money($0) } ?? "Effectif insuffisant",155 note: (t.valeursP25 != nil && t.valeursP75 != nil) ? "moitié centrale : \(Fmt.compact(t.valeursP25)) à \(Fmt.compact(t.valeursP75))" : nil)156 }157 genreRows(t.valeursParGenre, unit: "valeur médiane")158 }159 NatureBlock(title: "Ventes réelles", nature: "prix payés",160 period: (t.ventesDebut != nil && t.ventesFin != nil) ? "Du \(Fmt.day(t.ventesDebut, short: true)) au \(Fmt.day(t.ventesFin, short: true))" : nil) {161 FigureGrid {162 Figure(label: "Ventes, 12 mois", value: Fmt.int(t.ventesN))163 Figure(label: "Prix payé médian", value: t.ventesMedian.map { Fmt.money($0) } ?? "Effectif insuffisant")164 }165 genreRows(t.ventesParGenre, unit: "prix médian")166 }167 if let n = t.inscriptionsN, n > 0 {168 NatureBlock(title: "Prix demandés", nature: "inscriptions", period: "Inscriptions en ligne") {169 FigureGrid {170 Figure(label: "Inscriptions", value: Fmt.int(n))171 Figure(label: "Prix demandé médian", value: t.demandeMediane.map { Fmt.money($0) } ?? "Effectif insuffisant")172 }173 PositionShare(positions: t.positions)174 }175 }176 if !t.indice.isEmpty {177 NatureBlock(title: "Indice des prix de vente", nature: "prix payés", period: "Base 100 au début de 2021 ; variation sur un an") {178 ForEach(t.indice) { x in179 Button { model.open(.indexSeries(territory: t.ref.id, genre: x.genre)) } label: {180 HStack(alignment: .firstTextBaseline, spacing: 10) {181 VStack(alignment: .leading, spacing: 2) {182 Text(Genre.label(x.genre)).font(.subheadline.weight(.medium)).foregroundStyle(Theme.ink)183 if !x.propre, let p = x.territoire {184 Text("indice de \(p.title)").font(.caption).foregroundStyle(Theme.ink3)185 }186 }187 Spacer(minLength: 8)188 Text([x.valeur.map { Fmt.decimal($0, digits: 1) }, x.varAnPct.map { Fmt.pct($0) }].compactMap { $0 }.joined(separator: " · "))189 .font(.subheadline.weight(.semibold)).num().foregroundStyle(Theme.ink)190 Image(systemName: "chevron.right").font(.caption.weight(.semibold)).foregroundStyle(Theme.ink3)191 }192 .frame(minHeight: 44).contentShape(Rectangle())193 }194 .buttonStyle(.plain)195 }196 }197 }198 NatureBlock(title: "Parc immobilier", nature: "rôle", period: "Unités du rôle d'évaluation foncière") {199 FigureGrid {200 Figure(label: "Propriétés au rôle", value: Fmt.int(t.nbUnites))201 Figure(label: "Dans le champ du modèle", value: Fmt.int(t.nbChamp), note: t.horsChampPct.map { "\(Fmt.decimal($0, digits: 1)) % hors champ" })202 }203 ForEach(t.parc.prefix(8)) { g in FactRow(Fmt.capitalized(g.libelle), Fmt.int(g.n)) }204 }205 }206 .padding(.top, 20)207208 VStack(spacing: 0) {209 SectionHeader("Explorer").padding(.top, 32)210 Hairline().padding(.top, 8)211 if isStreet {212 NavRow(icon: .roleEvaluation, title: "Les propriétés de la rue", detail: t.nbUnites.map { "\(Fmt.int($0)) unités, par numéro civique" }) {213 model.open(.streetUnits(id: t.ref.id, name: t.ref.title))214 }215 .accessibilityIdentifier("street-units")216 } else {217 NavRow(icon: .venteConclue, title: "Ventes récentes", detail: "Le registre, pour ce territoire") {218 model.open(.registryV3(SaleQuery(place: t.ref.niveau == "municipalite" ? t.ref.nom : "", period: .d365)))219 }220 if t.ref.niveau == "municipalite" {221 NavRow(icon: .comparables, title: "Propriétés à vendre", detail: t.inscriptionsN.map { "\(Fmt.int($0)) inscriptions" }) {222 model.open(.listingsV3(ListingQuery(municipality: t.ref.nom)))223 }224 }225 }226 if let lat = t.lat, let lng = t.lng {227 NavRow(icon: .terrain, title: "Voir sur la carte", detail: "Valeurs, ventes, propriétés à vendre", divider: false) {228 model.showOnMap(lat: lat, lng: lng, layer: .units, span: isStreet ? 0.006 : 0.05)229 }230 }231 }232233 ForEach(t.enfants) { c in234 VStack(alignment: .leading, spacing: 0) {235 SectionHeader(childTitle(c.niveau), note: c.premiers.count < c.n ? "Les \(c.premiers.count) plus peuplés sur \(Fmt.int(c.n))." : nil).padding(.top, 32)236 ForEach(c.premiers.prefix(c.niveau == "rue" ? 12 : 20)) { x in237 NavRow(icon: c.niveau == "rue" ? .terrain : .municipalite, title: x.ref.title, detail: x.nbUnites.map { "\(Fmt.int($0)) propriétés" }) {238 model.open(.territory(x.ref.id))239 }240 }241 }242 }243244 if !t.proches.isEmpty {245 SectionHeader("Territoires proches", note: "Ceux dont le centre est le plus près : pas forcément limitrophes.").padding(.top, 32)246 ForEach(t.proches) { x in247 NavRow(icon: .municipalite, title: x.ref.title, detail: x.distanceKm.map { "à \(Fmt.decimal($0, digits: 1)) km" }) { model.open(.territory(x.ref.id)) }248 }249 }250 }251 }252253 private func childTitle(_ n: String) -> String {254 switch n {255 case "region": "Régions"256 case "mrc": "MRC"257 case "municipalite": "Municipalités"258 case "arrondissement": "Arrondissements"259 case "rue": "Rues"260 default: Fmt.capitalized(n)261 }262 }263264 @ViewBuilder265 private func genreRows(_ rows: [TerritoryV3.GenreRow], unit: String) -> some View {266 ForEach(rows.prefix(5)) { g in267 FactRow(label: Fmt.capitalized(g.libelle)) {268 Text(g.median.map { Fmt.money($0) } ?? "\(Fmt.int(g.n)) : effectif insuffisant")269 .font(.subheadline.weight(g.median == nil ? .regular : .semibold)).num()270 .foregroundStyle(g.median == nil ? Theme.ink3 : Theme.ink)271 }272 }273 }274}275276// MARK: - Unités d'une rue277278struct StreetUnitsView: View {279 let id: String280 let name: String281 @Environment(AppModel.self) private var model282 @State private var rows: [StreetUnitsV3.Unit] = []283 @State private var cursor: String?284 @State private var total: Int?285 @State private var loading = false286 @State private var error: APIError?287288 var body: some View {289 ScrollView {290 LazyVStack(alignment: .leading, spacing: 0) {291 Text((total.map { "\(Fmt.int($0)) propriétés" } ?? "Propriétés") + ", par numéro civique")292 .font(.subheadline.weight(.medium)).num().foregroundStyle(Theme.ink).padding(.bottom, 6)293 Hairline()294 if let error, rows.isEmpty {295 ErrorState(error: error, subject: "Cette rue") { Task { await load(reset: true) } }296 } else if rows.isEmpty {297 LoadingState(label: "Chargement de la rue")298 } else {299 ForEach(Array(rows.enumerated()), id: \.element.id) { i, u in300 Button { model.openProperty(u.id, trigger: .card) } label: {301 VStack(spacing: 0) {302 HStack(alignment: .center, spacing: 12) {303 VStack(alignment: .leading, spacing: 3) {304 Text(u.title).font(.subheadline.weight(.medium)).foregroundStyle(Theme.ink).multilineTextAlignment(.leading)305 Text([u.genreLibelle.map(Fmt.capitalized), u.ventePrix.map { "vendue \(Fmt.money($0))" + (u.venteDate.map { " en " + String($0.prefix(4)) } ?? "") }]306 .compactMap { $0 }.joined(separator: " · "))307 .font(.footnote).num().foregroundStyle(Theme.ink3)308 }309 Spacer(minLength: 8)310 ValueView(value: u.valeur, size: .line)311 Image(systemName: "chevron.right").font(.caption.weight(.semibold)).foregroundStyle(Theme.ink3)312 }313 .padding(.vertical, 11)314 Hairline()315 }316 .contentShape(Rectangle())317 }318 .buttonStyle(.plain)319 .accessibilityIdentifier("street-unit-\(i)")320 .onAppear { if i >= rows.count - 8 { Task { await load(reset: false) } } }321 }322 if cursor != nil { HStack { Spacer(); ProgressView(); Spacer() }.padding(.vertical, 18) }323 }324 }325 .pageColumn()326 .padding(.top, 6).padding(.bottom, 36)327 }328 .background(Theme.bg)329 .navigationTitle(name)330 .navigationBarTitleDisplayMode(.inline)331 .task { await load(reset: true) }332 }333334 private func load(reset: Bool) async {335 if loading { return }336 if !reset, cursor == nil { return }337 if reset, !rows.isEmpty { return }338 loading = true339 defer { loading = false }340 do {341 let r = try await APIClient.shared.v3StreetUnits(id, cursor: reset ? nil : cursor)342 let known = Set(rows.map(\.id))343 rows += r.items.filter { !known.contains($0.id) }344 cursor = r.nextCursor; total = r.total ?? total345 } catch is CancellationError {346 } catch { self.error = apiError(error) }347 }348}349350// MARK: - Recherche de territoires351352/// Liste et recherche de territoires : par niveau, ou par le début d'un nom.353struct TerritoriesView: View {354 @Environment(AppModel.self) private var model355 var body: some View {356 TerritorySearch(includeProvince: true) { model.open(.territory($0.id)) }357 .navigationTitle("Territoires")358 .navigationBarTitleDisplayMode(.inline)359 }360}361362/// Feuille de choix d'un territoire (onglet Marché).363struct TerritoryPicker: View {364 let pick: (TerritoryRef) -> Void365 @Environment(\.dismiss) private var dismiss366 var body: some View {367 NavigationStack {368 TerritorySearch(includeProvince: true) { pick($0); dismiss() }369 .navigationTitle("Choisir un territoire")370 .navigationBarTitleDisplayMode(.inline)371 .toolbar { ToolbarItem(placement: .cancellationAction) { Button("Fermer") { dismiss() } } }372 }373 }374}375376struct TerritorySearch: View {377 var includeProvince = false378 let pick: (TerritoryRef) -> Void379 @State private var level = "municipalite"380 @State private var text = ""381 @State private var rows: [TerritoryItemV3] = []382 @State private var loading = false383 @State private var failed = false384385 var body: some View {386 ScrollView {387 LazyVStack(alignment: .leading, spacing: 0) {388 HStack(spacing: 8) {389 Image(systemName: "magnifyingglass").foregroundStyle(Theme.ink3)390 TextField("Nom d'un territoire", text: $text)391 .textInputAutocapitalization(.words).autocorrectionDisabled()392 .accessibilityIdentifier("territory-search")393 if !text.isEmpty {394 Button { text = "" } label: { Image(systemName: "xmark.circle.fill").foregroundStyle(Theme.ink3).frame(width: 30, height: 44) }395 .buttonStyle(.plain).accessibilityLabel("Effacer")396 }397 }398 .padding(.horizontal, 12).frame(minHeight: 48)399 .background(Theme.surface, in: RoundedRectangle(cornerRadius: Theme.radiusSmall, style: .continuous))400 .overlay(RoundedRectangle(cornerRadius: Theme.radiusSmall, style: .continuous).strokeBorder(Theme.lineControl, lineWidth: 1))401 if text.trimmingCharacters(in: .whitespaces).count < 2 {402 SlidingSegmented(selection: $level, options: [("region", "Régions"), ("mrc", "MRC"), ("municipalite", "Villes"), ("arrondissement", "Arrond.")], label: "Niveau")403 .padding(.top, 12)404 }405 if failed, rows.isEmpty {406 EmptyState(title: "Chargement impossible", message: "La liste des territoires n'a pas pu être chargée. Réessayez dans un instant.")407 } else if rows.isEmpty, loading {408 LoadingState(label: "Chargement des territoires")409 } else if rows.isEmpty {410 EmptyState(title: "Aucun territoire de ce nom", message: "Les quartiers n'existent pas dans les données : cherchez une municipalité, un arrondissement, une MRC ou une région. Une rue se cherche par l'onglet Estimer.")411 } else {412 if includeProvince, text.isEmpty, level == "region" {413 row(title: "Québec", detail: "Province", id: "qc") { pick(TerritoryRef(json: .object(["id": .string("qc"), "niveau": .string("province"), "nom": .string("Québec")]))) }414 }415 ForEach(rows) { t in416 row(title: t.ref.title, detail: [t.ref.levelLabel, t.nbUnites.map { "\(Fmt.int($0)) propriétés" }].compactMap { $0 }.joined(separator: " · "), id: t.ref.id) { pick(t.ref) }417 }418 }419 }420 .pageColumn()421 .padding(.top, 8).padding(.bottom, 32)422 }423 .background(Theme.bg)424 .task(id: level + "|" + text) {425 let q = text.trimmingCharacters(in: .whitespaces)426 if !q.isEmpty { try? await Task.sleep(for: .milliseconds(280)) }427 if Task.isCancelled { return }428 loading = true; failed = false429 defer { loading = false }430 do {431 let r = q.count >= 2 ? try await APIClient.shared.v3Territories(q: q, limit: 40)432 : try await APIClient.shared.v3Territories(level: level, limit: level == "municipalite" ? 120 : 100)433 if !Task.isCancelled { rows = r.items }434 } catch is CancellationError {435 } catch { rows = []; failed = true }436 }437 }438439 private func row(title: String, detail: String, id: String, action: @escaping () -> Void) -> some View {440 Button(action: action) {441 VStack(spacing: 0) {442 HStack {443 VStack(alignment: .leading, spacing: 2) {444 Text(title).font(.body).foregroundStyle(Theme.ink).multilineTextAlignment(.leading)445 Text(detail).font(.footnote).num().foregroundStyle(Theme.ink3)446 }447 Spacer(minLength: 8)448 Image(systemName: "chevron.right").font(.footnote.weight(.semibold)).foregroundStyle(Theme.ink3)449 }450 .padding(.vertical, 12).frame(minHeight: 52)451 Hairline()452 }453 .contentShape(Rectangle())454 }455 .buttonStyle(.plain)456 .accessibilityIdentifier("territory-row-" + id)457 }458}459