Repository Public
1//2// Auto-Ka iOS v23// File: AutoKa/Features/Catalog/ModelView.swift4// Description: page d'un modèle — chiffres clés, prix médian par année, courbe de dépréciation (Swift Charts),5// versions, carburants, régions, verdicts, véhicules récents.6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9//1011import Charts12import SwiftUI1314struct ModelView: View {15 let makeSlug: String16 let modelSlug: String1718 @Environment(AppModel.self) private var model1920 var body: some View {21 Loadable(id: "modele-\(makeSlug)-\(modelSlug)") { [makeSlug, modelSlug] in22 try await APIClient.shared.model(make: makeSlug, model: modelSlug)23 } content: { (page: ModelPage) in24 content(page)25 .navigationTitle("\(page.make) \(page.model)")26 }27 .navigationBarTitleDisplayMode(.inline)28 }2930 @ViewBuilder31 private func content(_ page: ModelPage) -> some View {32 Page {33 VStack(alignment: .leading, spacing: 6) {34 Button { model.open(.brand(page.makeSlug ?? makeSlug)) } label: {35 Text(page.make).eyebrowStyle().frame(minHeight: 28, alignment: .bottomLeading).contentShape(Rectangle())36 }37 .buttonStyle(.plain)38 .accessibilityHint("Ouvre la page de la marque")39 Text("\(page.make) \(page.model)").font(.editorial(30)).foregroundStyle(Theme.ink).accessibilityAddTraits(.isHeader)40 Text("\(Fmt.plural(page.n, "véhicule en vente", "véhicules en vente")) au Québec.")41 .font(.subheadline).foregroundStyle(Theme.ink3)42 }4344 StatGrid {45 StatFigure(value: Fmt.money(page.priceMedian), label: "Prix médian demandé")46 StatFigure(value: Fmt.mileageShort(page.kmMedian) ?? "—", label: "Kilométrage médian")47 StatFigure(value: page.priceMin.flatMap { a in page.priceMax.map { "\(Fmt.kPrice(a)) à \(Fmt.kPrice($0))" } } ?? "—",48 label: "Du moins cher au plus cher")49 StatFigure(value: page.yearMin.flatMap { a in page.yearMax.map { a == $0 ? "\(a)" : "\(a) à \($0)" } } ?? "—",50 label: "Années-modèles")51 }5253 Button("Voir les \(Fmt.int(page.n)) véhicules") { model.search(.make(page.make, model: page.model)) }54 .buttonStyle(PrimaryButtonStyle())5556 byYear(page)57 depreciation(page)5859 if let v = page.verdicts, v.values.contains(where: { $0 > 0 }) {60 VStack(alignment: .leading, spacing: 12) {61 SectionHeader("Prix face au marché", subtitle: "Verdict de chaque véhicule, calculé par le service sur ses comparables")62 VerdictBreakdown(counts: v)63 }64 }6566 bars("Versions", page.trims.map { Array($0.filter { !$0.value.isEmpty }.prefix(10)) }, clean: true)67 bars("Carburants", page.fuels)68 bars("Régions", page.regions.map { Array($0.prefix(10)) })6970 if !page.listings.isEmpty {71 VStack(alignment: .leading, spacing: 14) {72 SectionHeader("Annonces récentes") { MoreLink { model.search(.make(page.make, model: page.model)) } }73 VehicleRail(vehicles: page.listings)74 }75 }7677 VStack(spacing: 0) {78 Rule()79 Button { model.open(.recalls) } label: {80 IndexRow(title: "Rappels de sécurité", detail: "Chercher les rappels de Transports Canada par marque, modèle et année", icon: "ic-rappel")81 }82 .buttonStyle(.plain)83 }84 }85 }8687 // MARK: Prix médian par année8889 @ViewBuilder90 private func byYear(_ page: ModelPage) -> some View {91 let rows = page.byYear.filter { $0.priceMedian != nil }.sorted { $0.year < $1.year }92 if rows.count >= 2 {93 VStack(alignment: .leading, spacing: 12) {94 SectionHeader("Prix médian par année-modèle", subtitle: "Prix demandés des annonces en ligne aujourd'hui")95 Chart(rows) { r in96 BarMark(x: .value("Année", String(r.year)), y: .value("Prix médian", r.priceMedian ?? 0), width: .ratio(0.62))97 .foregroundStyle(Theme.brand)98 .cornerRadius(2)99 .accessibilityLabel("\(r.year)")100 .accessibilityValue("\(Fmt.money(r.priceMedian)), \(Fmt.plural(r.n, "véhicule", "véhicules"))")101 }102 .chartYAxis {103 AxisMarks(position: .leading, values: .automatic(desiredCount: 4)) { v in104 AxisGridLine().foregroundStyle(Theme.line)105 AxisValueLabel { if let d = v.as(Double.self) { Text(Fmt.kPrice(d)).font(.caption2).monospacedDigit().foregroundStyle(Theme.ink3) } }106 }107 }108 .chartXAxis {109 AxisMarks(values: xYears(rows)) { v in110 AxisValueLabel { if let s = v.as(String.self) { Text(s).font(.caption2).monospacedDigit().foregroundStyle(Theme.ink3) } }111 }112 }113 .frame(height: 200)114 .accessibilityLabel("Prix médian demandé par année-modèle, de \(rows.first?.year ?? 0) à \(rows.last?.year ?? 0)")115116 VStack(spacing: 0) {117 Rule()118 ForEach(rows.reversed().prefix(8)) { r in119 FactRow(label: "\(r.year) · \(Fmt.plural(r.n, "véhicule", "véhicules"))",120 value: Fmt.money(r.priceMedian), note: Fmt.mileageShort(r.kmMedian).map { "médiane \($0)" })121 }122 }123 }124 }125 }126127 /// Au plus six années libellées sur l'axe, pour qu'elles ne se chevauchent pas.128 private func xYears(_ rows: [YearSummary]) -> [String] {129 let step = max(1, Int((Double(rows.count) / 6).rounded(.up)))130 return rows.enumerated().filter { ($0.offset - (rows.count - 1)) % step == 0 }.map { String($0.element.year) }131 }132133 // MARK: Dépréciation134135 @ViewBuilder136 private func depreciation(_ page: ModelPage) -> some View {137 if let dep = page.depreciation {138 let pts = dep.curve.filter { $0.priceMedian != nil && $0.n > 0 }.sorted { $0.age < $1.age }139 if pts.count >= 3 {140 VStack(alignment: .leading, spacing: 12) {141 SectionHeader("Dépréciation", subtitle: "Prix médian demandé selon l'âge du véhicule")142 Chart(pts) { p in143 LineMark(x: .value("Âge", p.age), y: .value("Prix médian", p.priceMedian ?? 0))144 .foregroundStyle(Theme.brand)145 .lineStyle(StrokeStyle(lineWidth: 2, lineCap: .round, lineJoin: .round))146 PointMark(x: .value("Âge", p.age), y: .value("Prix médian", p.priceMedian ?? 0))147 .foregroundStyle(Theme.brand)148 .symbolSize(26)149 .accessibilityLabel("\(p.age) an\(p.age > 1 ? "s" : "")")150 .accessibilityValue("\(Fmt.money(p.priceMedian)), \(Fmt.plural(p.n, "véhicule", "véhicules"))")151 }152 .chartYAxis {153 AxisMarks(position: .leading, values: .automatic(desiredCount: 4)) { v in154 AxisGridLine().foregroundStyle(Theme.line)155 AxisValueLabel { if let d = v.as(Double.self) { Text(Fmt.kPrice(d)).font(.caption2).monospacedDigit().foregroundStyle(Theme.ink3) } }156 }157 }158 .chartXAxis {159 AxisMarks(values: .automatic(desiredCount: 6)) { v in160 AxisValueLabel { if let a = v.as(Int.self) { Text(a == 0 ? "neuf" : "\(a) an\(a > 1 ? "s" : "")").font(.caption2).foregroundStyle(Theme.ink3) } }161 }162 }163 .frame(height: 200)164 .accessibilityLabel("Courbe du prix médian demandé selon l'âge, de \(pts.first?.age ?? 0) à \(pts.last?.age ?? 0) ans")165166 if let rate = dep.annualRatePct {167 Text("Entre deux années-modèles voisines, le prix médian demandé recule d'environ \(Fmt.pct(abs(rate))) par an\(dep.listings.map { " (\(Fmt.plural($0, "annonce", "annonces")))" } ?? "").")168 .font(.subheadline).foregroundStyle(Theme.ink2).fixedSize(horizontal: false, vertical: true)169 }170 Text("Coupe transversale des annonces en ligne aujourd'hui : ce n'est pas le suivi d'un même véhicule dans le temps.")171 .font(.footnote).foregroundStyle(Theme.ink3).fixedSize(horizontal: false, vertical: true)172 }173 }174 }175 }176177 @ViewBuilder178 private func bars(_ title: String, _ values: [FacetValue]?, clean: Bool = false) -> some View {179 if let values, !values.isEmpty {180 let top = Double(values.map(\.n).max() ?? 1)181 VStack(alignment: .leading, spacing: 12) {182 SectionHeader(title)183 ForEach(values) { v in184 // une version peut porter du texte de vente : on n'en garde que la tête185 let label = clean ? Fmt.cleanTrim(v.value) : v.title186 BarRow(label: label.isEmpty ? v.value : label, value: Double(v.n), max: top)187 }188 }189 }190 }191}192