Repository Public
1//2// Auto-Ka iOS v23// File: AutoKa/Features/Dealers/DealersView.swift4// Description: annuaire des concessionnaires — recherche, filtre par région, tri, pagination infinie, et carte5// MapKit. Une position « ville » est le centre de la ville, pas l'adresse du commerce : on le dit.6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9//1011import MapKit12import SwiftUI1314struct DealersView: View {15 enum Mode: Hashable { case list, map }16 enum Order: String, Hashable { case listings, name }1718 @Environment(AppModel.self) private var model1920 @State private var query = ""21 @State private var region: String?22 @State private var order: Order = .listings23 @State private var mode: Mode = .list2425 @State private var regions: [RegionSummary] = []26 @State private var dealers: [Dealer] = []27 @State private var total: Int?28 @State private var listingsTotal: Int?29 @State private var privateListings: Int?30 @State private var page = 131 @State private var loading = false32 @State private var loadingMore = false33 @State private var error: Error?34 @State private var attempt = 03536 /// commerces placés sur la carte (les plus fournis d'abord, 300 au plus)37 @State private var mapDealers: [Dealer] = []38 @State private var mapLoading = false39 @State private var camera: MapCameraPosition = .automatic40 @State private var selected: Dealer?4142 private static let pageSize = 6043 private static let mapMax = 3004445 /// clé de la requête : tout changement relance la première page (après un court délai de frappe)46 private var key: String { "\(query)|\(region ?? "")|\(order.rawValue)|\(attempt)" }47 private var hasMore: Bool { dealers.count < (total ?? 0) }4849 var body: some View {50 Group {51 if mode == .list { list } else { map }52 }53 .background(Theme.bg)54 .navigationTitle("Concessionnaires")55 .navigationBarTitleDisplayMode(.large)56 .searchable(text: $query, prompt: "Nom d'un commerce")57 .toolbar {58 ToolbarItem(placement: .topBarTrailing) {59 Menu {60 Picker("Tri", selection: $order) {61 Text("Nombre de véhicules").tag(Order.listings)62 Text("Nom").tag(Order.name)63 }64 } label: {65 Label("Trier", systemImage: "arrow.up.arrow.down")66 }67 }68 }69 .task {70 if regions.isEmpty, let r = try? await APIClient.shared.regions() { regions = r.regions.sorted { $0.n > $1.n } }71 }72 .task(id: key) { await reload() }73 .task(id: "\(key)|\(mode == .map)") { if mode == .map { await loadMap() } }74 }7576 // MARK: En-tête commun7778 private var header: some View {79 VStack(alignment: .leading, spacing: 14) {80 if let total {81 Text(intro(total)).font(.subheadline).foregroundStyle(Theme.ink3).fixedSize(horizontal: false, vertical: true)82 }83 SlidingSegmented(selection: $mode, options: [(value: Mode.list, label: "Liste"), (value: Mode.map, label: "Carte")], label: "Affichage")84 ScrollView(.horizontal, showsIndicators: false) {85 HStack(spacing: 8) {86 ChoiceChip(label: "Toutes les régions", selected: region == nil) { region = nil }87 ForEach(regions) { r in88 ChoiceChip(label: r.region, selected: region == r.region) { region = region == r.region ? nil : r.region }89 }90 }91 .padding(.horizontal, HeroLayout.margin)92 }93 .padding(.horizontal, -HeroLayout.margin)94 }95 }9697 private func intro(_ total: Int) -> String {98 var s = "\(Fmt.plural(total, "commerce", "commerces"))"99 if let n = listingsTotal { s += ", \(Fmt.plural(n, "véhicule", "véhicules"))" }100 s += region.map { " en \($0)." } ?? "."101 if region == nil, query.isEmpty, let p = privateListings, p > 0 {102 s += " S'y ajoutent \(Fmt.plural(p, "annonce de particulier", "annonces de particuliers")), hors annuaire."103 }104 return s105 }106107 // MARK: Liste108109 private var list: some View {110 Page(spacing: 18) {111 header112 if let error, dealers.isEmpty {113 ErrorState(error: error) { self.error = nil; attempt += 1 }114 } else if dealers.isEmpty, loading || total == nil {115 HStack { Spacer(); BrandLoader(); Spacer() }.padding(.top, 40)116 } else if dealers.isEmpty {117 EmptyState(title: "Aucun commerce ne correspond", message: "Vérifiez le nom, ou élargissez à toutes les régions.",118 actionLabel: "Tout afficher") { query = ""; region = nil }119 } else {120 LazyVStack(spacing: 0) {121 Rule()122 ForEach(dealers) { d in123 Button { model.open(.dealer(d.id)) } label: {124 IndexRow(title: d.name, detail: detail(d), value: Fmt.int(d.listings), icon: "ic-concessionnaire")125 }126 .buttonStyle(.plain)127 }128 if hasMore {129 HStack { Spacer(); BrandLoader(size: 32, label: "Chargement de la suite"); Spacer() }130 .padding(.vertical, 16)131 .onAppear { Task { await loadMore() } }132 }133 }134 }135 }136 }137138 /// « Sherbrooke · Estrie · Toyota, Honda »139 private func detail(_ d: Dealer) -> String {140 [d.placeLine, d.makesLine].filter { !$0.isEmpty }.joined(separator: " · ")141 }142143 // MARK: Carte144145 private var map: some View {146 VStack(alignment: .leading, spacing: 0) {147 header.padding(.horizontal, HeroLayout.margin).padding(.top, 8).padding(.bottom, 12)148 ZStack(alignment: .bottom) {149 Map(position: $camera) {150 ForEach(mapDealers) { d in151 if let c = d.coordinate {152 Annotation(d.name, coordinate: c, anchor: .center) {153 Button {154 Haptics.select()155 selected = d156 } label: {157 DealerPin(exact: d.hasExactPosition, selected: selected?.id == d.id)158 .frame(width: 44, height: 44)159 .contentShape(Rectangle())160 }161 .buttonStyle(.plain)162 .accessibilityLabel("\(d.name), \(Fmt.plural(d.listings ?? 0, "véhicule", "véhicules"))")163 }164 .annotationTitles(.hidden)165 }166 }167 }168 .mapStyle(.standard(pointsOfInterest: .excludingAll))169 .overlay(alignment: .top) {170 if mapLoading { BrandLoader(size: 32).padding(8).solidControl(RoundedRectangle(cornerRadius: Theme.radiusControl, style: .continuous)).padding(.top, 10) }171 }172 VStack(alignment: .leading, spacing: 8) {173 if let d = selected { selectedCard(d) }174 mapNote175 }176 .padding(12)177 }178 }179 }180181 private var mapNote: some View {182 HStack(alignment: .top, spacing: 10) {183 DealerPin(exact: true, selected: false).frame(width: 16, height: 16)184 Text("adresse du commerce").font(.caption).foregroundStyle(Theme.ink2)185 DealerPin(exact: false, selected: false).frame(width: 16, height: 16)186 Text("centre de sa ville (position approximative)").font(.caption).foregroundStyle(Theme.ink2)187 }188 .padding(.horizontal, 10).padding(.vertical, 8)189 .frame(maxWidth: .infinity, alignment: .leading)190 .solidControl(RoundedRectangle(cornerRadius: Theme.radiusControl, style: .continuous))191 .accessibilityElement(children: .ignore)192 .accessibilityLabel("Carré plein : adresse du commerce. Cercle : centre de sa ville, position approximative.\((total ?? 0) > Self.mapMax ? " Les \(Self.mapMax) commerces les plus fournis sont placés." : "")")193 }194195 private func selectedCard(_ d: Dealer) -> some View {196 Button { model.open(.dealer(d.id)) } label: {197 HStack(alignment: .top, spacing: 12) {198 VStack(alignment: .leading, spacing: 3) {199 Text(d.name).font(.editorial(18)).foregroundStyle(Theme.ink).multilineTextAlignment(.leading)200 Text(detail(d)).font(.footnote).foregroundStyle(Theme.ink3).multilineTextAlignment(.leading)201 Text("\(Fmt.plural(d.listings ?? 0, "véhicule", "véhicules"))\(d.medianPrice.map { " · prix médian \(Fmt.money($0))" } ?? "")")202 .font(.footnote.weight(.medium)).num().foregroundStyle(Theme.ink2)203 if !d.hasExactPosition {204 Text("Position : centre de la ville.").font(.caption).foregroundStyle(Theme.ink3)205 }206 }207 Spacer(minLength: 8)208 Image(systemName: "chevron.right").font(.caption.weight(.semibold)).foregroundStyle(Theme.ink3).padding(.top, 4)209 }210 .padding(14)211 .frame(maxWidth: .infinity, alignment: .leading)212 .solidControl(RoundedRectangle(cornerRadius: Theme.radiusCard, style: .continuous))213 }214 .buttonStyle(.plain)215 .accessibilityElement(children: .combine)216 .accessibilityHint("Ouvre la fiche du commerce")217 }218219 // MARK: Chargement220221 private func reload() async {222 // délai de frappe : la requête ne part que si la saisie s'est arrêtée223 if !query.isEmpty { try? await Task.sleep(for: .milliseconds(350)) }224 if Task.isCancelled { return }225 loading = true226 defer { loading = false }227 do {228 let r = try await APIClient.shared.dealers(q: query.trimmingCharacters(in: .whitespaces), region: region, sort: order.rawValue,229 page: 1, pageSize: Self.pageSize)230 if Task.isCancelled { return }231 dealers = r.dealers232 total = r.total233 listingsTotal = r.listingsTotal234 privateListings = r.privateListings235 page = 1236 error = nil237 } catch is CancellationError {238 } catch {239 self.error = error240 }241 }242243 private func loadMore() async {244 guard hasMore, !loadingMore, !loading else { return }245 loadingMore = true246 defer { loadingMore = false }247 let current = key248 guard let r = try? await APIClient.shared.dealers(q: query.trimmingCharacters(in: .whitespaces), region: region, sort: order.rawValue,249 page: page + 1, pageSize: Self.pageSize), current == key else { return }250 let known = Set(dealers.map(\.id))251 dealers += r.dealers.filter { !known.contains($0.id) }252 page += 1253 // garde-fou : une page vide arrête la pagination254 if r.dealers.isEmpty { total = dealers.count }255 }256257 private func loadMap() async {258 if !query.isEmpty { try? await Task.sleep(for: .milliseconds(350)) }259 if Task.isCancelled { return }260 mapLoading = true261 defer { mapLoading = false }262 guard let r = try? await APIClient.shared.dealers(q: query.trimmingCharacters(in: .whitespaces), region: region, sort: "listings",263 page: 1, pageSize: Self.mapMax), !Task.isCancelled else { return }264 mapDealers = r.dealers.filter { $0.coordinate != nil }265 selected = nil266 let pts = mapDealers.compactMap { d in d.coordinate.map { MapPoint(lat: $0.latitude, lng: $0.longitude, n: 1) } }267 if let b = Clusterer.robustBounds(pts) {268 let center = CLLocationCoordinate2D(latitude: (b.south + b.north) / 2, longitude: (b.west + b.east) / 2)269 let span = MKCoordinateSpan(latitudeDelta: (b.north - b.south) * 1.25, longitudeDelta: (b.east - b.west) * 1.25)270 withAnimation(.easeInOut(duration: 0.4)) { camera = .region(MKCoordinateRegion(center: center, span: span)) }271 }272 }273}274275/// Repère d'un commerce : carré plein pétrole = adresse connue ; cercle au trait = centre de la ville.276struct DealerPin: View {277 let exact: Bool278 let selected: Bool279280 var body: some View {281 GeometryReader { geo in282 let s = min(geo.size.width, geo.size.height) * (geo.size.width > 30 ? 0.36 : 0.8) * (selected ? 1.3 : 1)283 Group {284 if exact {285 RoundedRectangle(cornerRadius: s * 0.22, style: .continuous).fill(selected ? Theme.ink : Theme.brand)286 .overlay(RoundedRectangle(cornerRadius: s * 0.22, style: .continuous).strokeBorder(Theme.surface, lineWidth: 1.5))287 } else {288 Circle().fill(Theme.surface)289 .overlay(Circle().strokeBorder(selected ? Theme.ink : Theme.brand, lineWidth: 2))290 }291 }292 .frame(width: s, height: s)293 .position(x: geo.size.width / 2, y: geo.size.height / 2)294 }295 .accessibilityHidden(true)296 }297}298