Repository Public
1//2// Auto-Ka iOS v23// File: AutoKa/Features/Tools/VINDecoderView.swift4// Description: décodeur de NIV — saisie validée (17 caractères, sans I, O ni Q), fiche constructeur décodée par5// le service (vPIC de la NHTSA) et véhicules en vente portant ce NIV.6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9//1011import SwiftUI12import UIKit1314struct VINDecoderView: View {15 /// NIV à décoder d'emblée (lien depuis une fiche, lien profond)16 let initial: String?1718 private enum Phase {19 case idle20 case loading21 case loaded(VINResponse)22 case failed(Error)23 }2425 @State private var text = ""26 @State private var phase: Phase = .idle27 /// NIV soumis : change à chaque décodage demandé28 @State private var submitted: String?29 @State private var started = false30 @State private var attempt = 031 @FocusState private var focused: Bool3233 private var isValid: Bool { Fmt.isValidVIN(text) }3435 var body: some View {36 Page {37 VStack(alignment: .leading, spacing: 10) {38 Text("Décodeur de NIV").font(.editorial(28)).foregroundStyle(Theme.ink).accessibilityAddTraits(.isHeader)39 Text("Le numéro d'identification du véhicule (NIV) compte 17 caractères. Il se lit au bas du pare-brise côté conducteur, sur le montant de la portière et sur le certificat d'immatriculation.")40 .font(.subheadline).foregroundStyle(Theme.ink2).fixedSize(horizontal: false, vertical: true)41 }42 entry43 result44 }45 .scrollDismissesKeyboard(.interactively)46 .navigationTitle("Décodeur de NIV")47 .navigationBarTitleDisplayMode(.inline)48 .onAppear {49 guard !started else { return }50 started = true51 if let initial, !initial.isEmpty {52 text = VINDecoderView.clean(initial)53 if isValid { submit() }54 }55 }56 .task(id: "\(submitted ?? "")#\(attempt)") {57 guard let niv = submitted else { return }58 phase = .loading59 do {60 phase = .loaded(try await APIClient.shared.vin(niv))61 } catch is CancellationError {62 } catch {63 phase = .failed(error)64 }65 }66 }6768 /// Majuscules, lettres et chiffres seulement, 17 caractères au plus.69 static func clean(_ s: String) -> String {70 String(s.uppercased().filter { $0.isASCII && ($0.isLetter || $0.isNumber) }.prefix(17))71 }7273 private func submit() {74 guard isValid else { return }75 focused = false76 // un second décodage du même NIV relance la requête77 attempt += 178 submitted = text79 }8081 // MARK: Saisie8283 private var entry: some View {84 VStack(alignment: .leading, spacing: 10) {85 HStack(spacing: 8) {86 BrandIcon("ic-niv", size: 22).foregroundStyle(Theme.ink3)87 TextField("NIV à 17 caractères", text: $text)88 .font(.body.monospaced())89 .textInputAutocapitalization(.characters)90 .autocorrectionDisabled()91 .keyboardType(.asciiCapable)92 .submitLabel(.search)93 .focused($focused)94 .onSubmit(submit)95 .onChange(of: text) { _, new in96 let c = VINDecoderView.clean(new)97 if c != new { text = c }98 }99 .accessibilityLabel("Numéro d'identification du véhicule")100 .accessibilityIdentifier("champ-niv")101 if !text.isEmpty {102 Button {103 text = ""; phase = .idle; submitted = nil104 } label: {105 Image(systemName: "xmark.circle.fill").foregroundStyle(Theme.ink3).frame(width: 44, height: 44).contentShape(Rectangle())106 }107 .buttonStyle(.plain)108 .accessibilityLabel("Effacer")109 }110 }111 .padding(.leading, 12).padding(.trailing, text.isEmpty ? 12 : 0)112 .frame(minHeight: 52)113 .background(Theme.surface, in: RoundedRectangle(cornerRadius: Theme.radiusControl, style: .continuous))114 .overlay(RoundedRectangle(cornerRadius: Theme.radiusControl, style: .continuous).strokeBorder(focused ? Theme.brand : Theme.line2, lineWidth: 1))115116 HStack(alignment: .firstTextBaseline) {117 Text(hint).font(.footnote).foregroundStyle(hintIsError ? Theme.bad : Theme.ink3).fixedSize(horizontal: false, vertical: true)118 Spacer(minLength: 8)119 Text("\(text.count) / 17").font(.footnote).num().foregroundStyle(Theme.ink3)120 .accessibilityLabel("\(text.count) caractères sur 17")121 }122123 HStack(spacing: 10) {124 Button(action: submit) { Text("Décoder") }125 .buttonStyle(PrimaryButtonStyle())126 .disabled(!isValid)127 .opacity(isValid ? 1 : 0.45)128 .accessibilityIdentifier("decoder-niv")129 Button {130 if let s = UIPasteboard.general.string { text = VINDecoderView.clean(s) }131 } label: {132 Label("Coller", systemImage: "doc.on.clipboard")133 }134 .buttonStyle(SecondaryButtonStyle())135 .frame(minHeight: 48)136 }137 }138 }139140 private var hintIsError: Bool {141 text.count == 17 && !isValid142 }143144 private var hint: String {145 if text.isEmpty { return "Lettres et chiffres, sans I, O ni Q." }146 if text.contains(where: { "IOQ".contains($0) }) { return "Un NIV ne contient jamais les lettres I, O ni Q (elles se confondent avec 1 et 0)." }147 if text.count < 17 { return "Il manque \(17 - text.count) caractère\(17 - text.count > 1 ? "s" : "")." }148 return isValid ? "NIV complet." : "Ce NIV n'est pas valide."149 }150151 // MARK: Résultat152153 @ViewBuilder154 private var result: some View {155 switch phase {156 case .idle:157 EmptyView()158 case .loading:159 VStack(spacing: 10) {160 BrandLoader(label: "Décodage en cours")161 Text("Décodage en cours").font(.footnote).foregroundStyle(Theme.ink3)162 }163 .frame(maxWidth: .infinity).padding(.vertical, 30)164 case .failed(let error):165 ErrorState(error: error) { submit() }166 case .loaded(let r):167 decoded(r)168 }169 }170171 @ViewBuilder172 private func decoded(_ r: VINResponse) -> some View {173 VStack(alignment: .leading, spacing: 14) {174 SectionHeader("Fiche constructeur", subtitle: r.vin)175 if r.decoded, !r.info.isEmpty {176 VStack(spacing: 0) {177 Rule()178 ForEach(r.info) { kv in FactRow(label: kv.key, value: kv.value) }179 }180 Text("Source : base vPIC de la NHTSA (États-Unis). Ce sont les caractéristiques déclarées par le constructeur à la sortie d'usine ; elles ne disent rien de l'état actuel du véhicule.")181 .font(.footnote).foregroundStyle(Theme.ink3).fixedSize(horizontal: false, vertical: true)182 } else {183 VStack(alignment: .leading, spacing: 8) {184 Rule()185 Text("Ce NIV n'a pas pu être décodé.").font(.subheadline.weight(.medium)).foregroundStyle(Theme.ink)186 Text("La base vPIC de la NHTSA ne le reconnaît pas, ou n'a pas répondu. Vérifiez chaque caractère, puis réessayez.")187 .font(.subheadline).foregroundStyle(Theme.ink3).fixedSize(horizontal: false, vertical: true)188 }189 }190 }191 VStack(alignment: .leading, spacing: 16) {192 SectionHeader("En vente avec ce NIV",193 subtitle: r.listings.isEmpty ? nil : Fmt.plural(r.listings.count, "annonce publique", "annonces publiques"))194 if r.listings.isEmpty {195 Text("Aucune annonce publique ne porte ce NIV en ce moment. Certaines annonces n'indiquent pas leur NIV.")196 .font(.subheadline).foregroundStyle(Theme.ink3).fixedSize(horizontal: false, vertical: true)197 } else {198 VehicleGrid(vehicles: r.listings)199 }200 }201 }202}203