Repository Public
1//2// Auto-Ka iOS v23// File: AutoKa/Features/Market/MarketView.swift4// Description: onglet Marché — chiffres clés des annonces en ligne, inventaire par jour, verdicts, tranches de5// prix et de kilométrage, marques, carrosseries, carburants, régions, délais de vente.6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9//1011import Charts12import SwiftUI1314struct MarketView: View {15 var body: some View {16 Loadable(id: "marche") {17 try await APIClient.shared.stats()18 } content: { stats in19 MarketContent(stats: stats)20 }21 .navigationTitle("Marché")22 .navigationBarTitleDisplayMode(.large)23 }24}2526private struct MarketContent: View {27 let stats: Stats2829 @Environment(AppModel.self) private var model30 @State private var period = "30j"31 @State private var dashboard: Dashboard?32 @State private var dashboardFailed = false33 @State private var delays: SaleDelays?3435 private static let periods: [(value: String, label: String)] = [("7j", "7 j"), ("30j", "30 j"), ("3m", "3 mois"), ("12m", "12 mois")]3637 var body: some View {38 Page {39 intro40 figures41 inventory42 verdicts43 priceHistogram44 kmHistogram45 makes46 bodies47 fuels48 regions49 delaysSection50 links51 }52 .task(id: period) {53 dashboardFailed = false54 do { dashboard = try await APIClient.shared.dashboard(period: period) } catch is CancellationError {} catch { dashboardFailed = true }55 }56 .task {57 delays = try? await APIClient.shared.saleDelays()58 }59 }6061 // MARK: Introduction et chiffres clés6263 private var intro: some View {64 VStack(alignment: .leading, spacing: 6) {65 Text("Ces chiffres décrivent les annonces de voitures d'occasion en ligne au Québec en ce moment. Ce sont des prix demandés, pas des prix de vente.")66 .font(.subheadline).foregroundStyle(Theme.ink2).fixedSize(horizontal: false, vertical: true)67 if let g = stats.generatedAt {68 Text("Relevé \(Fmt.ago(g))").font(.footnote).foregroundStyle(Theme.ink3)69 }70 }71 }7273 private var figures: some View {74 VStack(alignment: .leading, spacing: 16) {75 Rule()76 StatGrid {77 StatFigure(value: Fmt.int(stats.auto.n), label: "voitures en vente",78 detail: otherKinds)79 StatFigure(value: Fmt.money(stats.auto.priceMedian), label: "prix demandé médian")80 StatFigure(value: Fmt.mileage(stats.auto.kmMedian), label: "kilométrage médian")81 if let n = stats.auto.new7d { StatFigure(value: Fmt.int(n), label: "nouvelles annonces en 7 jours") }82 if let n = stats.auto.priceDrops { StatFigure(value: Fmt.int(n), label: "annonces dont le prix a baissé") }83 if let n = stats.dealers { StatFigure(value: Fmt.int(n), label: "concessionnaires") }84 if let n = stats.cities { StatFigure(value: Fmt.int(n), label: "villes") }85 if let n = stats.sources { StatFigure(value: Fmt.int(n), label: "sources relevées") }86 }87 }88 }8990 private var otherKinds: String? {91 let motos = stats.kinds?["moto"] ?? 0, scooters = stats.kinds?["scooter"] ?? 092 guard motos + scooters > 0 else { return nil }93 return "et \(Fmt.plural(motos, "moto", "motos")), \(Fmt.plural(scooters, "scooter", "scooters"))"94 }9596 // MARK: Inventaire par jour9798 private var inventory: some View {99 VStack(alignment: .leading, spacing: 14) {100 SectionHeader("Inventaire par jour", subtitle: "Voitures en ligne chaque jour de la période.")101 SlidingSegmented(selection: $period, options: MarketContent.periods, label: "Période")102 if let series = dashboard?.series?.first(where: { $0.id == "inv" }), series.points.count > 1 {103 let pts = series.points104 Chart(pts) { p in105 LineMark(x: .value("Jour", p.date), y: .value("Véhicules", p.v))106 .foregroundStyle(Theme.brand)107 .lineStyle(StrokeStyle(lineWidth: 2, lineCap: .round, lineJoin: .round))108 .interpolationMethod(.monotone)109 }110 .chartYScale(domain: .automatic(includesZero: false))111 .chartXAxis {112 AxisMarks(values: .automatic(desiredCount: 4)) { _ in113 AxisGridLine().foregroundStyle(Theme.line)114 AxisValueLabel(format: .dateTime.day().month(.abbreviated).locale(Fmt.locale))115 }116 }117 .chartYAxis {118 AxisMarks(position: .leading, values: .automatic(desiredCount: 4)) { v in119 AxisGridLine().foregroundStyle(Theme.line)120 AxisValueLabel { if let d = v.as(Double.self) { Text(Fmt.int(d)).monospacedDigit() } }121 }122 }123 .frame(height: 190)124 .accessibilityElement()125 .accessibilityLabel("Inventaire par jour, \(dashboard?.period?.label ?? "")")126 .accessibilityValue("De \(Fmt.int(pts.first?.v)) à \(Fmt.int(pts.last?.v)) voitures")127 if let first = pts.first, let last = pts.last {128 Text("\(Fmt.int(first.v)) voitures le \(Fmt.isoDay(first.t)), \(Fmt.int(last.v)) le \(Fmt.isoDay(last.t)). La collecte a commencé en août 2026 : une période plus longue ne remonte pas plus loin.")129 .font(.footnote).foregroundStyle(Theme.ink3).num().fixedSize(horizontal: false, vertical: true)130 }131 } else if dashboardFailed {132 Text("La série n'a pas pu être chargée.").font(.footnote).foregroundStyle(Theme.ink3)133 } else {134 HStack { Spacer(); BrandLoader(size: 36); Spacer() }.frame(height: 190)135 }136 }137 }138139 // MARK: Verdicts140141 @ViewBuilder142 private var verdicts: some View {143 if let v = stats.verdicts, !v.isEmpty {144 VStack(alignment: .leading, spacing: 14) {145 SectionHeader("Prix demandés face au marché", subtitle: "Chaque voiture est comparée aux annonces du même modèle, ramenées à son kilométrage et à son année.") {146 MoreLink(label: "Méthode") { model.open(.method) }147 }148 VerdictBreakdown(counts: Dictionary(v.map { ($0.value, $0.n) }, uniquingKeysWith: { a, _ in a }))149 }150 }151 }152153 // MARK: Histogrammes154155 @ViewBuilder156 private var priceHistogram: some View {157 if let bins = stats.priceHistogram, !bins.isEmpty {158 VStack(alignment: .leading, spacing: 14) {159 SectionHeader("Tranches de prix", subtitle: "Nombre de voitures par tranche de prix demandé.")160 histogram(bins, name: "Prix") { Fmt.kPrice($0) }161 .accessibilityLabel("Répartition des voitures par tranche de prix")162 .accessibilityValue(peak(bins) { "\(Fmt.kPrice($0.from)) à \($0.to.map { Fmt.kPrice($0) } ?? "plus")" })163 }164 }165 }166167 @ViewBuilder168 private var kmHistogram: some View {169 if let bins = stats.kmHistogram, !bins.isEmpty {170 VStack(alignment: .leading, spacing: 14) {171 SectionHeader("Tranches de kilométrage", subtitle: "Nombre de voitures par tranche de kilométrage, en milliers de kilomètres.")172 histogram(bins, name: "Kilométrage") { "\(Fmt.int($0 / 1000))\(Fmt.nbsp)k" }173 .accessibilityLabel("Répartition des voitures par tranche de kilométrage")174 .accessibilityValue(peak(bins) { "\(Fmt.int($0.from)) à \($0.to.map { Fmt.int($0) } ?? "plus") kilomètres" })175 }176 }177 }178179 private func peak(_ bins: [Stats.Bin], _ label: (Stats.Bin) -> String) -> String {180 guard let top = bins.max(by: { $0.n < $1.n }) else { return "" }181 return "Tranche la plus fournie : \(label(top)), \(Fmt.int(top.n)) voitures"182 }183184 /// Barres à plat ; la dernière tranche (« et plus ») porte un « + ».185 private func histogram(_ bins: [Stats.Bin], name: String, label: @escaping (Double) -> String) -> some View {186 let labels = bins.map { $0.to == nil ? label($0.from) + " +" : label($0.from) }187 // un libellé sur deux (ou trois) : l'axe reste lisible à 320 pt188 let stride = bins.count > 8 ? 3 : 2189 let shown = labels.enumerated().filter { $0.offset % stride == 0 }.map(\.element)190 return Chart(Array(bins.enumerated()), id: \.offset) { i, b in191 BarMark(x: .value(name, labels[i]), y: .value("Véhicules", b.n), width: .ratio(0.82))192 .foregroundStyle(Theme.brand)193 .cornerRadius(2)194 }195 .chartXAxis {196 AxisMarks(values: shown) { _ in197 AxisValueLabel().font(.caption2)198 }199 }200 .chartYAxis {201 AxisMarks(position: .leading, values: .automatic(desiredCount: 4)) { v in202 AxisGridLine().foregroundStyle(Theme.line)203 AxisValueLabel { if let d = v.as(Double.self) { Text(Fmt.int(d)).monospacedDigit() } }204 }205 }206 .frame(height: 180)207 .accessibilityElement()208 }209210 // MARK: Répartitions211212 @ViewBuilder213 private var makes: some View {214 if let rows = stats.byMake, !rows.isEmpty {215 let top = Array(rows.prefix(12)), maxN = Double(top.map(\.n).max() ?? 1)216 VStack(alignment: .leading, spacing: 14) {217 SectionHeader("Marques les plus présentes", subtitle: "Nombre de voitures et prix demandé médian.") {218 MoreLink(label: "Toutes") { model.open(.brands) }219 }220 VStack(spacing: 12) {221 ForEach(top) { r in222 Button { model.open(.brand(r.slug ?? Fmt.slug(r.make))) } label: {223 BarRow(label: r.make, value: Double(r.n), max: maxN,224 valueLabel: "\(Fmt.int(r.n)) · \(Fmt.money(r.priceMedian))")225 .frame(minHeight: 44)226 .contentShape(Rectangle())227 }228 .buttonStyle(.plain)229 .accessibilityHint("Ouvre la marque")230 }231 }232 }233 }234 }235236 @ViewBuilder237 private var bodies: some View {238 if let rows = stats.byBody, !rows.isEmpty {239 let maxN = Double(rows.map(\.n).max() ?? 1)240 VStack(alignment: .leading, spacing: 14) {241 SectionHeader("Carrosseries")242 VStack(spacing: 12) {243 ForEach(rows) { r in244 Button { model.search(.body(r.bodyType)) } label: {245 BarRow(label: r.bodyType, value: Double(r.n), max: maxN,246 valueLabel: "\(Fmt.int(r.n)) · \(Fmt.money(r.priceMedian))", color: Theme.ink3,247 icon: BodyType.icon(for: r.bodyType))248 .frame(minHeight: 44)249 .contentShape(Rectangle())250 }251 .buttonStyle(.plain)252 .accessibilityHint("Lance la recherche")253 }254 }255 }256 }257 }258259 @ViewBuilder260 private var fuels: some View {261 if let rows = stats.byFuel, !rows.isEmpty {262 let maxN = Double(rows.map(\.n).max() ?? 1)263 let known = rows.reduce(0) { $0 + $1.n }264 VStack(alignment: .leading, spacing: 14) {265 SectionHeader("Carburants") {266 MoreLink(label: "Électriques") { model.open(.electrics) }267 }268 VStack(spacing: 12) {269 ForEach(rows) { r in270 Button { model.search(.fuel(r.fuel)) } label: {271 BarRow(label: r.fuel, value: Double(r.n), max: maxN, color: Theme.ink3, icon: Fuel.icon(for: r.fuel))272 .frame(minHeight: 44)273 .contentShape(Rectangle())274 }275 .buttonStyle(.plain)276 .accessibilityHint("Lance la recherche")277 }278 }279 if stats.auto.n > known {280 Text("\(Fmt.int(stats.auto.n - known)) annonces n'indiquent pas le carburant.")281 .font(.footnote).foregroundStyle(Theme.ink3).num()282 }283 }284 }285 }286287 @ViewBuilder288 private var regions: some View {289 if let rows = stats.byRegion, !rows.isEmpty {290 let maxN = Double(rows.map(\.n).max() ?? 1)291 VStack(alignment: .leading, spacing: 14) {292 SectionHeader("Régions", subtitle: "Nombre de voitures et prix demandé médian.") {293 MoreLink(label: "Villes") { model.open(.cities) }294 }295 VStack(spacing: 12) {296 ForEach(rows) { r in297 Button { model.search(.region(r.region)) } label: {298 BarRow(label: r.region, value: Double(r.n), max: maxN,299 valueLabel: "\(Fmt.int(r.n)) · \(Fmt.money(r.priceMedian))")300 .frame(minHeight: 44)301 .contentShape(Rectangle())302 }303 .buttonStyle(.plain)304 .accessibilityHint("Lance la recherche")305 }306 }307 }308 }309 }310311 // MARK: Délais312313 @ViewBuilder314 private var delaysSection: some View {315 if let d = delays, let median = d.medianDays {316 VStack(alignment: .leading, spacing: 14) {317 SectionHeader("Délais avant le retrait",318 subtitle: "Jours entre la première vue d'une annonce et son retrait, sur \(d.days ?? 90) jours. Sites de concessionnaires seulement ; un retrait n'est pas toujours une vente.")319 StatGrid {320 StatFigure(value: "\(Fmt.decimal(median)) jours", label: "délai médian")321 if let a = d.p25Days, let b = d.p75Days {322 StatFigure(value: "\(Fmt.decimal(a)) à \(Fmt.decimal(b))", label: "jours pour la moitié des annonces")323 }324 if let w = d.withdrawn { StatFigure(value: Fmt.int(w), label: "annonces retirées prises en compte") }325 }326 if let rows = d.byPrice, !rows.isEmpty {327 Text("Par tranche de prix").eyebrowStyle().padding(.top, 4)328 delayRows(MarketContent.sortedByPrice(rows))329 }330 if let rows = d.byBody, !rows.isEmpty {331 Text("Par carrosserie").eyebrowStyle().padding(.top, 4)332 delayRows(rows)333 }334 if let m = d.method {335 Text("Méthode : \(m).").font(.footnote).foregroundStyle(Theme.ink3).fixedSize(horizontal: false, vertical: true)336 }337 }338 }339 }340341 private func delayRows(_ rows: [SaleDelays.Row]) -> some View {342 let maxD = rows.compactMap(\.medianDays).max() ?? 1343 return VStack(spacing: 12) {344 ForEach(rows) { r in345 BarRow(label: r.value, value: r.medianDays ?? 0, max: maxD,346 valueLabel: "\(Fmt.decimal(r.medianDays)) j · \(Fmt.int(r.n))", color: Theme.ink3)347 }348 }349 }350351 /// Les tranches arrivent triées par effectif : on les remet dans l'ordre des prix (premier nombre du libellé).352 static func sortedByPrice(_ rows: [SaleDelays.Row]) -> [SaleDelays.Row] {353 func key(_ r: SaleDelays.Row) -> Int {354 if r.value.hasPrefix("moins") { return -1 }355 let digits = r.value.prefix { $0.isNumber || $0.isWhitespace || $0 == "\u{00A0}" || $0 == "\u{202F}" }.filter(\.isNumber)356 return Int(digits) ?? Int.max357 }358 return rows.sorted { key($0) < key($1) }359 }360361 // MARK: Liens362363 private var links: some View {364 VStack(alignment: .leading, spacing: 0) {365 Text("À lire aussi").eyebrowStyle().padding(.bottom, 6)366 Rule()367 Button { model.open(.priceDrops) } label: {368 IndexRow(title: "Baisses de prix", detail: "Les annonces dont le prix a baissé depuis 30 jours", icon: "ic-baisse-prix")369 }.buttonStyle(.plain)370 Button { model.open(.electrics) } label: {371 IndexRow(title: "Électriques et hybrides", detail: "Parts, prix médians, modèles les plus présents", icon: "ic-electrique")372 }.buttonStyle(.plain)373 Button { model.open(.method) } label: {374 IndexRow(title: "Méthode du verdict de prix", detail: "Comment un prix demandé est situé dans le marché", icon: "ic-verdict-dans")375 }.buttonStyle(.plain)376 }377 }378}379