Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : Immo-Ka iOS9// File : ImmoKa/Features/Market/MarketView.swift10// Description : marché — chiffres clés, taux hypothécaires du jour,11// inscriptions par jour, prix médian des nouvelles12// inscriptions, répartition des prix et des types, vrai13// prix, villes (Swift Charts).14// Module : ImmoKa15// Repository : https://git.spboucher.ai/immo-ka-ios-v316// Project Website : https://www.immo-ka.com17// Created : 2026-11-2518// Last Modified : 2026-11-2819//20// =============================================================================21// AUTHOR & PROFESSIONAL AFFILIATION22// =============================================================================23//24// Author : Simon-Pierre Boucher25// Position : Professor of Finance26// Institution : Université du Québec en Outaouais (UQO)27// Department : Département des sciences administratives28// Organization : SP Boucher29//30// Website : https://spboucher.ai31// Git : https://git.spboucher.ai32//33// =============================================================================34// OFFICIAL CONTACT DIRECTORY35// =============================================================================36//37// General : info@spboucher.ai38// Professional : contact@spboucher.ai39// Direct : simon@spboucher.ai40// Research : research@spboucher.ai41// Development : dev@spboucher.ai42// Support : support@spboucher.ai43// Security/Admin : admin@spboucher.ai44// Notifications : notifications@spboucher.ai45//46// Preferred Contact: support@spboucher.ai47//48// =============================================================================49// COPYRIGHT & INTELLECTUAL PROPERTY50// =============================================================================51//52// Copyright (c) 202653// Simon-Pierre Boucher54//55// All rights reserved where applicable.56//57// This file is governed by the applicable project license,58// copyright notices, institutional agreements and relevant law.59//60// Unless expressly authorized by the applicable license or61// rights holder, copying, redistribution, sublicensing,62// publication and commercial exploitation are not permitted.63//64// Existing third-party rights and notices remain unaffected.65//66// =============================================================================67// CONFIDENTIALITY & SECURITY68// =============================================================================69//70// Classification : Public71// Distribution : Public repository; use is governed by the project license72// Security Contact : admin@spboucher.ai73//74// Access to this source does not independently grant permission75// to redistribute or disclose confidential materials.76//77// Do not embed credentials, private keys, access tokens,78// certificates or confidential personal information.79//80// =============================================================================81// LICENSE & MAINTENANCE82// =============================================================================83//84// License : None specified (no license file in this repository)85// Maintainer : Simon-Pierre Boucher86// Technical Contact: dev@spboucher.ai87//88// =============================================================================89// END OF SP BOUCHER SOURCE HEADER90// =============================================================================9192import Charts93import SwiftUI9495struct MarketView: View {96 @Environment(AppModel.self) private var app97 @State private var dash: Dashboard?98 @State private var stats: GlobalStats?99 @State private var best: MortgageBest?100 @State private var shares: VerdictShares?101 @State private var error: Error?102 @State private var drawLine: Double = 0103 @State private var drawBars: Double = 0104 @State private var drawPrice: Double = 0105 @State private var drawTypes: Double = 0106 @State private var flow = "nouvelles"107 /// v3 : portrait de marché servi par `/api/v3/market` (prix demandés et ventes réelles, jamais confondus)108 @State private var v3 = MarketV3Model()109 @State private var usesV3 = ServiceGeneration.current >= 3110 @State private var pickPlace = false111112 var body: some View {113 ScrollViewReader { proxy in114 ScrollView {115 LazyVStack(alignment: .leading, spacing: 32) {116 if usesV3 {117 Button { pickPlace = true } label: {118 HStack(spacing: 6) {119 Text(v3.place?.name ?? "Tout le Québec").font(.editorial(26)).foregroundStyle(Theme.ink)120 Image(systemName: "chevron.down").font(.footnote.weight(.bold)).foregroundStyle(Theme.ink3)121 }122 }123 .buttonStyle(.plain)124 .accessibilityLabel("Marché de \(v3.place?.name ?? "tout le Québec"). Changer de lieu")125 .accessibilityIdentifier("market.place")126 MarketPortraitView(model: v3)127 ratesTeaser128 vraiPrix.id("vraiprix")129 NavigationLink(value: Route.neighborhoods(city: nil, name: nil)) {130 HStack {131 VStack(alignment: .leading, spacing: 4) {132 Text("Quartiers et villes").font(.editorial(20)).foregroundStyle(Theme.ink)133 Text("Prix demandés, ventes réelles, parc immobilier, services et transport, lieu par lieu.")134 .font(.footnote).foregroundStyle(Theme.ink2).multilineTextAlignment(.leading)135 }136 Spacer(minLength: 8)137 Image(systemName: "chevron.right").font(.footnote.weight(.semibold)).foregroundStyle(Theme.ink3)138 }139 .cardStyle(padding: 16)140 }141 .buttonStyle(.plain)142 .accessibilityIdentifier("market.neighborhoods")143 } else if let d = dash {144 numbers(d)145 ratesTeaser146 activity(d).id("activity")147 medianPrice(d).id("median")148 priceDistribution(d).id("prices")149 types(d).id("types")150 vraiPrix.id("vraiprix")151 cities(d).id("cities")152 } else if let error {153 ErrorStateView(error: error) { Task { await load() } }154 ratesTeaser155 } else {156 Skeleton(height: 130, radius: Theme.radius)157 Skeleton(height: 220, radius: Theme.radius)158 Skeleton(height: 220, radius: Theme.radius)159 }160 guides161 }162 .padding(.horizontal, 20).padding(.bottom, 30)163 .frame(maxWidth: 760)164 .frame(maxWidth: .infinity)165 }166 .background(Theme.bg)167 .navigationTitle("Marché")168 .toolbar {169 ToolbarItem(placement: .topBarTrailing) {170 NavigationLink(value: Route.settings) { Image(systemName: "gearshape") }.accessibilityLabel("Réglages")171 }172 }173 .refreshable { await load() }174 .sheet(isPresented: $pickPlace) { MarketPlacePicker(current: v3.place) { v3.select($0) } }175 .task {176 usesV3 = await APIClient.shared.isV3()177 if usesV3 ? v3.portrait == nil : dash == nil { await load() }178 // ancre de départ imposée par argument de lancement (captures d'écran des graphiques)179 guard let anchor = UserDefaults.standard.string(forKey: "IKAnchor") else { return }180 try? await Task.sleep(for: .seconds(1.0))181 proxy.scrollTo(anchor, anchor: .top)182 }183 }184 }185186 private func load() async {187 error = nil188 if usesV3 {189 async let b = try? APIClient.shared.mortgageBest()190 async let sh = try? APIClient.shared.verdictShares()191 await v3.load(force: true)192 best = await b ?? best193 shares = await sh ?? shares194 return195 }196 async let s = try? APIClient.shared.stats()197 async let b = try? APIClient.shared.mortgageBest()198 do { dash = try await APIClient.shared.dashboard() } catch is CancellationError {} catch { if dash == nil { self.error = error } }199 stats = await s ?? stats200 best = await b ?? best201 shares = (try? await APIClient.shared.verdictShares()) ?? shares202 }203204 // MARK: Chiffres clés205206 private func numbers(_ d: Dashboard) -> some View {207 VStack(alignment: .leading, spacing: 16) {208 Text("Calculé sur les inscriptions en ligne, toutes sources confondues\(d.periodLabel.map { " ; variations sur \($0)" } ?? "").")209 .font(.subheadline).foregroundStyle(Theme.ink2).fixedSize(horizontal: false, vertical: true)210 LazyVGrid(columns: [GridItem(.flexible(), spacing: 16, alignment: .topLeading), GridItem(.flexible(), spacing: 16, alignment: .topLeading)], spacing: 20) {211 if let k = d.kpi("prix_median") { StatTile(value: Fmt.money(k.value), label: "Prix médian demandé") }212 if let k = d.kpi("actives") { StatTile(value: Fmt.int(k.value), label: "Propriétés en ligne", hint: delta(k)) }213 if let k = d.kpi("prix_pi2") { StatTile(value: "\(Fmt.int(k.value)) $", label: "Prix médian au pi²") }214 if let k = d.kpi("jours_marche") { StatTile(value: "\(Fmt.int(k.value)) j", label: "Jours sur le marché (médiane)") }215 if let k = d.kpi("nouvelles") { StatTile(value: Fmt.int(k.value), label: "Nouvelles inscriptions", hint: delta(k)) }216 if let k = d.kpi("baisses_prix") { StatTile(value: Fmt.int(k.value), label: "Baisses de prix observées") }217 }218 .padding(.vertical, 16)219 .overlay(alignment: .top) { Divider().overlay(Theme.line) }220 .overlay(alignment: .bottom) { Divider().overlay(Theme.line) }221 }222 .accessibilityIdentifier("market.numbers")223 }224225 private func delta(_ k: Dashboard.KPI) -> String? {226 k.deltaPct.map { "\($0 > 0 ? "+" : "−")\(Fmt.decimal(abs($0))) % sur la période" }227 }228229 // MARK: Taux230231 private var ratesTeaser: some View {232 NavigationLink(value: Route.rates) {233 HStack(alignment: .center, spacing: 16) {234 VStack(alignment: .leading, spacing: 4) {235 Text("Taux hypothécaires").font(.editorial(20)).foregroundStyle(Theme.ink)236 if let b = best?.best {237 Text("Meilleur taux fixe 5 ans : \(b.institution)\(b.medianRate.map { " · médiane \(Fmt.rate($0))" } ?? "")")238 .font(.footnote).num().foregroundStyle(Theme.ink2).multilineTextAlignment(.leading)239 } else {240 Text("Meilleurs taux du jour, historique et calculateur.").font(.footnote).foregroundStyle(Theme.ink2)241 }242 }243 Spacer(minLength: 8)244 if let b = best?.best {245 Text(Fmt.rate(b.rate)).font(.display(26, weight: .semibold)).num().foregroundStyle(Theme.ink)246 }247 Image(systemName: "chevron.right").font(.footnote.weight(.semibold)).foregroundStyle(Theme.ink3)248 }249 .cardStyle(padding: 16)250 }251 .buttonStyle(.plain)252 .accessibilityIdentifier("market.rates")253 }254255 // MARK: Activité256257 @ViewBuilder258 private func activity(_ d: Dashboard) -> some View {259 if let news = d.serie("nouvelles"), let out = d.serie("retraits"), news.points.count > 3 {260 let s = flow == "nouvelles" ? news : out261 VStack(alignment: .leading, spacing: 14) {262 SectionHeader(title: "Le marché, jour après jour") {263 SlidingSegmented(selection: $flow, options: [("nouvelles", "Nouvelles"), ("retraits", "Retirées")], label: "Série affichée")264 }265 Chart(s.points) { p in266 if let date = p.date {267 BarMark(x: .value("Jour", date, unit: .day), y: .value("Inscriptions", p.v * drawBars))268 .foregroundStyle(flow == "nouvelles" ? Theme.brand : Theme.ink3)269 .cornerRadius(1.5)270 }271 }272 .chartYAxis { AxisMarks(position: .leading, values: .automatic(desiredCount: 4)) { _ in AxisGridLine().foregroundStyle(Theme.line); AxisValueLabel().font(.caption2) } }273 .chartXAxis { dateAxis }274 .frame(height: 190)275 .drawOnAppear($drawBars, duration: 0.8)276 .animation(.snappy, value: flow)277 .accessibilityLabel(flow == "nouvelles" ? "Nouvelles inscriptions par jour" : "Inscriptions retirées ou vendues par jour")278 Text(flow == "nouvelles" ? "Inscriptions repérées chaque jour." : "Inscriptions disparues des sources chaque jour : vendues ou retirées.")279 .font(.caption).foregroundStyle(Theme.ink3)280 }281 }282 }283284 private var dateAxis: some AxisContent {285 AxisMarks(values: .stride(by: .day, count: 7)) { _ in286 AxisGridLine().foregroundStyle(Theme.line)287 AxisValueLabel(format: .dateTime.day().month(.abbreviated).locale(Fmt.locale)).font(.caption2)288 }289 }290291 @ViewBuilder292 private func medianPrice(_ d: Dashboard) -> some View {293 if let s = d.serie("prix_median_nouvelles"), s.points.count > 3 {294 let values = s.points.map(\.v)295 let lo = (values.min() ?? 0) * 0.97, hi = (values.max() ?? 1) * 1.03296 let mid = values.reduce(0, +) / Double(values.count)297 VStack(alignment: .leading, spacing: 14) {298 SectionHeader(title: "Prix médian des nouvelles inscriptions", subtitle: "Ce que demandent les vendeurs qui arrivent sur le marché.")299 Chart(s.points) { p in300 if let date = p.date {301 // le tracé part de la moyenne et prend sa forme302 LineMark(x: .value("Jour", date), y: .value("Prix", mid + (p.v - mid) * drawLine))303 .foregroundStyle(Theme.brand).lineStyle(StrokeStyle(lineWidth: 2, lineJoin: .round))304 .interpolationMethod(.monotone)305 }306 }307 .chartYScale(domain: lo...hi)308 .chartYAxis {309 AxisMarks(position: .leading, values: .automatic(desiredCount: 4)) { v in310 AxisGridLine().foregroundStyle(Theme.line)311 AxisValueLabel { if let x = v.as(Double.self) { Text(Fmt.compactMoney(x)).font(.caption2).monospacedDigit() } }312 }313 }314 .chartXAxis { dateAxis }315 .frame(height: 190)316 .drawOnAppear($drawLine, duration: 1.0)317 .accessibilityLabel("Prix médian des nouvelles inscriptions, de \(Fmt.money(values.first)) à \(Fmt.money(values.last))")318 }319 }320 }321322 // MARK: Répartitions323324 @ViewBuilder325 private func priceDistribution(_ d: Dashboard) -> some View {326 if let b = d.distribution("prix") ?? d.breakdown("prix"), b.items.count > 2 {327 VStack(alignment: .leading, spacing: 14) {328 SectionHeader(title: "Combien coûtent les propriétés", subtitle: "Inscriptions en ligne par tranche de prix demandé.")329 Chart(b.items) { i in330 BarMark(x: .value("Tranche", short(i.label)), y: .value("Inscriptions", i.value * drawPrice))331 .foregroundStyle(Theme.brand).cornerRadius(2)332 }333 .chartXScale(domain: b.items.map { short($0.label) })334 .chartXAxis { AxisMarks { _ in AxisValueLabel(orientation: .verticalReversed).font(.system(size: 9)) } }335 .chartYAxis { AxisMarks(position: .leading, values: .automatic(desiredCount: 4)) { _ in AxisGridLine().foregroundStyle(Theme.line); AxisValueLabel().font(.caption2) } }336 .frame(height: 230)337 .drawOnAppear($drawPrice, duration: 0.9)338 .accessibilityLabel("Répartition des propriétés par tranche de prix")339 }340 }341 }342343 /// « 200–300 k$ » → « 200–300 k » (étiquettes d'axe compactes)344 private func short(_ label: String) -> String {345 label.replacingOccurrences(of: " k$", with: " k").replacingOccurrences(of: "k$", with: "k").replacingOccurrences(of: " M$", with: " M").replacingOccurrences(of: "M$", with: "M")346 }347348 @ViewBuilder349 private func types(_ d: Dashboard) -> some View {350 if let b = d.breakdown("types"), !b.items.isEmpty {351 let rows = Array(b.items.filter { !PropertyKind.normalize($0.label).isEmpty }.prefix(8))352 let top = rows.map(\.value).max() ?? 1353 VStack(alignment: .leading, spacing: 14) {354 SectionHeader(title: "Types de propriété")355 Chart(rows) { i in356 BarMark(x: .value("Inscriptions", i.value * drawTypes), y: .value("Type", i.label))357 .foregroundStyle(Theme.brand).cornerRadius(2)358 .annotation(position: .trailing) { Text(Fmt.int(i.value)).font(.caption2.weight(.semibold)).num().foregroundStyle(Theme.ink2) }359 }360 .chartYScale(domain: rows.map(\.label))361 .chartXScale(domain: 0...(top * 1.2))362 .chartXAxis(.hidden)363 .chartYAxis { AxisMarks { _ in AxisValueLabel().font(.caption.weight(.medium)) } }364 .frame(height: CGFloat(rows.count) * 32 + 10)365 .drawOnAppear($drawTypes, duration: 0.8)366 .accessibilityLabel("Inscriptions par type de propriété")367 }368 }369 }370371 @ViewBuilder372 private var vraiPrix: some View {373 if let v = shares {374 VStack(alignment: .leading, spacing: 14) {375 SectionHeader(title: "Prix demandés et prix de vente attendus", subtitle: v.sentence) {376 NavigationLink(value: Route.vraiPrixGuide) { Image(systemName: "info.circle").foregroundStyle(Theme.ink3) }377 .accessibilityLabel("La méthode du prix de vente attendu")378 }379 VerdictShareBar(shares: v)380 let rows = (stats?.bannieres ?? []).filter { $0.n >= 200 }.sorted { $0.median < $1.median }.prefix(6)381 if !rows.isEmpty {382 VStack(alignment: .leading, spacing: 4) {383 Text("Écart médian par bannière").font(.caption.weight(.semibold)).foregroundStyle(Theme.ink3)384 RowList(rows: rows.map { ($0.banniere, "\($0.median > 0 ? "+" : "−")\(Fmt.decimal(abs($0.median))) %") })385 }386 }387 }388 }389 }390391 @ViewBuilder392 private func cities(_ d: Dashboard) -> some View {393 if let t = d.table("top_villes"), !t.rows.isEmpty {394 VStack(alignment: .leading, spacing: 4) {395 SectionHeader(title: "Villes") {396 Button("Toutes") { app.open(.cities) }.font(.subheadline.weight(.semibold))397 }398 .padding(.bottom, 6)399 ForEach(Array(t.rows.prefix(8).enumerated()), id: \.offset) { _, row in400 if row.count >= 4, Fmt.isPlausibleCity(row[0]) {401 Button { app.open(.city(row[0])) } label: {402 VStack(spacing: 0) {403 HStack(alignment: .firstTextBaseline) {404 Text(row[0]).font(.editorial(18)).foregroundStyle(Theme.ink)405 Spacer()406 Text(row[1]).font(.footnote).num().foregroundStyle(Theme.ink3)407 Text(row[3]).font(.subheadline.weight(.semibold)).num().foregroundStyle(Theme.ink).frame(minWidth: 96, alignment: .trailing)408 }409 .padding(.vertical, 12)410 Divider().overlay(Theme.line)411 }412 .contentShape(Rectangle())413 }414 .buttonStyle(.plain)415 .accessibilityLabel("\(row[0]), \(row[1]) propriétés, prix médian \(row[3])")416 }417 }418 }419 }420 }421422 // MARK: Guides et réglages423424 private var guides: some View {425 VStack(alignment: .leading, spacing: 0) {426 SectionHeader(title: "Comprendre et régler").padding(.bottom, 6)427 guide(.calculator, "Calculateur d'achat", "Versement, assurance prêt, droits de mutation", "function")428 guide(.vraiPrixGuide, "La méthode du prix de vente attendu", "D'après les ventes réelles, avec son intervalle", "scalemass")429 guide(.settings, "Réglages", "Thème, animations d'ouverture, données locales", "gearshape")430 guide(.about, "À propos d'Immo-Ka", "Sources, confidentialité, conditions", "info.circle")431 }432 }433434 private func guide(_ route: Route, _ title: String, _ text: String, _ icon: String) -> some View {435 NavigationLink(value: route) {436 VStack(spacing: 0) {437 HStack(spacing: 14) {438 Image(systemName: icon).font(.system(size: 16)).foregroundStyle(Theme.brand).frame(width: 26)439 VStack(alignment: .leading, spacing: 2) {440 Text(title).font(.subheadline.weight(.semibold)).foregroundStyle(Theme.ink)441 Text(text).font(.footnote).foregroundStyle(Theme.ink3)442 }443 Spacer()444 Image(systemName: "chevron.right").font(.caption.weight(.semibold)).foregroundStyle(Theme.ink3)445 }446 .padding(.vertical, 12)447 Divider().overlay(Theme.line)448 }449 .contentShape(Rectangle())450 }451 .buttonStyle(.plain)452 }453}454