SPB Git

Repository Public

VehicleSections.swift 22.4 KB 413 lines swift

1//2//  Auto-Ka iOS v23//  File: AutoKa/Features/Vehicle/VehicleSections.swift4//  Description: sections de la fiche sous la tête — caractéristiques, description, équipement, historique de5//               prix (Swift Charts), NIV décodé, rappels de sécurité, vendeur, annonce d'origine, similaires.6//7//  Author: Simon-Pierre Boucher8//  Contact: contact@spboucher.ai9//1011import Charts12import MapKit13import SwiftUI1415struct VehicleSections: View {16    let vehicle: Vehicle17    @Binding var link: ExternalLink?1819    @Environment(AppModel.self) private var model20    @Environment(\.openURL) private var openURL21    @Environment(\.horizontalSizeClass) private var hSize22    @State private var descriptionOpen = false23    @State private var featuresOpen = false2425    private var v: Vehicle { vehicle }2627    var body: some View {28        VStack(alignment: .leading, spacing: 0) {29            section("Caractéristiques", id: "caracteristiques") { specs }30            if !v.description.isEmpty { section("Description", id: "description") { descriptionBlock } }31            if !v.features.isEmpty { section("Équipement", id: "equipement", subtitle: "\(Fmt.plural(v.features.count, "élément indiqué", "éléments indiqués")) par le vendeur") { featuresBlock } }32            section("Historique de prix", id: "historique") { history }33            if !v.vin.isEmpty { section("NIV", id: "niv") { vinBlock } }34            if v.isCar || v.recalls != nil { section("Rappels de sécurité", id: "rappels") { recallsBlock } }35            section("Vendeur", id: "vendeur") { seller }36            section("Annonce d'origine", id: "annonce") { sourceBlock }37            if !v.similar.isEmpty {38                section("Véhicules similaires", id: "similaires", subtitle: "Même marque et même modèle d'abord, puis même carrosserie à prix voisin.") {39                    VehicleRail(vehicles: v.similar)40                }41            }42            footer43        }44    }4546    private func section<C: View>(_ title: String, id: String, subtitle: String? = nil, @ViewBuilder _ content: () -> C) -> some View {47        VStack(alignment: .leading, spacing: 14) {48            SectionHeader(title, subtitle: subtitle)49            content()50        }51        .padding(.top, 34)52        .id(id)53    }5455    // MARK: Caractéristiques5657    private var specs: some View {58        let inferredNote = "déduit du modèle, non indiqué par la source"59        return VStack(spacing: 0) {60            Rule()61            if let y = v.year { FactRow(label: "Année", value: String(y), icon: "ic-annee") }62            FactRow(label: "Kilométrage", value: Fmt.mileage(v.mileageKm), icon: "ic-kilometrage")63            if !v.bodyType.isEmpty { FactRow(label: "Carrosserie", value: v.bodyType, note: v.isInferred("body_type") ? inferredNote : nil, icon: v.bodyIcon) }64            if !v.fuel.isEmpty { FactRow(label: "Carburant", value: v.fuel, note: v.isInferred("fuel") ? inferredNote : nil, icon: Fuel.icon(for: v.fuel)) }65            if !v.transmission.isEmpty { FactRow(label: "Transmission", value: v.transmission, icon: "ic-transmission") }66            if !v.drivetrain.isEmpty { FactRow(label: "Rouage", value: v.drivetrain, icon: "ic-rouage") }67            if !v.engine.isEmpty { FactRow(label: "Moteur", value: v.engine) }68            if !v.exteriorColor.isEmpty { FactRow(label: "Couleur extérieure", value: v.exteriorColor) }69            if !v.interiorColor.isEmpty { FactRow(label: "Couleur intérieure", value: v.interiorColor) }70            if let d = v.doors { FactRow(label: "Portes", value: String(d)) }71            if let s = v.seats { FactRow(label: "Places", value: String(s)) }72            if !v.cleanTrim.isEmpty { FactRow(label: "Version", value: v.trim.count <= 40 ? v.trim : v.cleanTrim) }73            if let s = v.statusLabel { FactRow(label: "Statut", value: s) }74            if !v.stockNumber.isEmpty { FactRow(label: "Numéro d'inventaire", value: v.stockNumber) }75            if let d = Fmt.daysListed(v.daysListed) { FactRow(label: "Mise en ligne", value: d) }76        }77    }7879    // MARK: Description8081    private var descriptionBlock: some View {82        VStack(alignment: .leading, spacing: 10) {83            Text(v.description)84                .font(.body).foregroundStyle(Theme.ink2).lineSpacing(3)85                .lineLimit(descriptionOpen ? nil : 7)86                .fixedSize(horizontal: false, vertical: true)87            if v.description.count > 380 {88                Button(descriptionOpen ? "Réduire" : "Lire la suite") { withAnimation(.easeOut(duration: 0.2)) { descriptionOpen.toggle() } }89                    .font(.subheadline.weight(.medium)).foregroundStyle(Theme.brand).frame(minHeight: 44)90            }91        }92    }9394    // MARK: Équipement9596    private var featuresBlock: some View {97        let limit = 1098        let shown = featuresOpen ? v.features : Array(v.features.prefix(limit))99        return VStack(alignment: .leading, spacing: 4) {100            LazyVGrid(columns: Array(repeating: GridItem(.flexible(), spacing: 20, alignment: .topLeading), count: hSize == .regular ? 2 : 1), alignment: .leading, spacing: 0) {101                ForEach(Array(shown.enumerated()), id: \.offset) { _, f in102                    VStack(spacing: 0) {103                        Text(f).font(.subheadline).foregroundStyle(Theme.ink).frame(maxWidth: .infinity, alignment: .leading).padding(.vertical, 10)104                        Rule()105                    }106                }107            }108            if v.features.count > limit {109                Button(featuresOpen ? "Réduire la liste" : "Afficher les \(v.features.count) éléments") { withAnimation(.easeOut(duration: 0.2)) { featuresOpen.toggle() } }110                    .font(.subheadline.weight(.medium)).foregroundStyle(Theme.brand).frame(minHeight: 44)111            }112        }113    }114115    // MARK: Historique de prix116117    private var history: some View {118        let pts = v.priceHistory119        return VStack(alignment: .leading, spacing: 12) {120            if pts.count >= 2 {121                PriceHistoryChart(points: pts, until: v.active ? Date() : Date(timeIntervalSince1970: v.lastSeen ?? pts.last?.ts ?? 0))122                Text(historySentence(pts)).font(.footnote).foregroundStyle(Theme.ink3).fixedSize(horizontal: false, vertical: true)123            } else {124                Text("Le prix n'a pas changé depuis la première vue de l'annonce, le \(Fmt.date(v.firstSeen ?? pts.first?.ts)).")125                    .font(.subheadline).foregroundStyle(Theme.ink2).fixedSize(horizontal: false, vertical: true)126            }127        }128    }129130    private func historySentence(_ pts: [PricePoint]) -> String {131        guard let first = pts.first, let last = pts.last else { return "" }132        let delta = last.price - first.price133        let n = pts.count - 1134        let head = "Affiché à \(Fmt.money(first.price)) le \(Fmt.date(first.ts)). \(n) changement\(n > 1 ? "s" : "") de prix depuis"135        if abs(delta) < 1 { return head + " ; le prix est revenu à son niveau de départ." }136        return head + " : \(Fmt.signedMoney(delta)) au total (\(Fmt.signedPct(delta / first.price * 100)))."137    }138139    // MARK: NIV140141    private var vinBlock: some View {142        VStack(alignment: .leading, spacing: 0) {143            HStack(spacing: 10) {144                BrandIcon("ic-niv", size: 20).foregroundStyle(Theme.ink2)145                Text(v.vin).font(.system(.body, design: .monospaced).weight(.medium)).foregroundStyle(Theme.ink).textSelection(.enabled)146                Spacer()147                Button {148                    UIPasteboard.general.string = v.vin149                    Haptics.tap()150                    model.showToast("NIV copié")151                } label: { Image(systemName: "doc.on.doc").font(.subheadline).frame(width: 44, height: 44) }152                    .accessibilityLabel("Copier le NIV")153            }154            Rule()155            if !v.vinInfo.isEmpty {156                ForEach(v.vinInfo) { kv in FactRow(label: kv.key, value: kv.value) }157                Text("Fiche du constructeur décodée du NIV (base vPIC de la NHTSA). Elle décrit le véhicule à sa sortie d'usine.")158                    .font(.footnote).foregroundStyle(Theme.ink3).padding(.top, 10).fixedSize(horizontal: false, vertical: true)159            } else if v.vinInfoPending {160                HStack(spacing: 10) { ProgressView(); Text("Décodage du NIV en cours.").font(.footnote).foregroundStyle(Theme.ink3) }.padding(.vertical, 12)161            } else {162                Text("Ce NIV n'a pas pu être décodé.").font(.footnote).foregroundStyle(Theme.ink3).padding(.vertical, 12)163            }164            Button { model.open(.vin(v.vin)) } label: { Text("Ouvrir dans le décodeur de NIV").font(.subheadline.weight(.medium)).foregroundStyle(Theme.brand).frame(minHeight: 44) }165        }166    }167168    // MARK: Rappels169170    @ViewBuilder171    private var recallsBlock: some View {172        let subject = [v.make, v.model, v.year.map(String.init) ?? ""].filter { !$0.isEmpty }.joined(separator: " ")173        if let r = v.recalls, r.checked {174            VStack(alignment: .leading, spacing: 12) {175                HStack(alignment: .top, spacing: 10) {176                    BrandIcon("ic-rappel", size: 20).foregroundStyle(r.count > 0 ? Theme.high : Theme.ink3)177                    Text(r.count == 0 ? "Aucun rappel trouvé pour les \(subject) dans la base de Transports Canada."178                                      : "\(Fmt.plural(r.count, "rappel publié", "rappels publiés")) par Transports Canada pour les \(subject).")179                        .font(.subheadline.weight(.medium)).foregroundStyle(Theme.ink).fixedSize(horizontal: false, vertical: true)180                }181                Text("Le croisement se fait par marque, modèle et année, pas par NIV : ce véhicule n'est pas forcément touché, et la réparation a pu être faite. À confirmer auprès du constructeur ou du vendeur.")182                    .font(.footnote).foregroundStyle(Theme.ink3).fixedSize(horizontal: false, vertical: true)183                if !r.items.isEmpty {184                    VStack(spacing: 0) {185                        Rule()186                        ForEach(r.items) { item in RecallRow(recall: item) }187                    }188                }189            }190        } else {191            Text("Les rappels n'ont pas pu être vérifiés : la marque, le modèle ou l'année manque à cette annonce.")192                .font(.subheadline).foregroundStyle(Theme.ink2).fixedSize(horizontal: false, vertical: true)193        }194    }195196    // MARK: Vendeur197198    private var seller: some View {199        VStack(alignment: .leading, spacing: 14) {200            if let d = v.dealer {201                Button { model.open(.dealer(d.id)) } label: {202                    HStack(alignment: .top, spacing: 12) {203                        BrandIcon("ic-concessionnaire", size: 24).foregroundStyle(Theme.ink2)204                        VStack(alignment: .leading, spacing: 3) {205                            Text(d.name).font(.body.weight(.semibold)).foregroundStyle(Theme.ink).multilineTextAlignment(.leading)206                            Text([v.city.isEmpty ? d.placeLine : v.city, d.listings.map { Fmt.plural($0, "véhicule en vente", "véhicules en vente") }].compactMap { $0 }.filter { !$0.isEmpty }.joined(separator: " · "))207                                .font(.footnote).foregroundStyle(Theme.ink3).multilineTextAlignment(.leading)208                            if let a = d.address, !a.isEmpty { Text(a).font(.footnote).foregroundStyle(Theme.ink2).multilineTextAlignment(.leading) }209                        }210                        Spacer(minLength: 8)211                        Image(systemName: "chevron.right").font(.caption.weight(.semibold)).foregroundStyle(Theme.ink3)212                    }213                    .frame(minHeight: 44).contentShape(Rectangle())214                }215                .buttonStyle(.plain)216                .accessibilityHint("Ouvre la fiche du concessionnaire")217            } else {218                HStack(spacing: 12) {219                    BrandIcon(v.privateSeller ? "ic-particulier" : "ic-concessionnaire", size: 24).foregroundStyle(Theme.ink2)220                    VStack(alignment: .leading, spacing: 3) {221                        Text(v.privateSeller ? "Particulier" : (v.dealerName.isEmpty ? "Vendeur non indiqué" : v.dealerName)).font(.body.weight(.semibold)).foregroundStyle(Theme.ink)222                        if !v.city.isEmpty { Text([v.city, v.region].filter { !$0.isEmpty }.joined(separator: " · ")).font(.footnote).foregroundStyle(Theme.ink3) }223                    }224                }225                .accessibilityElement(children: .combine)226            }227228            let phone = v.dealer?.phone ?? v.details["dealerPhone"] ?? v.details["dealer_phone"]229            let exact = v.dealer?.hasExactPosition ?? false230            let coord = (exact ? v.dealer?.coordinate : nil) ?? v.coordinate231            ViewThatFits(in: .horizontal) {232                HStack(spacing: 10) { sellerButtons(phone: phone, coord: coord, exact: exact) }233                VStack(alignment: .leading, spacing: 10) { sellerButtons(phone: phone, coord: coord, exact: exact) }234            }235236            if let coord {237                Map(initialPosition: .region(MKCoordinateRegion(center: coord, latitudinalMeters: exact ? 2500 : 14000, longitudinalMeters: exact ? 2500 : 14000)), interactionModes: []) {238                    if exact {239                        Annotation(v.dealerName, coordinate: coord) { BrandMark(size: 30).padding(5).solidControl(RoundedRectangle(cornerRadius: 8, style: .continuous)) }240                    } else {241                        MapCircle(center: coord, radius: 3500).foregroundStyle(Theme.brand.opacity(0.14)).stroke(Theme.brand.opacity(0.7), lineWidth: 1)242                    }243                }244                .mapStyle(.standard(pointsOfInterest: .excludingAll))245                .frame(height: 170)246                .clipShape(RoundedRectangle(cornerRadius: Theme.radiusPhoto, style: .continuous))247                .overlay(RoundedRectangle(cornerRadius: Theme.radiusPhoto, style: .continuous).strokeBorder(Theme.line, lineWidth: 1))248                .allowsHitTesting(false)249                .accessibilityLabel(exact ? "Carte : emplacement du commerce" : "Carte : secteur de \(v.city)")250                if !exact {251                    Text("Position approximative : la source ne donne que la ville\(v.city.isEmpty ? "" : " (\(v.city))").")252                        .font(.footnote).foregroundStyle(Theme.ink3)253                }254            }255        }256    }257258    @ViewBuilder259    private func sellerButtons(phone: String?, coord: CLLocationCoordinate2D?, exact: Bool) -> some View {260        if let tel = Fmt.telURL(phone) {261            Button { openURL(tel) } label: { Label("Appeler", systemImage: "phone") }262                .buttonStyle(SecondaryButtonStyle())263                .accessibilityLabel("Appeler le \(phone ?? "")")264        }265        if let coord {266            Button {267                let item = MKMapItem(placemark: MKPlacemark(coordinate: coord))268                item.name = v.dealerName.isEmpty ? v.city : v.dealerName269                item.openInMaps(launchOptions: [MKLaunchOptionsDirectionsModeKey: MKLaunchOptionsDirectionsModeDriving])270            } label: { Label("Itinéraire", systemImage: "arrow.triangle.turn.up.right.diamond") }271                .buttonStyle(SecondaryButtonStyle())272                .accessibilityHint(exact ? "Ouvre Plans" : "Ouvre Plans vers le centre de la ville")273        }274        if let site = ExternalLink(v.dealer?.website) {275            Button { link = site } label: { Label("Site web", systemImage: "globe") }.buttonStyle(SecondaryButtonStyle())276        }277    }278279    // MARK: Annonce d'origine280281    private var sourceBlock: some View {282        VStack(alignment: .leading, spacing: 12) {283            if let l = ExternalLink(v.url) {284                Button { link = l } label: {285                    HStack(spacing: 8) {286                        Text("Voir l'annonce sur \(v.sourceName.isEmpty ? "le site d'origine" : v.sourceName)")287                        Image(systemName: "arrow.up.right").font(.footnote.weight(.semibold))288                    }289                }290                .buttonStyle(PrimaryButtonStyle())291                .accessibilityIdentifier("annonce-origine")292            }293            if let c = ExternalLink(v.carfaxURL) {294                Button { link = c } label: { Label("Rapport Carfax fourni par le vendeur", systemImage: "doc.text.magnifyingglass") }.buttonStyle(SecondaryButtonStyle())295            }296            if !v.offers.isEmpty {297                Text("Le même véhicule est aussi affiché ailleurs").font(.subheadline.weight(.medium)).foregroundStyle(Theme.ink).padding(.top, 6)298                VStack(spacing: 0) {299                    Rule()300                    ForEach(v.offers) { o in301                        Button { if let l = ExternalLink(o.url) { link = l } } label: {302                            VStack(spacing: 0) {303                                HStack(spacing: 10) {304                                    VStack(alignment: .leading, spacing: 2) {305                                        Text(o.sourceName ?? o.source ?? "Autre source").font(.subheadline).foregroundStyle(Theme.ink)306                                        if let dn = o.dealerName, !dn.isEmpty { Text(dn).font(.caption).foregroundStyle(Theme.ink3) }307                                    }308                                    Spacer()309                                    Text(Fmt.money(o.price)).font(.subheadline.weight(.medium)).num().foregroundStyle(Theme.ink)310                                    Image(systemName: "arrow.up.right").font(.caption.weight(.semibold)).foregroundStyle(Theme.ink3)311                                }312                                .padding(.vertical, 11).frame(minHeight: 44).contentShape(Rectangle())313                                Rule()314                            }315                        }316                        .buttonStyle(.plain)317                        .accessibilityElement(children: .combine)318                    }319                }320            }321        }322    }323324    private var footer: some View {325        Text("Première vue le \(Fmt.date(v.firstSeen)) ; confirmée \(Fmt.ago(v.lastSeen)). Renseignements relevés automatiquement chez \(v.sourceName.isEmpty ? "la source" : v.sourceName) : à vérifier auprès du vendeur.")326            .font(.footnote).foregroundStyle(Theme.ink3).fixedSize(horizontal: false, vertical: true)327            .padding(.top, 30)328    }329}330331/// Historique de prix : paliers, un point par changement.332struct PriceHistoryChart: View {333    let points: [PricePoint]334    let until: Date335    @State private var drawn = 0.0336337    var body: some View {338        let prices = points.map(\.price)339        let lo = (prices.min() ?? 0), hi = (prices.max() ?? 1)340        let pad = max((hi - lo) * 0.35, hi * 0.01)341        // le dernier prix est prolongé jusqu'à aujourd'hui (ou jusqu'au retrait)342        let extended = points + (points.last.map { until > $0.date ? [PricePoint(ts: until.timeIntervalSince1970, price: $0.price)] : [] } ?? [])343        Chart {344            ForEach(extended) { p in345                LineMark(x: .value("Date", p.date), y: .value("Prix", p.price))346                    .interpolationMethod(.stepEnd)347                    .foregroundStyle(Theme.brand)348                    .lineStyle(StrokeStyle(lineWidth: 2, lineCap: .round, lineJoin: .round))349            }350            ForEach(points) { p in351                PointMark(x: .value("Date", p.date), y: .value("Prix", p.price))352                    .foregroundStyle(Theme.brand).symbolSize(34)353            }354        }355        .chartYScale(domain: (lo - pad)...(hi + pad))356        .chartYAxis {357            AxisMarks(position: .leading, values: .automatic(desiredCount: 3)) { value in358                AxisGridLine().foregroundStyle(Theme.line)359                AxisValueLabel { if let d = value.as(Double.self) { Text(Fmt.kPrice(d)).font(.caption2).monospacedDigit().foregroundStyle(Theme.ink3) } }360            }361        }362        .chartXAxis {363            AxisMarks(values: .automatic(desiredCount: 3)) { value in364                AxisValueLabel { if let d = value.as(Date.self) { Text(d.formatted(.dateTime.day().month(.abbreviated).locale(Fmt.locale))).font(.caption2).foregroundStyle(Theme.ink3) } }365            }366        }367        .frame(height: 150)368        .mask(alignment: .leading) { GeometryReader { g in Rectangle().frame(width: g.size.width * drawn) } }369        .drawOnAppear($drawn, duration: 0.8)370        .accessibilityElement()371        .accessibilityLabel("Historique de prix : " + points.map { "\(Fmt.money($0.price)) le \(Fmt.date($0.ts))" }.joined(separator: ", "))372    }373}374375/// Un rappel de Transports Canada, repliable : composant, date et numéro, puis le texte en paragraphes titrés.376struct RecallRow: View {377    let recall: Recall378    @State private var open = false379380    var body: some View {381        VStack(alignment: .leading, spacing: 0) {382            Button { withAnimation(.easeOut(duration: 0.2)) { open.toggle() } } label: {383                HStack(alignment: .top, spacing: 10) {384                    VStack(alignment: .leading, spacing: 3) {385                        Text(recall.component ?? "Rappel").font(.subheadline.weight(.medium)).foregroundStyle(Theme.ink).multilineTextAlignment(.leading)386                        Text("\(Fmt.isoDay(recall.date)) · n° \(recall.recallNumber)").font(.caption).num().foregroundStyle(Theme.ink3)387                    }388                    Spacer(minLength: 8)389                    Image(systemName: "chevron.down").font(.caption.weight(.semibold)).foregroundStyle(Theme.ink3).rotationEffect(.degrees(open ? 180 : 0))390                }391                .padding(.vertical, 12).frame(minHeight: 44).contentShape(Rectangle())392            }393            .buttonStyle(.plain)394            .accessibilityHint(open ? "Replie le texte du rappel" : "Affiche le texte du rappel")395            if open {396                VStack(alignment: .leading, spacing: 10) {397                    ForEach(Array(recall.paragraphs.enumerated()), id: \.offset) { _, p in398                        VStack(alignment: .leading, spacing: 3) {399                            if let t = p.title { Text(t).font(.caption.weight(.semibold)).foregroundStyle(Theme.ink2) }400                            Text(p.text).font(.footnote).foregroundStyle(Theme.ink2).fixedSize(horizontal: false, vertical: true)401                        }402                    }403                    if let u = recall.unitsAffected, u > 0 {404                        Text("\(Fmt.plural(u, "véhicule touché", "véhicules touchés")) au Canada.").font(.caption).num().foregroundStyle(Theme.ink3)405                    }406                }407                .padding(.bottom, 14)408            }409            Rule()410        }411    }412}413
Files main
Menu

Theme