SPB Git

Repository Public

DealsView.swift 17.6 KB 329 lines swift

1//2//  Food-Ka iOS v23//  File: FoodKa/Features/Deals/DealsView.swift4//  Description: soldes et circulaires — les baisses de prix vérifiées dans l'historique (plus forte baisse d'abord),5//               et les circulaires en cours par enseigne avec leurs dates de validité.6//7//  Author: Simon-Pierre Boucher8//  Contact: contact@spboucher.ai9//1011import SwiftUI1213struct DealsView: View {14    var root = true15    @Environment(AppModel.self) private var model16    @Environment(\.horizontalSizeClass) private var hSize17    @State private var products: [Product] = []18    @State private var byStatus: [String: Int] = [:]19    @State private var total = 020    @State private var page = 021    @State private var pages = 122    @State private var loading = true23    @State private var failure: APIError?24    @State private var stale = false25    @State private var flyers: FlyersResponse?26    @State private var kind: String?27    @State private var status: Deal.Status = .verifiee2829    /// Les cinq statuts d'un solde, nommés pour ce qu'ils sont.30    static let statuses: [(Deal.Status, String)] = [(.verifiee, "Baisses vérifiées"), (.declaree, "Annoncés, non vérifiables"),31                                                    (.circulaire, "En circulaire"), (.habituelle, "Prix inchangé"), (.gonflee, "Écartés")]3233    private var statusTitle: String { DealsView.statuses.first { $0.0 == status }?.1 ?? "Soldes" }3435    var body: some View {36        ScrollView {37            LazyVStack(alignment: .leading, spacing: 0) {38                if root, let f = flyers, !f.flyers.isEmpty {39                    flyerStrip(f).padding(.top, 6).padding(.bottom, 30)40                }41                SectionHeader(statusTitle, note: loading && products.isEmpty ? nil42                              : (status == .verifiee43                                 ? "\(Fmt.plural(total, "produit dont le prix a réellement baissé", "produits dont le prix a réellement baissé")), les plus fortes baisses de chaque enseigne d'abord."44                                 : Fmt.plural(total, "produit", "produits") + "."))45                // la règle publiée du statut choisi46                if let rule = ServiceInfo.dealRule(status) {47                    Text(Fmt.capitalized(rule) + ".").font(.footnote).foregroundStyle(Theme.ink3)48                        .fixedSize(horizontal: false, vertical: true).padding(.top, 6)49                }50                ScrollView(.horizontal, showsIndicators: false) {51                    HStack(spacing: 8) {52                        ForEach(DealsView.statuses, id: \.0) { s in53                            Chip(label: s.1, selected: status == s.0, count: byStatus[s.0.rawValue]) { status = s.0 }54                                .accessibilityIdentifier("deal-status-\(s.0.rawValue)")55                        }56                    }57                }58                .scrollClipDisabled().padding(.top, 8)59                HStack(spacing: 8) {60                    Chip(label: "Tout", selected: kind == nil) { kind = nil }61                    Chip(label: "Catalogue", selected: kind == "catalogue") { kind = "catalogue" }62                    Chip(label: "Circulaires", selected: kind == "circulaire") { kind = "circulaire" }63                }64                if stale { StaleBanner().padding(.vertical, 8) }65                if loading && products.isEmpty {66                    LoadingShelves(rows: 5)67                } else if let failure, products.isEmpty {68                    ErrorState(error: failure) { Task { await reload() } }69                } else if products.isEmpty {70                    EmptyShelf(title: "Aucun produit dans cet état", message: status == .verifiee ? "Aucun prix n'a baissé de 5 % ou plus face à ce qui était observé avant." : nil)71                } else {72                    if status == .verifiee, let gonflee = byStatus["gonflee"], gonflee > 0 {73                        HonestNote(text: "\(Fmt.group(gonflee)) soldes annoncés par les enseignes ne figurent pas ici : leur prix régulier dépasse ce qui était réellement observé, et le prix n'a pas baissé.")74                            .padding(.vertical, 10)75                    }76                    if hSize == .regular {77                        LazyVGrid(columns: [GridItem(.flexible(), spacing: 28), GridItem(.flexible(), spacing: 28)], alignment: .leading, spacing: 0) {78                            ForEach(products) { p in VStack(spacing: 0) { ProductRow(product: p, note: note(p)); Hairline() } }79                        }80                    } else {81                        ForEach(products) { p in82                            ProductRow(product: p, note: note(p))83                            Hairline()84                        }85                    }86                    if page < pages {87                        HStack { Spacer(); ProgressView(); Spacer() }.frame(height: 60)88                            .onAppear { Task { await more() } }89                    }90                }91            }92            .pageColumn(wide: hSize == .regular)93            .padding(.bottom, 30)94        }95        .paper()96        .navigationTitle(root ? "Soldes" : "Baisses vérifiées")97        .navigationBarTitleDisplayMode(root ? .large : .inline)98        .task(id: [kind ?? "", status.rawValue]) { await reload() }99        .refreshable { await reload() }100    }101102    /// « Metro · était 7,97 $ » : le prix observé avant, pas le prix régulier annoncé.103    private func note(_ p: Product) -> String {104        var s = p.storeName105        if status != .verifiee {106            // sans baisse vérifiée, on montre ce que l'enseigne annonce, nommé comme tel107            if let r = p.deal?.declaredRegular ?? p.regularPrice { s += " · prix régulier annoncé " + Fmt.price(r) }108        } else if let ref = p.deal?.referencePrice { s += " · était " + Fmt.price(ref) }109        if p.isFlyer, let to = p.validTo { s += " · jusqu'au " + Fmt.shortDate(to) }110        return s111    }112113    private func flyerStrip(_ f: FlyersResponse) -> some View {114        VStack(alignment: .leading, spacing: 6) {115            SectionHeader("Circulaires en cours", note: "\(f.total) circulaires, \(Fmt.group(f.nProducts)) rabais. Zone de Montréal.") {116                MoreLink { model.open(.flyers) }117            }118            ForEach(f.flyers.filter { $0.n > 0 }.sorted { $0.n > $1.n }.prefix(4)) { fl in119                FlyerRow(flyer: fl)120                Hairline()121            }122        }123    }124125    private func reload() async {126        loading = true; failure = nil127        if root, flyers == nil { flyers = try? await APIClient.shared.flyers().value }128        do {129            let r = try await APIClient.shared.deals(status: status.rawValue, kind: kind)130            if Task.isCancelled { return }131            products = r.value.products; byStatus = r.value.byStatus132            total = r.value.total; page = 1; pages = r.value.pages; stale = r.stale133        } catch is CancellationError {134            return135        } catch {136            products = []137            failure = (error as? APIError) ?? .offline138        }139        loading = false140    }141142    private func more() async {143        guard page < pages else { return }144        let k = kind, st = status145        guard let r = try? await APIClient.shared.deals(status: st.rawValue, kind: k, page: page + 1), k == kind, st == status else { return }146        let known = Set(products.map(\.id))147        products.append(contentsOf: r.value.products.filter { !known.contains($0.id) })148        page = r.value.page; pages = r.value.pages149    }150}151152/// Ligne de circulaire : enseigne, dates de validité, nombre de rabais et de baisses vérifiées.153struct FlyerRow: View {154    let flyer: Flyer155    @Environment(AppModel.self) private var model156157    var body: some View {158        Button { model.open(.flyer(flyer.store)) } label: {159            HStack(alignment: .center, spacing: 12) {160                Image("ic-circulaire").resizable().scaledToFit().frame(width: 24, height: 24).foregroundStyle(Theme.ink2)161                VStack(alignment: .leading, spacing: 2) {162                    Text(flyer.storeName).font(.body.weight(.medium)).foregroundStyle(Theme.ink)163                    Text(flyer.n == 0 && flyer.nUpcoming > 0164                         ? "à venir" + (flyer.validFrom.map { " le " + Fmt.shortDate($0) } ?? "")165                         : [Fmt.range(flyer.validFrom, flyer.validTo), Fmt.remaining(flyer.validTo)].compactMap { $0 }.joined(separator: " · "))166                        .font(.caption).monospacedDigit().foregroundStyle(Theme.ink3).multilineTextAlignment(.leading)167                }168                Spacer(minLength: 4)169                VStack(alignment: .trailing, spacing: 1) {170                    Text(Fmt.plural(flyer.n == 0 ? flyer.nUpcoming : flyer.n, "rabais", "rabais")).font(.subheadline.weight(.medium)).monospacedDigit().foregroundStyle(Theme.ink)171                    if flyer.nVerifiedDeals > 0 {172                        Text("\(flyer.nVerifiedDeals) \(flyer.nVerifiedDeals < 2 ? "vérifié" : "vérifiés")").font(.caption).monospacedDigit().foregroundStyle(Theme.good)173                    }174                }175                Image(systemName: "chevron.right").font(.caption.weight(.semibold)).foregroundStyle(Theme.ink3)176            }177            .frame(minHeight: 58).contentShape(Rectangle())178        }179        .buttonStyle(.plain)180        .accessibilityElement(children: .ignore)181        .accessibilityLabel("Circulaire \(flyer.storeName), \(Fmt.range(flyer.validFrom, flyer.validTo) ?? ""), \(flyer.n) rabais, \(flyer.nVerifiedDeals) baisses vérifiées")182        .accessibilityAddTraits(.isButton)183        .accessibilityIdentifier("flyer-\(flyer.store)")184    }185}186187struct FlyersView: View {188    @State private var state: Loadable<FlyersResponse> = .loading189190    var body: some View {191        ScrollView {192            LazyVStack(alignment: .leading, spacing: 0) {193                switch state {194                case .loading: LoadingShelves()195                case .failed(let e): ErrorState(error: e) { Task { await load() } }196                case .loaded(let f, let stale):197                    if stale { StaleBanner().padding(.vertical, 8) }198                    Text("\(f.total) circulaires en cours, \(Fmt.group(f.nProducts)) rabais."199                         + (f.nUpcoming > 0 ? " \(Fmt.group(f.nUpcoming)) rabais à venir." : "")200                         + (f.nExpired > 0 ? " \(Fmt.group(f.nExpired)) rabais échus, en attente du prochain relevé." : ""))201                        .font(.subheadline).monospacedDigit().foregroundStyle(Theme.ink3).padding(.vertical, 8)202                        .fixedSize(horizontal: false, vertical: true)203                    ForEach(f.flyers.sorted { $0.storeName.localizedCompare($1.storeName) == .orderedAscending }) { fl in204                        FlyerRow(flyer: fl)205                        Hairline()206                    }207                    if let n = f.note { HonestNote(text: n).padding(.top, 16) }208                }209            }210            .pageColumn().padding(.bottom, 30)211        }212        .paper()213        .navigationTitle("Circulaires")214        .navigationBarTitleDisplayMode(.inline)215        .task { await load() }216    }217218    private func load() async {219        if let s = await Loadable.from({ try await APIClient.shared.flyers() }) { state = s }220    }221}222223/// La circulaire d'une enseigne : tous ses rabais en cours, par rayon.224struct FlyerView: View {225    let store: String226    @Environment(\.horizontalSizeClass) private var hSize227    @State private var state: Loadable<Flyer> = .loading228    @State private var verifiedOnly = false229    @State private var showUpcoming = false230231    var body: some View {232        ScrollView {233            LazyVStack(alignment: .leading, spacing: 0) {234                switch state {235                case .loading: LoadingShelves()236                case .failed(let e):237                    if e == .notFound {238                        EmptyShelf(title: "Pas de circulaire en cours", message: "Cette enseigne n'a aucune circulaire en vigueur aujourd'hui.")239                    } else {240                        ErrorState(error: e) { Task { await load() } }241                    }242                case .loaded(let f, let stale):243                    if stale { StaleBanner().padding(.vertical, 8) }244                    VStack(alignment: .leading, spacing: 6) {245                        Text("Circulaire").eyebrowStyle()246                        Text(f.storeName).font(.editorial(28)).foregroundStyle(Theme.ink).accessibilityAddTraits(.isHeader)247                        if let r = Fmt.range(f.validFrom, f.validTo) {248                            Text("Valide \(r)" + (Fmt.remaining(f.validTo).map { " · \($0)" } ?? "") + ".")249                                .font(.subheadline).monospacedDigit().foregroundStyle(Theme.ink2)250                                .accessibilityIdentifier("flyer-validity")251                        }252                        Text("\(Fmt.plural(f.n, "rabais", "rabais")), dont \(f.nVerifiedDeals) \(f.nVerifiedDeals < 2 ? "baisse vérifiée" : "baisses vérifiées") face au prix observé avant."253                             + (f.nUpcoming > 0 ? " \(f.nUpcoming) rabais d'une circulaire à venir ne sont pas encore publics." : ""))254                            .font(.subheadline).monospacedDigit().foregroundStyle(Theme.ink3).fixedSize(horizontal: false, vertical: true)255                    }256                    .padding(.top, 8)257                    if f.longValidityItems > 0, let m = f.validToMax {258                        HonestNote(text: "\(Fmt.plural(f.longValidityItems, "rabais dure", "rabais durent")) plus longtemps que le cahier principal, jusqu'au \(Fmt.dayMonth(m)) au plus : la date figure sur chaque fiche.")259                            .padding(.top, 6)260                    }261                    FlowLayout(spacing: 8) {262                        Chip(label: "Tous les rabais", selected: !verifiedOnly && !showUpcoming) { verifiedOnly = false; showUpcoming = false }263                        Chip(label: "Baisses vérifiées", selected: verifiedOnly && !showUpcoming, count: f.nVerifiedDeals) { verifiedOnly = true; showUpcoming = false }264                        if !f.upcomingProducts.isEmpty {265                            Chip(label: "À venir", selected: showUpcoming, count: f.upcomingProducts.count) { showUpcoming = true }266                                .accessibilityIdentifier("flyer-upcoming")267                        }268                    }269                    .padding(.top, 10)270                    if showUpcoming {271                        HonestNote(text: "Rabais d'un cahier déjà publié, pas encore en vigueur : le prix ne vaut qu'à partir de la date indiquée.")272                            .padding(.top, 10)273                    }274                    let groups = grouped(showUpcoming ? f.upcomingProducts : f.products.filter { !verifiedOnly || $0.deal?.status == .verifiee })275                    if f.products.isEmpty, !showUpcoming {276                        EmptyShelf(title: "Aucun rabais en cours", message: f.upcomingProducts.isEmpty ? nil : "Cette circulaire commence bientôt : voyez l'onglet « À venir ».")277                    } else if groups.isEmpty {278                        EmptyShelf(title: "Aucune baisse vérifiée dans cette circulaire",279                                   message: "Les rabais annoncés n'ont pas de prix de référence observé, ou le prix n'a pas réellement baissé.")280                    }281                    ForEach(groups, id: \.0) { g in282                        HStack(spacing: 10) {283                            Image(Category.icon(name: g.0)).resizable().scaledToFit().frame(width: 22, height: 22).foregroundStyle(Theme.ink2)284                            Text(g.0).font(.editorial(19)).foregroundStyle(Theme.ink)285                            Spacer()286                            Text(Fmt.group(g.1.count)).font(.subheadline).monospacedDigit().foregroundStyle(Theme.ink3)287                        }288                        .padding(.top, 26).padding(.bottom, 6)289                        .accessibilityAddTraits(.isHeader)290                        ShelfBar(thickness: 2.5)291                        if hSize == .regular {292                            LazyVGrid(columns: [GridItem(.flexible(), spacing: 28), GridItem(.flexible(), spacing: 28)], alignment: .leading, spacing: 0) {293                                ForEach(g.1) { p in VStack(spacing: 0) { ProductRow(product: p, note: upcomingNote(p), showStore: false); Hairline() } }294                            }295                        } else {296                            ForEach(g.1) { p in297                                ProductRow(product: p, note: upcomingNote(p), showStore: false)298                                Hairline()299                            }300                        }301                    }302                    HonestNote(text: "Circulaire de la zone de Montréal. Les conditions (carte de membre, limite, taxes) figurent sur chaque fiche, telles que l'enseigne les publie.")303                        .padding(.top, 20)304                }305            }306            .pageColumn(wide: hSize == .regular).padding(.bottom, 30)307        }308        .paper()309        .navigationBarTitleDisplayMode(.inline)310        .task { await load() }311    }312313    private func upcomingNote(_ p: Product) -> String? {314        guard showUpcoming else { return nil }315        return "à venir" + (Fmt.range(p.validFrom, p.validTo).map { ", " + $0 } ?? "")316    }317318    private func grouped(_ products: [Product]) -> [(String, [Product])] {319        Dictionary(grouping: products) { $0.category ?? "Autres" }320            .map { ($0.key, $0.value) }321            // « Autres » à la fin322            .sorted { ($0.0 == "Autres" ? 1 : 0, $0.0) < ($1.0 == "Autres" ? 1 : 0, $1.0) }323    }324325    private func load() async {326        if let s = await Loadable.from({ try await APIClient.shared.flyer(store) }) { state = s }327    }328}329
Files main
Menu

Theme