SPB Git

Repository Public

StoresView.swift 14.1 KB 281 lines swift

1//2//  Food-Ka iOS v23//  File: FoodKa/Features/Stores/StoresView.swift4//  Description: enseignes — la liste (niveau de prix relatif, fraîcheur du relevé, type) et la page d'une enseigne5//               (catalogue par rayon, marques, baisses vérifiées, circulaire, où ses prix sont relevés).6//7//  Author: Simon-Pierre Boucher8//  Contact: contact@spboucher.ai9//1011import SwiftUI1213struct StoresView: View {14    @State private var state: Loadable<StoresResponse> = .loading15    @State private var type: String?1617    var body: some View {18        ScrollView {19            LazyVStack(alignment: .leading, spacing: 0) {20                switch state {21                case .loading: LoadingShelves()22                case .failed(let e): ErrorState(error: e) { Task { await load() } }23                case .loaded(let r, let stale):24                    if stale { StaleBanner().padding(.vertical, 8) }25                    Text("\(r.total) enseignes, dont \(r.connected) relevées. \(Fmt.group(r.nProducts)) produits.")26                        .font(.subheadline).monospacedDigit().foregroundStyle(Theme.ink3).padding(.vertical, 8)27                    levels(r)28                    SectionHeader("Toutes les enseignes").padding(.top, 34)29                    ScrollView(.horizontal, showsIndicators: false) {30                        HStack(spacing: 8) {31                            Chip(label: "Toutes", selected: type == nil) { type = nil }32                            ForEach(r.typeLabels.keys.sorted { (r.typeLabels[$0] ?? "") < (r.typeLabels[$1] ?? "") }, id: \.self) { k in33                                Chip(label: r.typeLabels[k] ?? k, selected: type == k) { type = type == k ? nil : k }34                            }35                        }36                    }37                    .scrollClipDisabled().padding(.top, 6)38                    ForEach(r.stores.filter { type == nil || $0.type == type }.sorted { ($0.connected ? 0 : 1, $0.name) < ($1.connected ? 0 : 1, $1.name) }) { s in39                        StoreRow(store: s)40                        Hairline()41                    }42                }43            }44            .pageColumn().padding(.bottom, 30)45        }46        .paper()47        .navigationTitle("Enseignes")48        .navigationBarTitleDisplayMode(.inline)49        .task { await load() }50    }5152    /// Niveau de prix relatif : chaque enseigne sur un même rail, 100 au centre.53    @ViewBuilder54    private func levels(_ r: StoresResponse) -> some View {55        let ranked = r.ranked56        if !ranked.isEmpty {57            VStack(alignment: .leading, spacing: 10) {58                SectionHeader("Niveau de prix", note: "Sur les produits que chaque enseigne partage avec les autres. 100 est la médiane ; plus bas, c'est moins cher.")59                // chaque enseigne sur son rail : la barre part de la médiane (100), à gauche si c'est moins cher60                let spread = max(8, (ranked.compactMap { $0.priceLevel?.index }.map { abs($0 - 100) }.max() ?? 8) * 1.15)61                VStack(spacing: 0) {62                    ForEach(ranked) { s in63                        let v = s.priceLevel?.index ?? 10064                        HStack(spacing: 10) {65                            Text(s.name).font(.footnote).foregroundStyle(Theme.ink).lineLimit(1).minimumScaleFactor(0.8)66                                .frame(width: 118, alignment: .leading)67                            GeometryReader { geo in68                                let half = geo.size.width / 269                                let w = max(2, half * abs(v - 100) / spread)70                                ZStack(alignment: .leading) {71                                    Rectangle().fill(Theme.line).frame(height: 1).offset(y: 0)72                                    RoundedRectangle(cornerRadius: 2).fill(v <= 100 ? Theme.good : Theme.high)73                                        .frame(width: w, height: 8)74                                        .offset(x: v <= 100 ? half - w : half)75                                    Rectangle().fill(Theme.ink).frame(width: 1.5, height: geo.size.height).offset(x: half - 0.75)76                                }77                                .frame(height: geo.size.height)78                            }79                            .frame(height: 30)80                            Text(Fmt.number(v, digits: 1)).font(.footnote.weight(.semibold)).monospacedDigit().foregroundStyle(Theme.ink)81                                .frame(width: 46, alignment: .trailing)82                        }83                        .accessibilityElement(children: .ignore)84                        .accessibilityLabel("\(s.name) : \(Fmt.number(v, digits: 1))")85                    }86                }87                .accessibilityIdentifier("price-level-chart")88                if let m = r.priceLevelMethod { HonestNote(text: m) }89                let outside = r.stores.filter { !$0.comparable && $0.n > 0 }.map(\.name)90                if !outside.isEmpty {91                    HonestNote(text: outside.joined(separator: " et ") + " : prix relevés hors Québec, donc absents de ce classement.", icon: "exclamationmark.circle")92                }93            }94            .padding(.top, 10)95        }96    }9798    private func load() async {99        if let s = await Loadable.from({ try await APIClient.shared.stores() }) { state = s }100    }101}102103struct StoreView: View {104    let id: String105    @Environment(AppModel.self) private var model106    @Environment(Library.self) private var library107    @State private var state: Loadable<Store> = .loading108    @State private var safari: IdentifiedURL?109110    var body: some View {111        ScrollView {112            LazyVStack(alignment: .leading, spacing: 0) {113                switch state {114                case .loading: LoadingShelves()115                case .failed(let e): ErrorState(error: e) { Task { await load() } }116                case .loaded(let s, let stale):117                    if stale { StaleBanner().padding(.vertical, 8) }118                    content(s)119                }120            }121            .padding(.bottom, 30)122        }123        .paper()124        .navigationBarTitleDisplayMode(.inline)125        .sheet(item: $safari) { SafariView(url: $0.url).ignoresSafeArea() }126        .task { await load() }127    }128129    @ViewBuilder130    private func content(_ s: Store) -> some View {131        VStack(alignment: .leading, spacing: 8) {132            Text([s.typeLabel, s.region].compactMap { $0 }.joined(separator: " · ")).eyebrowStyle()133            Text(s.name).font(.editorial(28)).foregroundStyle(Theme.ink).accessibilityAddTraits(.isHeader)134                .accessibilityIdentifier("store-title")135            if let f = s.freshness {136                Text(f.label + (Fmt.age(hours: f.ageHours).map { ", " + $0 } ?? "") + ".")137                    .font(.subheadline).foregroundStyle(f.isCurrent ? Theme.ink3 : Theme.high)138            } else if !s.connected {139                Text("Enseigne connue, mais non relevée.").font(.subheadline).foregroundStyle(Theme.high)140            }141            if let cov = s.coverage, let label = ServiceInfo.coverageLabel(cov) {142                // un catalogue relevé en partie se dit : il limite l'appariement et les paniers143                Text("Couverture : \(label).").font(.subheadline).foregroundStyle(Theme.ink3)144                    .accessibilityIdentifier("store-coverage")145            }146            if let scope = s.priceScope, let note = scope.note {147                HonestNote(text: note, icon: scope.needsWarning ? "exclamationmark.circle" : "info.circle").padding(.top, 2)148            }149        }150        .pageColumn().padding(.top, 8)151152        FigureGrid {153            Figure(label: "Produits publics", value: Fmt.group(s.n), note: "\(Fmt.group(s.nCatalogue)) au catalogue, \(Fmt.group(s.nFlyer)) en circulaire")154            if let i = s.priceLevel?.index {155                Figure(label: "Niveau de prix", value: Fmt.number(i, digits: 1),156                       note: (s.priceLevel?.rank).flatMap { r in (s.priceLevel?.of).map { "\(r)\(r == 1 ? "re" : "e") sur \($0) · \(Fmt.group(s.priceLevel?.nCommon ?? 0)) produits communs" } })157            } else {158                Figure(label: "Niveau de prix", value: "—", note: s.comparable ? "moins de 15 produits communs avec les autres enseignes" : "non mesuré : prix relevés hors Québec")159            }160            Figure(label: "Baisses vérifiées", value: Fmt.group(s.nDeals))161        }162        .pageColumn().padding(.top, 22)163164        VStack(spacing: 10) {165            Button {166                var f = SearchFilters(); f.stores = [s.id]167                model.openSearch(f)168            } label: { Text("Voir les \(Fmt.group(s.n)) produits") }169                .buttonStyle(PrimaryButtonStyle())170                .accessibilityIdentifier("store-products")171            HStack(spacing: 10) {172                if s.nFlyer > 0 {173                    Button("Circulaire") { model.open(.flyer(s.id)) }.buttonStyle(SecondaryButtonStyle())174                }175                Button(library.preferredStores.contains(s.id) ? "Préférée" : "Préférer") {176                    library.togglePreferred(s.id)177                    model.showToast(library.preferredStores.contains(s.id) ? "\(s.name) ajoutée aux enseignes préférées" : "\(s.name) retirée des enseignes préférées")178                }179                .buttonStyle(SecondaryButtonStyle())180                if let u = s.url.flatMap(URL.init(string:)), u.scheme == "https" {181                    Button("Site") { safari = IdentifiedURL(url: u) }.buttonStyle(SecondaryButtonStyle())182                }183            }184        }185        .pageColumn().padding(.top, 22)186187        if !s.topDeals.isEmpty {188            VStack(alignment: .leading, spacing: 12) {189                SectionHeader("Baisses vérifiées").pageColumn()190                ProductShelfRow(products: s.topDeals)191                    .frame(maxWidth: Theme.readable + 2 * Theme.margin).frame(maxWidth: .infinity)192            }193            .padding(.top, 34)194        }195        let levels = s.priceLevelByCategory.filter { $0.index != nil }196        if !levels.isEmpty {197            VStack(alignment: .leading, spacing: 4) {198                SectionHeader("Niveau de prix par rayon", note: "100 est la médiane des enseignes pour les produits communs du rayon ; plus bas, c'est moins cher.")199                ForEach(levels.sorted { ($0.index ?? 0) < ($1.index ?? 0) }) { l in200                    HStack(spacing: 12) {201                        Image(Category.icon(slug: l.slug)).resizable().scaledToFit().frame(width: 22, height: 22).foregroundStyle(Theme.ink2)202                        VStack(alignment: .leading, spacing: 1) {203                            Text(l.rayon).font(.subheadline.weight(.medium)).foregroundStyle(Theme.ink)204                            Text(Fmt.plural(l.n_common ?? 0, "produit commun", "produits communs")).font(.caption).monospacedDigit().foregroundStyle(Theme.ink3)205                        }206                        Spacer(minLength: 4)207                        Text(Fmt.number(l.index, digits: 1)).font(.display(17)).monospacedDigit()208                            .foregroundStyle((l.index ?? 100) <= 100 ? Theme.good : Theme.high)209                    }210                    .frame(minHeight: 50)211                    .accessibilityElement(children: .combine)212                    Hairline()213                }214            }215            .pageColumn().padding(.top, 34)216            .accessibilityIdentifier("price-level-by-category")217        }218        if !s.categories.isEmpty {219            VStack(alignment: .leading, spacing: 4) {220                SectionHeader("Par rayon")221                ForEach(s.categories) { c in222                    Button {223                        var f = SearchFilters(); f.stores = [s.id]; f.category = c.slug; f.categoryName = c.name224                        model.openSearch(f)225                    } label: {226                        HStack(spacing: 12) {227                            Image(c.icon).resizable().scaledToFit().frame(width: 22, height: 22).foregroundStyle(Theme.ink2)228                            Text(c.name).font(.body).foregroundStyle(Theme.ink)229                            Spacer()230                            Text(Fmt.group(c.n)).font(.subheadline).monospacedDigit().foregroundStyle(Theme.ink3)231                            Image(systemName: "chevron.right").font(.caption2.weight(.bold)).foregroundStyle(Theme.ink3)232                        }233                        .frame(minHeight: 48).contentShape(Rectangle())234                    }235                    .buttonStyle(.plain)236                    Hairline()237                }238            }239            .pageColumn().padding(.top, 34)240        }241        if !s.brands.isEmpty {242            VStack(alignment: .leading, spacing: 10) {243                SectionHeader("Marques les plus présentes")244                FlowLayout(spacing: 8) {245                    ForEach(s.brands.prefix(16)) { b in246                        Chip(label: b.name, count: b.n) {247                            var f = SearchFilters(); f.stores = [s.id]; f.brand = b.name248                            model.openSearch(f)249                        }250                    }251                }252            }253            .pageColumn().padding(.top, 34)254        }255        if !s.sample.isEmpty {256            VStack(alignment: .leading, spacing: 4) {257                SectionHeader("Quelques produits")258                ForEach(s.sample.prefix(8)) { p in259                    ProductRow(product: p, showStore: false)260                    Hairline()261                }262            }263            .pageColumn().padding(.top, 34)264        }265        if !s.sourceDetails.isEmpty {266            VStack(alignment: .leading, spacing: 4) {267                SectionHeader("Relevés", note: "État de chaque source de cette enseigne.")268                ForEach(s.sourceDetails) { d in269                    FactRow(d.name ?? d.id, [d.lastSuccess.flatMap { Fmt.ago($0) }, d.lastFound.map { "\(Fmt.group($0)) trouvés" }, d.lastOk == false ? "dernier essai en échec" : nil]270                        .compactMap { $0 }.joined(separator: " · "))271                }272            }273            .pageColumn().padding(.top, 34)274        }275    }276277    private func load() async {278        if let s = await Loadable.from({ try await APIClient.shared.store(id) }) { state = s }279    }280}281
Files main
Menu

Theme