SPB Git

Repository Public

RecallsView.swift 10.5 KB 239 lines swift

1//2//  Auto-Ka iOS v23//  File: AutoKa/Features/Tools/RecallsView.swift4//  Description: rappels de sécurité de Transports Canada — recherche par marque, modèle et année-modèle (le5//               croisement ne se fait pas par NIV), et carte repliable d'un rappel, reprise par la fiche.6//7//  Author: Simon-Pierre Boucher8//  Contact: contact@spboucher.ai9//1011import SwiftUI1213/// Un rappel : composant, date et numéro ; le texte (problème, risque, mesure corrective) se déplie.14struct RecallCard: View {15    let recall: Recall16    @State private var open = false1718    var body: some View {19        VStack(alignment: .leading, spacing: 0) {20            Button {21                withAnimation(.easeOut(duration: 0.2)) { open.toggle() }22            } label: {23                HStack(alignment: .top, spacing: 12) {24                    BrandIcon("ic-rappel", size: 22).foregroundStyle(Theme.ink2).padding(.top, 1)25                    VStack(alignment: .leading, spacing: 3) {26                        Text(recall.component ?? "Rappel de sécurité").font(.body.weight(.medium)).foregroundStyle(Theme.ink).multilineTextAlignment(.leading)27                        Text(headLine).font(.footnote).foregroundStyle(Theme.ink3).num().multilineTextAlignment(.leading)28                    }29                    Spacer(minLength: 8)30                    Image(systemName: "chevron.down").font(.caption.weight(.semibold)).foregroundStyle(Theme.ink3)31                        .rotationEffect(.degrees(open ? 180 : 0)).padding(.top, 5)32                }33                .padding(.vertical, 12)34                .frame(minHeight: 48)35                .contentShape(Rectangle())36            }37            .buttonStyle(.plain)38            .accessibilityElement(children: .combine)39            .accessibilityValue(open ? "déplié" : "replié")40            .accessibilityHint("Affiche ou masque le texte du rappel")4142            if open {43                VStack(alignment: .leading, spacing: 12) {44                    let parts = recall.paragraphs45                    if parts.isEmpty {46                        Text("Transports Canada ne publie pas de texte pour ce rappel.").font(.subheadline).foregroundStyle(Theme.ink3)47                    }48                    ForEach(Array(parts.enumerated()), id: \.offset) { _, p in49                        VStack(alignment: .leading, spacing: 3) {50                            if let t = p.title { Text(t).font(.footnote.weight(.semibold)).foregroundStyle(Theme.ink) }51                            Text(p.text).font(.subheadline).foregroundStyle(Theme.ink2).fixedSize(horizontal: false, vertical: true)52                        }53                        .accessibilityElement(children: .combine)54                    }55                    if let u = recall.unitsAffected, u > 0 {56                        Text("\(Fmt.plural(u, "véhicule touché", "véhicules touchés")) au Canada.").font(.footnote).foregroundStyle(Theme.ink3).num()57                    }58                    if let c = recall.category, !c.isEmpty {59                        Text("Catégorie : \(c)").font(.footnote).foregroundStyle(Theme.ink3)60                    }61                }62                .padding(.leading, 34).padding(.bottom, 14)63                .transition(.opacity)64            }65            Rule()66        }67    }6869    private var headLine: String {70        ["Rappel nº \(recall.recallNumber)", recall.date.map { Fmt.isoDay($0) }].compactMap { $0 }.joined(separator: " · ")71    }72}7374struct RecallsView: View {75    private enum Phase {76        case idle77        case loading78        case loaded(RecallsResponse)79        case failed(Error)80    }8182    private struct Query: Hashable {83        var make: String84        var model: String85        var year: Int86    }8788    @State private var makes: [MakeSummary] = []89    @State private var makesError: Error?90    @State private var makesAttempt = 091    @State private var models: [ModelSummary] = []92    @State private var makeSlug = ""93    @State private var modelName = ""94    @State private var year = Calendar.current.component(.year, from: Date()) - 595    @State private var query: Query?96    @State private var attempt = 097    @State private var phase: Phase = .idle9899    private static var years: [Int] {100        let next = Calendar.current.component(.year, from: Date()) + 1101        return Array((1990...next).reversed())102    }103104    private var make: MakeSummary? { makes.first { $0.slug == makeSlug } }105    private var canSearch: Bool { make != nil && !modelName.isEmpty }106107    var body: some View {108        Page {109            VStack(alignment: .leading, spacing: 10) {110                Text("Rappels de sécurité").font(.editorial(28)).foregroundStyle(Theme.ink).accessibilityAddTraits(.isHeader)111                Text("Les rappels publiés par Transports Canada pour une marque, un modèle et une année-modèle. Le croisement ne se fait pas par NIV : un rappel de la liste peut ne pas viser un véhicule précis, ou avoir déjà été corrigé. Le concessionnaire de la marque le confirme avec le NIV.")112                    .font(.subheadline).foregroundStyle(Theme.ink2).fixedSize(horizontal: false, vertical: true)113            }114            form115            result116        }117        .navigationTitle("Rappels")118        .navigationBarTitleDisplayMode(.inline)119        .task(id: makesAttempt) {120            guard makes.isEmpty else { return }121            do {122                makes = try await APIClient.shared.makes().makes.sorted { $0.make.localizedCompare($1.make) == .orderedAscending }123                makesError = nil124            } catch is CancellationError {125            } catch {126                makesError = error127            }128        }129        .task(id: makeSlug) {130            models = []131            guard !makeSlug.isEmpty else { return }132            if let page = try? await APIClient.shared.make(makeSlug) {133                models = page.models.sorted { $0.model.localizedCompare($1.model) == .orderedAscending }134            }135        }136        .task(id: "\(query?.hashValue ?? 0)#\(attempt)") {137            guard let q = query else { return }138            phase = .loading139            do {140                phase = .loaded(try await APIClient.shared.recalls(make: q.make, model: q.model, year: q.year))141            } catch is CancellationError {142            } catch {143                phase = .failed(error)144            }145        }146    }147148    // MARK: Formulaire149150    @ViewBuilder151    private var form: some View {152        if let makesError, makes.isEmpty {153            ErrorState(error: makesError) { self.makesError = nil; makesAttempt += 1 }154        } else {155            VStack(alignment: .leading, spacing: 0) {156                Rule()157                field("Marque") {158                    Picker("Marque", selection: $makeSlug) {159                        Text(makes.isEmpty ? "Chargement" : "Choisir").tag("")160                        ForEach(makes) { m in Text(m.make).tag(m.slug) }161                    }162                    .onChange(of: makeSlug) { _, _ in modelName = "" }163                }164                field("Modèle") {165                    Picker("Modèle", selection: $modelName) {166                        Text(makeSlug.isEmpty ? "Choisir la marque d'abord" : (models.isEmpty ? "Chargement" : "Choisir")).tag("")167                        ForEach(models) { m in Text(m.model).tag(m.model) }168                    }169                    .disabled(models.isEmpty)170                }171                field("Année-modèle") {172                    Picker("Année-modèle", selection: $year) {173                        ForEach(RecallsView.years, id: \.self) { y in Text(String(y)).tag(y) }174                    }175                }176                Button {177                    guard let make, !modelName.isEmpty else { return }178                    query = Query(make: make.make, model: modelName, year: year)179                    attempt += 1180                } label: {181                    Text("Chercher les rappels")182                }183                .buttonStyle(PrimaryButtonStyle())184                .disabled(!canSearch)185                .opacity(canSearch ? 1 : 0.45)186                .padding(.top, 16)187                .accessibilityIdentifier("chercher-rappels")188                Text("Les marques et les modèles proposés sont ceux des véhicules en vente en ce moment.")189                    .font(.footnote).foregroundStyle(Theme.ink3).padding(.top, 10).fixedSize(horizontal: false, vertical: true)190            }191        }192    }193194    private func field<P: View>(_ label: String, @ViewBuilder picker: () -> P) -> some View {195        VStack(spacing: 0) {196            HStack {197                Text(label).font(.subheadline).foregroundStyle(Theme.ink3)198                Spacer(minLength: 8)199                picker().pickerStyle(.menu).tint(Theme.brand)200            }201            .frame(minHeight: 50)202            Rule()203        }204    }205206    // MARK: Résultat207208    @ViewBuilder209    private var result: some View {210        switch phase {211        case .idle:212            EmptyView()213        case .loading:214            HStack { Spacer(); BrandLoader(label: "Recherche des rappels"); Spacer() }.padding(.vertical, 30)215        case .failed(let error):216            ErrorState(error: error) { attempt += 1 }217        case .loaded(let r):218            let subject = [r.make ?? query?.make, r.model ?? query?.model, (r.year ?? query?.year).map(String.init)].compactMap { $0 }.joined(separator: " ")219            VStack(alignment: .leading, spacing: 12) {220                if r.recalls.isEmpty {221                    Rule(strong: true)222                    Text("Aucun rappel trouvé pour \(subject)").font(.editorial(20)).foregroundStyle(Theme.ink).fixedSize(horizontal: false, vertical: true)223                    Text("La base de Transports Canada ne contient aucun rappel pour cette marque, ce modèle et cette année-modèle. Le nom du modèle peut y être écrit autrement : essayez une année voisine ou un modèle apparenté.")224                        .font(.subheadline).foregroundStyle(Theme.ink3).fixedSize(horizontal: false, vertical: true)225                } else {226                    SectionHeader(Fmt.plural(r.recalls.count, "rappel", "rappels"), subtitle: "\(subject), selon Transports Canada.")227                    VStack(spacing: 0) {228                        Rule()229                        ForEach(r.recalls) { recall in RecallCard(recall: recall) }230                    }231                }232                if let source = r.source, !source.isEmpty {233                    Text("Source : \(source).").font(.footnote).foregroundStyle(Theme.ink3).fixedSize(horizontal: false, vertical: true)234                }235            }236        }237    }238}239
Files main
Menu

Theme