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/MarketV3.swift10// Description : l'onglet Marché sous l'API v3. Un territoire, un genre ;11// quatre natures de chiffres qui ne se mêlent jamais (ventes12// réelles, prix demandés, rôle, estimations), l'indice des13// prix de vente avec son intervalle et l'état de chaque14// période, les classements bornés. Sous le seuil :15// l'effectif, pas la statistique.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 Charts95import SwiftUI9697/// Un bloc de chiffres d'une seule nature, étiqueté.98struct NatureBlock<Content: View>: View {99 let title: String100 let nature: String101 var period: String?102 @ViewBuilder var content: () -> Content103104 var body: some View {105 VStack(alignment: .leading, spacing: 12) {106 HStack(alignment: .firstTextBaseline) {107 Text(title).font(.editorial(19)).foregroundStyle(Theme.ink).accessibilityAddTraits(.isHeader)108 Spacer(minLength: 8)109 PlainTag(text: nature)110 }111 if let period { Text(period).font(.footnote).num().foregroundStyle(Theme.ink3) }112 content()113 }114 .frame(maxWidth: .infinity, alignment: .leading)115 .padding(.top, 14)116 .overlay(alignment: .top) { Hairline(color: Theme.line2) }117 }118}119120struct MarketV3View: View {121 @Environment(AppModel.self) private var model122 @State private var territory = "qc"123 @State private var territoryName = "Québec"124 @State private var genre = "residentiel"125 @State private var market: Loadable<MarketV3> = .loading126 @State private var index: IndexSeriesV3?127 @State private var indexGenre = "maison"128 @State private var pickPlace = false129130 var body: some View {131 ScrollView {132 VStack(alignment: .leading, spacing: 0) {133 Button { pickPlace = true } label: {134 HStack(spacing: 8) {135 VStack(alignment: .leading, spacing: 2) {136 Text("Territoire").eyebrowStyle()137 Text(territoryName).font(.editorial(24)).foregroundStyle(Theme.ink)138 }139 Spacer()140 Text("Changer").font(.subheadline.weight(.medium)).foregroundStyle(Theme.brand)141 }142 .frame(minHeight: 48).contentShape(Rectangle())143 }144 .buttonStyle(.plain)145 .accessibilityIdentifier("market-place")146 SlidingSegmented(selection: $genre, options: Genre.market.map { ($0.key, $0.label) }, label: "Genre de propriété").padding(.top, 10)147148 switch market {149 case .loading: LoadingState(label: "Chargement du marché")150 case .failed(let e): ErrorState(error: e, subject: "Le marché") { Task { await load() } }151 case .loaded(let m, let stale):152 if stale { StaleNotice().padding(.top, 12) }153 blocks(m)154 }155156 indexSection.padding(.top, 34)157158 SectionHeader("Aller plus loin").padding(.top, 36)159 VStack(spacing: 0) {160 Hairline().padding(.top, 8)161 if territory != "qc" {162 NavRow(icon: .municipalite, title: "Portrait de \(territoryName)", detail: "Parc, valeurs, ventes, inscriptions, rues") { model.open(.territory(territory)) }163 }164 NavRow(icon: .ecart, title: "Classements", detail: "Indice, prix payés, prix demandés, valeurs") { model.open(.rankings) }165 NavRow(icon: .municipalite, title: "Territoires", detail: "Régions, MRC, municipalités, arrondissements, rues") { model.open(.territories) }166 NavRow(icon: .comparables, title: "Propriétés à vendre", detail: "Le prix demandé face à l'intervalle") { model.open(.listingsV3(ListingQuery())) }167 NavRow(icon: .fourchette, title: "Estimer sans adresse", detail: "Un ordre de grandeur, par les ventes du voisinage") { model.open(.manual) }168 NavRow(icon: .estimation, title: "Méthodologie", detail: "Le modèle, ses mesures, ses limites") { model.open(.methodology) }169 NavRow(icon: .aplomb, title: "Réglages et à propos", detail: "Thème, animations, données sur l'appareil", divider: false) { model.open(.settings) }170 }171 }172 .pageColumn()173 .padding(.top, 6).padding(.bottom, 36)174 }175 .background(Theme.bg)176 .navigationTitle("Marché")177 .sheet(isPresented: $pickPlace) {178 TerritoryPicker { t in territory = t.id; territoryName = t.title }179 }180 .task(id: territory + "|" + genre) { await load() }181 .task(id: territory + "|" + indexGenre) { index = try? await APIClient.shared.v3Index(territory: territory, genre: indexGenre) }182 .refreshable { await load() }183 .onAppear {184 if let t = UserDefaults.standard.string(forKey: "VPTerritory"), territory == "qc" { territory = t; territoryName = UserDefaults.standard.string(forKey: "VPTerritoryName") ?? t }185 }186 }187188 private func load() async {189 do {190 let f = try await APIClient.shared.v3Market(territory: territory, genre: genre)191 if Task.isCancelled { return }192 market = .loaded(f.value, stale: f.stale)193 if let n = f.value.territoire?.title { territoryName = n }194 } catch is CancellationError {195 } catch { market = .failed(apiError(error)) }196 }197198 @ViewBuilder199 private func blocks(_ m: MarketV3) -> some View {200 VStack(alignment: .leading, spacing: 26) {201 if let b = m.ventes {202 NatureBlock(title: "Ventes réelles", nature: "prix payés", period: period(b)) {203 FigureGrid {204 Figure(label: "Ventes", value: Fmt.int(b.count("ventes_n")))205 Figure(label: "Prix payé médian", value: stat(b["ventes_prix_median"], insufficient: b.insufficient), note: quartiles(b["ventes_prix_p25"], b["ventes_prix_p75"]))206 Figure(label: "Prix payé sur le rôle, médian", value: b["ventes_ratio_role_median"].map { Fmt.decimal($0, digits: 2) + " ×" } ?? "Effectif insuffisant")207 Figure(label: "Prix au pied carré, médian", value: b["ventes_pi2_median"].map { Fmt.money($0) } ?? "Effectif insuffisant")208 }209 }210 .accessibilityIdentifier("market-sales")211 } else {212 NatureBlock(title: "Ventes réelles", nature: "prix payés") {213 Text("Aucune vente publiée sur la période.").font(.subheadline).foregroundStyle(Theme.ink3)214 }215 }216 if let b = m.demandes {217 NatureBlock(title: "Prix demandés", nature: "inscriptions", period: b.date.map { "Inscriptions en ligne au \(Fmt.day($0))" }) {218 FigureGrid {219 Figure(label: "Inscriptions", value: Fmt.int(b.count("insc_n")))220 Figure(label: "Prix demandé médian", value: stat(b["insc_demande_median"], insufficient: b.insufficient), note: quartiles(b["insc_demande_p25"], b["insc_demande_p75"]))221 }222 PositionShare(positions: b.positions)223 }224 }225 if let b = m.valeurs {226 NatureBlock(title: "Valeurs estimées", nature: "estimations", period: b.date.map { "Valeurs fermes du modèle au \(Fmt.day($0))" }) {227 FigureGrid {228 Figure(label: "Propriétés à valeur ferme", value: Fmt.int(b.count("valeur_n")))229 Figure(label: "Valeur estimée médiane", value: stat(b["valeur_mediane"], insufficient: b.insufficient), note: quartiles(b["valeur_p25"], b["valeur_p75"]))230 }231 }232 }233 if let b = m.parc {234 NatureBlock(title: "Rôle d'évaluation", nature: "rôle", period: "Évaluation municipale, jamais une valeur marchande") {235 FigureGrid {236 Figure(label: "Propriétés au rôle", value: Fmt.int(b.count("parc_n")), note: b.count("parc_champ_n").map { "\(Fmt.int($0)) dans le champ du modèle" })237 Figure(label: "Valeur au rôle médiane", value: b["role_median"].map { Fmt.money($0) } ?? "Effectif insuffisant")238 }239 }240 }241 if let d = m.delaiDeVente {242 Text("Délai de vente : " + d).font(.footnote).foregroundStyle(Theme.ink3).fixedSize(horizontal: false, vertical: true)243 }244 }245 .padding(.top, 20)246 }247248 private func period(_ b: MarketBlock) -> String? {249 guard let a = b.debut, let z = b.fin else { return nil }250 return "Du \(Fmt.day(a, short: true)) au \(Fmt.day(z, short: true))" + (b.etat == "provisoire" ? " · provisoire" : "")251 }252 private func stat(_ v: Double?, insufficient: Bool) -> String { v.map { Fmt.money($0) } ?? "Effectif insuffisant" }253 private func quartiles(_ a: Double?, _ b: Double?) -> String? {254 guard let a, let b else { return nil }255 return "moitié centrale : \(Fmt.compact(a)) à \(Fmt.compact(b))"256 }257258 @ViewBuilder259 private var indexSection: some View {260 VStack(alignment: .leading, spacing: 0) {261 SectionHeader("Indice des prix de vente", note: "Évolution du prix payé pour une propriété de qualité constante. Aucun prix demandé, aucune prévision.") {262 MoreLink(label: "Détail") { model.open(.indexSeries(territory: territory, genre: indexGenre)) }263 }264 SlidingSegmented(selection: $indexGenre, options: Genre.indexed.map { ($0.key, $0.label) }, label: "Genre").padding(.top, 12)265 if let s = index {266 IndexSummary(series: s).padding(.top, 14)267 if !s.serie.isEmpty { IndexLineChart(series: s, compact: true).frame(height: 190).padding(.top, 10) }268 } else {269 ProgressView().frame(maxWidth: .infinity).padding(.vertical, 30)270 }271 }272 }273}274275/// Répartition des prix demandés face à l'intervalle : trois effectifs, trois glyphes, un total.276struct PositionShare: View {277 let positions: [String: Int]278 var body: some View {279 let s = positions["sous"] ?? 0, d = positions["dans"] ?? 0, a = positions["au_dessus"] ?? positions["au-dessus"] ?? 0280 let total = s + d + a281 if total > 0 {282 VStack(alignment: .leading, spacing: 8) {283 Text("Prix demandés situés face à l'intervalle (\(Fmt.int(total)))").font(.caption).foregroundStyle(Theme.ink3)284 ForEach([(PricePosition.sous, s), (.dans, d), (.auDessus, a)], id: \.0) { p, n in285 HStack(spacing: 8) {286 PositionPlate(position: p, size: .compact)287 Spacer(minLength: 8)288 Text("\(Fmt.int(n)) · \(Fmt.share(Double(n) / Double(total)))").font(.subheadline.weight(.medium)).num().foregroundStyle(Theme.ink)289 }290 .accessibilityElement(children: .combine)291 }292 }293 }294 }295}296297/// Lecture du dernier point clos d'une série, et le territoire qui la porte quand ce n'est pas celui demandé.298struct IndexSummary: View {299 let series: IndexSeriesV3300 var body: some View {301 VStack(alignment: .leading, spacing: 8) {302 if !series.propre, let t = series.applicable, t.id != series.territoire?.id {303 NoteBlock(text: "Aucune série propre à ce territoire pour ce genre" + (series.raison.map { " (\($0))" } ?? "") + ". La série affichée est celle de \(t.title).", dashed: true)304 .accessibilityIdentifier("index-parent")305 } else if series.serie.isEmpty {306 NoteBlock(text: "Aucune série publiée pour ce genre" + (series.raison.map { " : \($0)" } ?? "") + ".", dashed: true)307 }308 if let p = series.lastClosed, let v = p.valeur {309 FigureGrid {310 Figure(label: "Indice, \(p.label)", value: Fmt.decimal(v, digits: 1),311 note: (series.base.map { "base 100 : \($0)" } ?? "") + (p.stateLabel.map { " · \($0)" } ?? ""))312 Figure(label: "Variation sur un an", value: p.varAnPct.map { Fmt.pct($0) } ?? "—",313 note: (p.icBas != nil && p.icHaut != nil) ? "intervalle à 95 % : \(Fmt.decimal(p.icBas, digits: 1)) à \(Fmt.decimal(p.icHaut, digits: 1))" : nil)314 }315 }316 }317 }318}319320/// La série d'un indice : trait plein jusqu'à la dernière période close, bande de l'intervalle à 95 %, période en cours321/// en pointillé. Rien au-delà de la dernière vente connue.322struct IndexLineChart: View {323 let series: IndexSeriesV3324 var compact = false325326 var body: some View {327 let pts = series.serie.compactMap { p -> (IndexPointV3, Date, Double)? in328 guard let d = p.date, let v = p.valeur else { return nil }329 return (p, d, v)330 }331 let closed = pts.filter { $0.0.closed }332 let lo = (pts.compactMap { $0.0.icBas ?? $0.2 }.min() ?? 90), hi = (pts.compactMap { $0.0.icHaut ?? $0.2 }.max() ?? 110)333 Chart {334 ForEach(closed, id: \.0.id) { p, d, _ in335 if let a = p.icBas, let b = p.icHaut {336 AreaMark(x: .value("Période", d), yStart: .value("Bas", a), yEnd: .value("Haut", b)).foregroundStyle(Theme.dataBand)337 }338 }339 ForEach(closed, id: \.0.id) { _, d, v in340 LineMark(x: .value("Période", d), y: .value("Indice", v), series: .value("Série", "close"))341 .foregroundStyle(Theme.ink).lineStyle(StrokeStyle(lineWidth: 2))342 }343 if let last = closed.last, let open = pts.last, !open.0.closed {344 LineMark(x: .value("Période", last.1), y: .value("Indice", last.2), series: .value("Série", "en cours"))345 .foregroundStyle(Theme.dataRef).lineStyle(StrokeStyle(lineWidth: 1.6, dash: [4, 3]))346 LineMark(x: .value("Période", open.1), y: .value("Indice", open.2), series: .value("Série", "en cours"))347 .foregroundStyle(Theme.dataRef).lineStyle(StrokeStyle(lineWidth: 1.6, dash: [4, 3]))348 }349 if let last = closed.last {350 PointMark(x: .value("Période", last.1), y: .value("Indice", last.2)).foregroundStyle(Theme.brand).symbolSize(70)351 }352 RuleMark(y: .value("Base", 100)).foregroundStyle(Theme.lineControl).lineStyle(StrokeStyle(lineWidth: 1, dash: [2, 3]))353 }354 .chartYScale(domain: (lo - 3).rounded(.down)...(hi + 3).rounded(.up))355 .chartYAxis {356 AxisMarks(position: .leading, values: .automatic(desiredCount: compact ? 4 : 5)) { v in357 AxisGridLine().foregroundStyle(Theme.line)358 AxisValueLabel { if let d = v.as(Double.self) { Text(Fmt.decimal(d, digits: 0)).font(.chartAxis).monospacedDigit().foregroundStyle(Theme.ink3) } }359 }360 }361 .chartXAxis {362 AxisMarks(values: .stride(by: .year)) { _ in363 AxisGridLine().foregroundStyle(Theme.line)364 AxisValueLabel(format: .dateTime.year(), centered: false).font(.chartAxis).foregroundStyle(Theme.ink3)365 }366 }367 .accessibilityLabel(a11y)368 }369370 private var a11y: String {371 guard let p = series.lastClosed, let v = p.valeur else { return "Indice des prix de vente : aucune série." }372 return "Indice des prix de vente : \(Fmt.decimal(v, digits: 1)) en \(p.label)" + (p.varAnPct.map { ", \(Fmt.pct($0)) sur un an" } ?? "") + "."373 }374}375376// MARK: - Indice détaillé377378struct IndexV3View: View {379 let territory: String380 @State var genre: String381 @State private var freq = "T"382 @State private var state: Loadable<IndexSeriesV3> = .loading383384 init(territory: String, genre: String) { self.territory = territory; _genre = State(initialValue: genre) }385386 var body: some View {387 ScrollView {388 VStack(alignment: .leading, spacing: 0) {389 SlidingSegmented(selection: $genre, options: Genre.indexed.map { ($0.key, $0.label) }, label: "Genre")390 SlidingSegmented(selection: $freq, options: [("T", "Trimestriel"), ("M", "Mensuel")], label: "Fréquence").padding(.top, 10)391 switch state {392 case .loading: LoadingState(label: "Chargement de l'indice")393 case .failed(let e): ErrorState(error: e, subject: "L'indice") { Task { await load() } }394 case .loaded(let s, _):395 Text(s.territoire?.title ?? "").font(.editorial(24)).foregroundStyle(Theme.ink).padding(.top, 18)396 IndexSummary(series: s).padding(.top, 12)397 if !s.serie.isEmpty {398 IndexLineChart(series: s).frame(height: 240).padding(.top, 16)399 Text("Trait plein : périodes closes. Bande : intervalle à 95 %. Pointillé : période en cours, incomplète, qui sera révisée et ne se lit pas comme une tendance.")400 .font(.footnote).foregroundStyle(Theme.ink3).fixedSize(horizontal: false, vertical: true).padding(.top, 10)401 SectionHeader("Par période").padding(.top, 28)402 ForEach(s.serie.reversed()) { p in403 FactRow(label: p.label + (p.stateLabel.map { " (\($0))" } ?? "")) {404 VStack(alignment: .trailing, spacing: 1) {405 Text(Fmt.decimal(p.valeur, digits: 1) + (p.varAnPct.map { " · " + Fmt.pct($0) } ?? ""))406 .font(.subheadline.weight(.semibold)).num().foregroundStyle(Theme.ink)407 Text([p.nVentes.map { "\(Fmt.int($0)) ventes" }, p.prixMedian.map { "prix médian brut " + Fmt.compact($0) }].compactMap { $0 }.joined(separator: " · "))408 .font(.caption2).num().foregroundStyle(Theme.ink3)409 }410 }411 }412 Text("Le prix médian brut dépend de ce qui s'est vendu : ce n'est pas l'indice." + (s.ventesJusqua.map { " Ventes connues jusqu'au \(Fmt.day($0))." } ?? ""))413 .font(.footnote).num().foregroundStyle(Theme.ink3).fixedSize(horizontal: false, vertical: true).padding(.top, 12)414 }415 }416 }417 .pageColumn()418 .padding(.top, 6).padding(.bottom, 36)419 }420 .background(Theme.bg)421 .navigationTitle("Indice des prix de vente")422 .navigationBarTitleDisplayMode(.inline)423 .task(id: genre + freq) { await load() }424 }425426 private func load() async {427 do { state = .loaded(try await APIClient.shared.v3Index(territory: territory, genre: genre, freq: freq), stale: false) }428 catch is CancellationError {}429 catch { state = .failed(apiError(error)) }430 }431}432433// MARK: - Classements434435struct RankingsView: View {436 @Environment(AppModel.self) private var model437 @State private var criterion = "indice_var_an"438 @State private var level = "municipalite"439 @State private var genre = "maison"440 @State private var descending = true441 @State private var state: Loadable<RankingV3> = .loading442443 static let criteria: [(key: String, label: String)] = [444 ("indice_var_an", "Indice, sur un an"), ("ventes_prix_median", "Prix payé médian"), ("ventes_n", "Nombre de ventes"),445 ("demande_mediane", "Prix demandé médian"), ("part_au_dessus", "Part au-dessus de l'intervalle"), ("valeur_mediane", "Valeur estimée médiane")]446 private var isIndex: Bool { criterion.hasPrefix("indice") }447448 var body: some View {449 ScrollView {450 LazyVStack(alignment: .leading, spacing: 0) {451 FlowChips(options: RankingsView.criteria, selection: $criterion)452 if !isIndex {453 SlidingSegmented(selection: $level, options: [("region", "Régions"), ("mrc", "MRC"), ("municipalite", "Villes"), ("arrondissement", "Arrond.")], label: "Niveau")454 .padding(.top, 12)455 }456 SlidingSegmented(selection: $genre, options: (isIndex ? Genre.indexed : Genre.market).map { ($0.key, $0.label) }, label: "Genre").padding(.top, 10)457 SlidingSegmented(selection: $descending, options: [(true, "Les plus élevés"), (false, "Les plus bas")], label: "Ordre").padding(.top, 10)458 switch state {459 case .loading: LoadingState(label: "Chargement du classement")460 case .failed(let e): ErrorState(error: e, subject: "Le classement") { Task { await load() } }461 case .loaded(let r, _):462 VStack(alignment: .leading, spacing: 3) {463 Text(Fmt.capitalized(r.libelle ?? "")).font(.subheadline.weight(.medium)).foregroundStyle(Theme.ink).fixedSize(horizontal: false, vertical: true)464 if let c = r.classes, let e = r.exclus {465 Text("\(Fmt.int(c)) territoires classés ; \(Fmt.int(e)) sous le seuil de publication ne le sont pas.")466 .font(.footnote).num().foregroundStyle(Theme.ink3).fixedSize(horizontal: false, vertical: true)467 }468 }469 .padding(.top, 16).padding(.bottom, 6)470 Hairline()471 ForEach(r.items) { row in472 Button { model.open(.territory(row.territoire.id)) } label: {473 VStack(spacing: 0) {474 HStack(alignment: .firstTextBaseline, spacing: 12) {475 Text(String(row.rang)).font(.footnote.weight(.semibold)).monospacedDigit().foregroundStyle(Theme.ink3).frame(width: 26, alignment: .leading)476 VStack(alignment: .leading, spacing: 2) {477 Text(row.territoire.title).font(.subheadline.weight(.medium)).foregroundStyle(Theme.ink).multilineTextAlignment(.leading)478 Text([row.territoire.levelLabel, row.effectif.map { "effectif \(Fmt.int($0))" }, row.periode].compactMap { $0 }.joined(separator: " · "))479 .font(.caption).num().foregroundStyle(Theme.ink3)480 }481 Spacer(minLength: 8)482 Text(format(row.valeur, unit: r.unite)).font(.subheadline.weight(.semibold)).num().foregroundStyle(Theme.ink)483 }484 .padding(.vertical, 12)485 Hairline()486 }487 .contentShape(Rectangle())488 }489 .buttonStyle(.plain)490 .accessibilityIdentifier("ranking-row")491 }492 }493 }494 .pageColumn()495 .padding(.top, 6).padding(.bottom, 36)496 }497 .background(Theme.bg)498 .navigationTitle("Classements")499 .navigationBarTitleDisplayMode(.inline)500 .task(id: "\(criterion)|\(level)|\(genre)|\(descending)") { await load() }501 .onChange(of: criterion) {502 if isIndex, genre == "residentiel" { genre = "maison" }503 }504 }505506 private func format(_ v: Double?, unit: String?) -> String {507 guard let v else { return "—" }508 switch unit {509 case "$": return Fmt.money(v)510 case "%": return criterion == "part_au_dessus" ? Fmt.decimal(v, digits: 1) + Fmt.nbsp + "%" : Fmt.pct(v)511 default: return v == v.rounded() ? Fmt.int(Int(v)) : Fmt.decimal(v, digits: 1)512 }513 }514515 private func load() async {516 state = .loading517 do {518 let g = isIndex && genre == "residentiel" ? "maison" : genre519 state = .loaded(try await APIClient.shared.v3Rankings(criterion: criterion, genre: g, level: isIndex ? nil : level, order: descending ? "desc" : "asc"), stale: false)520 } catch is CancellationError {521 } catch { state = .failed(apiError(error)) }522 }523}524