Repository Public
1//2// Auto-Ka iOS v23// File: AutoKa/Features/Saved/FavoritesView.swift4// Description: favoris gardés sur l'appareil — baisse de prix ou retrait de l'annonce signalés à chaque5// ouverture —, recherches enregistrées, accès au comparateur et aux véhicules consultés.6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9//1011import SwiftData12import SwiftUI1314struct FavoritesView: View {15 @Environment(AppModel.self) private var model16 @Environment(Library.self) private var library17 @Environment(BoardingCenter.self) private var boarding18 @Query(sort: \FavoriteItem.savedAt, order: .reverse) private var favorites: [FavoriteItem]19 @Query(filter: #Predicate<SearchItem> { $0.pinned }, sort: \SearchItem.at, order: .reverse) private var searches: [SearchItem]20 @State private var checking = false2122 var body: some View {23 Page(spacing: 30) {24 if favorites.isEmpty {25 EmptyState(title: "Aucun favori",26 message: "Le cœur d'une fiche garde un véhicule ici, sur cet appareil. Une baisse de prix ou le retrait de l'annonce y seront signalés.",27 actionLabel: "Chercher un véhicule") { model.search(SearchFilters()) }28 } else {29 VStack(alignment: .leading, spacing: 4) {30 HStack(alignment: .firstTextBaseline) {31 Text(Fmt.plural(favorites.count, "favori", "favoris")).font(.editorial(21)).num().foregroundStyle(Theme.ink)32 .accessibilityAddTraits(.isHeader).accessibilityIdentifier("nombre-favoris")33 Spacer()34 if checking { ProgressView().controlSize(.small).accessibilityLabel("Vérification des prix") }35 }36 Text(statusLine).font(.footnote).foregroundStyle(Theme.ink3).fixedSize(horizontal: false, vertical: true)37 VStack(spacing: 0) {38 Rule().padding(.top, 10)39 ForEach(favorites) { f in favoriteRow(f) }40 }41 }42 }4344 VStack(alignment: .leading, spacing: 0) {45 Rule()46 Button { model.open(.compare) } label: {47 IndexRow(title: "Comparateur", detail: library.compareIDs.isEmpty ? "Jusqu'à \(Library.compareMax) véhicules côte à côte" : nil,48 value: library.compareIDs.isEmpty ? nil : "\(library.compareIDs.count) sur \(Library.compareMax)", icon: "ic-comparer")49 }50 .buttonStyle(.plain).accessibilityIdentifier("ouvrir-comparateur")51 Button { model.open(.recent) } label: {52 IndexRow(title: "Récemment consultés", value: library.seenIDs.isEmpty ? nil : Fmt.int(library.seenIDs.count), systemIcon: "clock.arrow.circlepath")53 }54 .buttonStyle(.plain)55 }5657 if !searches.isEmpty {58 VStack(alignment: .leading, spacing: 6) {59 SectionHeader("Recherches enregistrées")60 VStack(spacing: 0) {61 Rule()62 ForEach(searches) { s in63 HStack(spacing: 0) {64 Button { model.search(s.filters, sort: s.sort) } label: {65 VStack(alignment: .leading, spacing: 2) {66 Text(s.label).font(.body).foregroundStyle(Theme.ink).multilineTextAlignment(.leading)67 Text("Tri : \(s.sort.label.lowercased())" + (s.lastTotal.map { " · \(Fmt.plural($0, "véhicule", "véhicules")) à l'enregistrement" } ?? ""))68 .font(.footnote).foregroundStyle(Theme.ink3).multilineTextAlignment(.leading)69 }70 .frame(maxWidth: .infinity, alignment: .leading).padding(.vertical, 12).contentShape(Rectangle())71 }72 .buttonStyle(.plain)73 Button { library.delete(s) } label: { Image(systemName: "trash").font(.subheadline).foregroundStyle(Theme.ink3).frame(width: 44, height: 44) }74 .accessibilityLabel("Supprimer la recherche \(s.label)")75 }76 Rule()77 }78 }79 }80 }81 }82 .navigationTitle("Favoris")83 .task { await check() }84 }8586 private var statusLine: String {87 let gone = favorites.filter { !$0.active }.count88 let drops = favorites.filter { ($0.changeSinceSaved ?? 0) < 0 && $0.active }.count89 var parts: [String] = []90 if drops > 0 { parts.append(Fmt.plural(drops, "prix a baissé", "prix ont baissé") + " depuis l'enregistrement") }91 if gone > 0 { parts.append(Fmt.plural(gone, "annonce a été retirée", "annonces ont été retirées")) }92 return parts.isEmpty ? "Gardés sur cet appareil. Les prix sont vérifiés à chaque ouverture." : parts.joined(separator: " · ") + "."93 }9495 private func favoriteRow(_ f: FavoriteItem) -> some View {96 let change = f.changeSinceSaved97 let note: String? = !f.active ? "Annonce retirée par sa source"98 : change.map { "\($0 < 0 ? "Baisse" : "Hausse") de \(Fmt.money(abs($0))) depuis l'enregistrement (\(Fmt.money(f.savedPrice)))" }99 return VStack(spacing: 0) {100 HStack(alignment: .top, spacing: 0) {101 Button {102 // la fiche fraîche est en mémoire après la vérification : le geste part de la vignette103 if let v = model.seed(for: f.uid) { model.openVehicle(v, origin: .favorite, boarding: boarding) } else { model.open(.vehicle(f.uid)) }104 } label: {105 SnapshotRow(item: f, note: note, noteColor: !f.active ? Theme.bad : ((change ?? 0) < 0 ? Theme.good : Theme.ink2), dimmed: !f.active) { EmptyView() }106 }107 .buttonStyle(CardPressStyle())108 .accessibilityIdentifier("favori-\(f.uid)")109 Button {110 library.removeFavorite(f.uid)111 model.showToast("Retiré des favoris")112 } label: { Image(systemName: "heart.fill").font(.subheadline).foregroundStyle(Theme.brand).frame(width: 44, height: 44) }113 .accessibilityLabel("Retirer \(f.title) des favoris")114 }115 .padding(.vertical, 12)116 Rule()117 }118 }119120 /// Vérifie chaque favori auprès du service : prix courant, verdict, retrait. Au plus 60, quatre à la fois.121 private func check() async {122 let stale = favorites.filter { $0.checkedAt.map { Date().timeIntervalSince($0) > 300 } ?? true || model.seed(for: $0.uid) == nil }.prefix(60).map(\.uid)123 guard !stale.isEmpty, !checking else { return }124 checking = true125 defer { checking = false }126 await withTaskGroup(of: (String, Result<Vehicle, Error>).self) { group in127 var it = stale.makeIterator()128 var running = 0129 func add() { if let uid = it.next() { running += 1; group.addTask { (uid, await Result { try await APIClient.shared.vehicle(uid) }) } } }130 for _ in 0..<4 { add() }131 for await (uid, result) in group {132 running -= 1133 switch result {134 case .success(let v): model.seed(v); library.refreshFavorite(v)135 case .failure(let e): if let e = e as? APIError, e == .gone || e == .notFound { library.markFavoriteGone(uid) }136 }137 add()138 }139 }140 }141}142143private extension Result where Failure == Error {144 init(_ body: () async throws -> Success) async {145 do { self = .success(try await body()) } catch { self = .failure(error) }146 }147}148149/// Véhicules consultés récemment (instantanés gardés sur l'appareil).150struct RecentView: View {151 @Environment(AppModel.self) private var model152 @Environment(Library.self) private var library153 @Query(sort: \SeenItem.at, order: .reverse) private var seen: [SeenItem]154155 var body: some View {156 Page {157 if seen.isEmpty {158 EmptyState(title: "Aucun véhicule consulté", message: "Les fiches ouvertes sont notées ici, sur cet appareil seulement.")159 } else {160 VStack(spacing: 0) {161 Rule()162 ForEach(seen.prefix(120)) { s in163 Button { model.open(.vehicle(s.uid)) } label: {164 VStack(spacing: 0) {165 SnapshotRow(item: s, note: "Consulté \(Fmt.ago(s.at.timeIntervalSince1970))", noteColor: Theme.ink3) { EmptyView() }.padding(.vertical, 12)166 Rule()167 }168 }169 .buttonStyle(CardPressStyle())170 }171 }172 }173 }174 .navigationTitle("Récemment consultés")175 .navigationBarTitleDisplayMode(.inline)176 .toolbar {177 if !seen.isEmpty {178 ToolbarItem(placement: .topBarTrailing) { Button("Effacer") { library.clearSeen() } }179 }180 }181 }182}183