SPB Git

Repository Public

BasketView.swift 25.4 KB 480 lines swift

1//2//  Food-Ka iOS v23//  File: FoodKa/Features/Basket/BasketView.swift4//  Description: la liste d'épicerie — articles, quantités, recherche libre, partage, et le coût par enseigne5//               (`POST /api/panier/comparer`) : le rail des totaux pour les enseignes qui offrent toute la liste,6//               la meilleure répartition entre deux enseignes, et les articles manquants des autres. Jamais de7//               total pour une liste incomplète. Tout vit sur l'appareil et fonctionne hors ligne.8//9//  Author: Simon-Pierre Boucher10//  Contact: contact@spboucher.ai11//1213import SwiftUI1415struct BasketView: View {16    @Environment(AppModel.self) private var model17    @Environment(GroceryList.self) private var list18    @State private var draft = ""19    @FocusState private var adding: Bool20    @State private var confirmClear = false21    @State private var shown: BasketComparison.StoreResult?22    @State private var allIncomplete = false2324    var body: some View {25        ScrollViewReader { proxy in26        ScrollView {27            VStack(alignment: .leading, spacing: 0) {28                heading29                addField.padding(.top, 14)30                if list.isEmpty {31                    EmptyShelf(title: "Votre liste est vide",32                               message: "Ajoutez un produit depuis une fiche ou une recherche avec le bouton +, ou écrivez simplement « bananes » ci-dessus. La liste reste sur cet appareil et fonctionne sans réseau.",33                               actionLabel: "Chercher un produit") { model.tab = .home }34                        .accessibilityIdentifier("basket-empty")35                } else {36                    lines.padding(.top, 10)37                    Button { model.storeMode = true } label: {38                        HStack(spacing: 8) {39                            Image("ic-liste").resizable().scaledToFit().frame(width: 20, height: 20)40                            Text("À l'épicerie")41                        }42                    }43                    .buttonStyle(SecondaryButtonStyle())44                    .padding(.top, 18)45                    .accessibilityHint("Gros texte, cases à cocher, tri par rayon, écran qui reste allumé")46                    .accessibilityIdentifier("store-mode-button")47                    comparison.padding(.top, 34).id("compare")48                }49            }50            .pageColumn()51            .padding(.bottom, 40)52        }53        .task {54            // ancre demandée au lancement (capture du coût par enseigne)55            guard UserDefaults.standard.string(forKey: "FKBasketAnchor") == "compare" else { return }56            try? await Task.sleep(for: .seconds(5))57            proxy.scrollTo("compare", anchor: .top)58        }59        }60        .scrollDismissesKeyboard(.immediately)61        .paper()62        .navigationTitle("Liste d'épicerie")63        .toolbar {64            ToolbarItemGroup(placement: .topBarTrailing) {65                if !list.isEmpty {66                    ShareLink(item: list.shareText) { Image(systemName: "square.and.arrow.up") }67                        .accessibilityLabel("Partager la liste")68                        .accessibilityIdentifier("share-list")69                    Menu {70                        Button("Tout décocher", systemImage: "square") { list.uncheckAll() }71                        Button("Retirer les articles cochés", systemImage: "checkmark.square") { list.removeChecked() }72                        Button("Vider la liste", systemImage: "trash", role: .destructive) { confirmClear = true }73                    } label: {74                        Image(systemName: "ellipsis.circle")75                    }76                    .accessibilityLabel("Actions sur la liste")77                }78            }79        }80        .confirmationDialog("Vider la liste d'épicerie ?", isPresented: $confirmClear, titleVisibility: .visible) {81            Button("Vider la liste", role: .destructive) { list.clear() }82        }83        .sheet(item: $shown) { r in84            BasketStoreSheet(result: r).presentationDetents([.large])85        }86        // la comparaison suit la liste : relancée peu après chaque changement87        .task(id: list.signature) {88            guard !list.isEmpty, !list.comparisonIsCurrent else { return }89            try? await Task.sleep(for: .milliseconds(700))90            if Task.isCancelled { return }91            await list.compare()92        }93    }9495    private var heading: some View {96        Group {97            if !list.isEmpty {98                Text("\(Fmt.plural(list.count, "article", "articles"))" + (list.remaining < list.count ? ", \(list.remaining) à trouver" : ""))99                    .font(.subheadline).monospacedDigit().foregroundStyle(Theme.ink3)100                    .accessibilityIdentifier("basket-count")101            }102        }103    }104105    private var addField: some View {106        HStack(spacing: 10) {107            Image(systemName: "plus").foregroundStyle(Theme.ink3)108            TextField("Ajouter un article : bananes, beurre salé 454 g", text: $draft)109                .focused($adding)110                .submitLabel(.done)111                .onSubmit(addDraft)112                .accessibilityIdentifier("basket-add-field")113            if !draft.isEmpty {114                Button("Ajouter", action: addDraft).font(.subheadline.weight(.semibold)).foregroundStyle(Theme.brand)115                    .frame(minHeight: 44)116            }117        }118        .padding(.horizontal, 14).frame(minHeight: 50)119        .background(Theme.surface, in: RoundedRectangle(cornerRadius: Theme.radius, style: .continuous))120        .overlay(RoundedRectangle(cornerRadius: Theme.radius, style: .continuous).strokeBorder(adding ? Theme.brand : Theme.line2, lineWidth: adding ? 1.5 : 1))121    }122123    private func addDraft() {124        let q = draft.trimmingCharacters(in: .whitespacesAndNewlines)125        guard !q.isEmpty else { return }126        if list.add(query: q) {127            draft = ""128            Haptics.soft()129        } else {130            model.showToast("La liste est pleine (\(GroceryList.maxItems) articles)")131        }132    }133134    // --- Lignes -----------------------------------------------------------------------------------------135136    private var lines: some View {137        VStack(spacing: 0) {138            ForEach(Array(list.items.enumerated()), id: \.element.id) { i, item in139                BasketLine(item: item, index: i)140                Hairline()141            }142        }143    }144145    // --- Coût par enseigne ------------------------------------------------------------------------------146147    @ViewBuilder private var comparison: some View {148        VStack(alignment: .leading, spacing: 14) {149            SectionHeader("Coût par enseigne", eyebrow: "Le rail des prix") {150                if list.comparing { ProgressView().controlSize(.small) }151            }152            if let error = list.compareError {153                VStack(alignment: .leading, spacing: 8) {154                    HonestNote(text: error + (list.comparison != nil ? " La dernière comparaison reste affichée." : " La liste reste utilisable sans réseau."), icon: "wifi.slash")155                    Button("Réessayer") { Task { await list.compare() } }156                        .font(.subheadline.weight(.medium)).foregroundStyle(Theme.brand).frame(minHeight: 44)157                }158                .accessibilityIdentifier("compare-error")159            }160            if let c = list.comparison {161                if !list.comparisonIsCurrent, !list.comparing {162                    HonestNote(text: "La liste a changé depuis cette comparaison" + (list.comparedAt.map { " (" + (Fmt.ago($0.timeIntervalSince1970) ?? "") + ")" } ?? "") + ".")163                }164                totals(c)165                pair(c)166                incomplete(c)167                if !c.unresolved.isEmpty {168                    VStack(alignment: .leading, spacing: 4) {169                        Text("Introuvables").eyebrowStyle()170                        ForEach(c.unresolved, id: \.line) { u in171                            Text("\(u.label) : \(u.error ?? "aucune réponse dans les enseignes relevées").")172                                .font(.subheadline).foregroundStyle(Theme.ink2).fixedSize(horizontal: false, vertical: true)173                        }174                    }175                }176                VStack(alignment: .leading, spacing: 6) {177                    HonestNote(text: "Un total n'est donné que pour une enseigne qui offre toute la liste. Les catalogues relevés sont partiels : un panier courant est rarement complet dans plus de deux ou trois enseignes.")178                    if !c.excludedStores.isEmpty {179                        HonestNote(text: c.excludedStores.map(\.store_name).joined(separator: " et ") + " : prix relevés hors Québec, non comparés.", icon: "exclamationmark.circle")180                            .accessibilityIdentifier("basket-excluded")181                    }182                    HonestNote(text: "La liste est envoyée au service le temps du calcul ; il n'en garde rien.", icon: "lock")183                    if let at = list.comparedAt {184                        Text("Comparé \(Fmt.ago(at.timeIntervalSince1970) ?? "à l'instant") dans \(c.storesCompared) enseignes.")185                            .font(.footnote).monospacedDigit().foregroundStyle(Theme.ink3)186                    }187                }188                .padding(.top, 6)189            } else if list.comparing {190                LoadingShelves(rows: 2, label: "Comparaison en cours")191            } else if list.compareError == nil {192                Button("Comparer les enseignes") { Task { await list.compare() } }.buttonStyle(PrimaryButtonStyle())193            }194        }195    }196197    @ViewBuilder198    private func totals(_ c: BasketComparison) -> some View {199        let complete = c.complete200        if complete.isEmpty {201            Text(c.statement ?? "Aucune enseigne n'offre toute la liste.")202                .font(.editorial(19)).foregroundStyle(Theme.ink).fixedSize(horizontal: false, vertical: true)203                .accessibilityIdentifier("basket-statement")204            Text("Aucun total n'est affiché : il ne porterait que sur une partie de la liste.")205                .font(.subheadline).foregroundStyle(Theme.ink2).fixedSize(horizontal: false, vertical: true)206        } else {207            Text("Pour les \(c.linesResolved) articles, dans les enseignes qui les offrent tous.")208                .font(.subheadline).monospacedDigit().foregroundStyle(Theme.ink3)209            AnimatedPriceRail(rows: complete.map { s in210                RailRow(id: s.store, name: s.storeName,211                        detail: Fmt.plural(s.found, "article", "articles") + (s.substitutions > 0 ? " · " + Fmt.plural(s.substitutions, "substitution", "substitutions") : ""),212                        value: s.total ?? 0)213            }, bestLabel: "le moins cher") { row in214                shown = c.stores.first { $0.store == row.id }215            }216            if let s = c.statement {217                Text(s).font(.editorial(19)).foregroundStyle(Theme.ink).fixedSize(horizontal: false, vertical: true)218                    .accessibilityIdentifier("basket-statement")219            }220            if complete.contains(where: { $0.substitutions > 0 }) {221                HonestNote(text: "Un total avec substitution compte un produit équivalent, pas le produit demandé. Touchez l'enseigne pour voir lequel.", icon: "arrow.triangle.2.circlepath")222            }223        }224    }225226    @ViewBuilder227    private func pair(_ c: BasketComparison) -> some View {228        if let p = c.bestPair, let split = p.split, split.count == 2 {229            VStack(alignment: .leading, spacing: 8) {230                Text("En deux arrêts").eyebrowStyle().padding(.top, 10)231                if p.complete == true, let total = p.total {232                    HStack(alignment: .firstTextBaseline) {233                        Text(split.map(\.store_name).joined(separator: " et ")).font(.body.weight(.semibold)).foregroundStyle(Theme.ink)234                        Spacer(minLength: 8)235                        Text(Fmt.price(total)).font(.display(20)).monospacedDigit().foregroundStyle(Theme.ink)236                    }237                    if let s = p.savings_vs_best_single, s > 0.004, let single = c.bestSingle {238                        Text("\(Fmt.price(s)) de moins qu'en achetant tout chez \(single.store_name).")239                            .font(.subheadline).monospacedDigit().foregroundStyle(Theme.ink2)240                    }241                } else {242                    Text(split.map(\.store_name).joined(separator: " et ")).font(.body.weight(.semibold)).foregroundStyle(Theme.ink)243                    Text("La meilleure paire couvre \(p.covered ?? 0) articles sur \(c.linesRequested) : pas de total.")244                        .font(.subheadline).monospacedDigit().foregroundStyle(Theme.ink2)245                }246                ForEach(split) { part in247                    Button { shown = c.stores.first { $0.store == part.store } } label: {248                        HStack(alignment: .firstTextBaseline) {249                            Text("\(part.store_name) · \(Fmt.plural(part.lines.count, "article", "articles"))").font(.subheadline).foregroundStyle(Theme.ink2)250                            Spacer(minLength: 8)251                            Text(Fmt.price(part.subtotal)).font(.subheadline.weight(.medium)).monospacedDigit().foregroundStyle(Theme.ink2)252                            Image(systemName: "chevron.right").font(.caption2.weight(.bold)).foregroundStyle(Theme.ink3)253                        }254                        .frame(minHeight: 40).contentShape(Rectangle())255                    }256                    .buttonStyle(.plain)257                    Hairline()258                }259            }260            .accessibilityIdentifier("basket-pair")261        }262    }263264    @ViewBuilder265    private func incomplete(_ c: BasketComparison) -> some View {266        let inc = c.incomplete267        if !inc.isEmpty {268            VStack(alignment: .leading, spacing: 0) {269                Text("Enseignes où il manque des articles").eyebrowStyle().padding(.top, 12).padding(.bottom, 4)270                ForEach(allIncomplete ? inc : Array(inc.prefix(4))) { s in271                    Button { shown = s } label: {272                        VStack(alignment: .leading, spacing: 3) {273                            HStack(alignment: .firstTextBaseline) {274                                Text(s.storeName).font(.subheadline.weight(.semibold)).foregroundStyle(Theme.ink)275                                Spacer(minLength: 8)276                                Text("\(s.found) sur \(c.linesRequested)").font(.subheadline).monospacedDigit().foregroundStyle(Theme.ink2)277                                Image(systemName: "chevron.right").font(.caption2.weight(.bold)).foregroundStyle(Theme.ink3)278                            }279                            Text("Absent : " + s.missing.map(\.label).joined(separator: ", ") + ".")280                                .font(.caption).foregroundStyle(Theme.ink3).lineLimit(3).multilineTextAlignment(.leading)281                            // partiel : dit comme tel, jamais classé avec les totaux282                            if let p = s.partialTotal {283                                Text("\(Fmt.price(p)) pour les \(s.found) articles trouvés, sans les absents.")284                                    .font(.caption).monospacedDigit().foregroundStyle(Theme.ink3)285                            }286                        }287                        .padding(.vertical, 10).contentShape(Rectangle())288                    }289                    .buttonStyle(.plain)290                    .accessibilityIdentifier("incomplete-\(s.store)")291                    Hairline()292                }293                if inc.count > 4 {294                    Button(allIncomplete ? "Moins d'enseignes" : "Les \(inc.count) enseignes incomplètes") { allIncomplete.toggle() }295                        .font(.subheadline).foregroundStyle(Theme.brand).frame(minHeight: 44)296                }297            }298        }299    }300}301302/// Ligne de la liste : vignette posée sur sa petite tablette, nom, marque et format, quantité, prix et enseigne.303struct BasketLine: View {304    let item: GroceryItem305    let index: Int306    @Environment(AppModel.self) private var model307    @Environment(GroceryList.self) private var list308    @Environment(\.dynamicTypeSize) private var typeSize309    @State private var box = FrameBox()310311    var body: some View {312        HStack(alignment: .center, spacing: 12) {313            Button {314                // depuis le panier : geste compact315                if let p = item.product { model.openProduct(p, from: box.rect, trigger: .secondary) }316                else if let q = item.query { var f = SearchFilters(); f.q = q; model.openSearch(f) }317            } label: {318                HStack(alignment: .center, spacing: 12) {319                    VStack(spacing: 0) {320                        Group {321                            if let p = item.product {322                                ProductPhoto(source: p.image, maxPixel: 160, icon: Category.icon(name: p.category), flyer: p.isFlyer)323                            } else {324                                Image(systemName: "magnifyingglass").font(.system(size: 18)).foregroundStyle(Theme.ink3)325                                    .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .bottom).padding(.bottom, 8)326                            }327                        }328                        .frame(width: 44, height: 42)329                        .sourceFrame(box)330                        .dropOnShelf(index)331                        ShelfBar(thickness: 2.5).frame(width: 48)332                    }333                    VStack(alignment: .leading, spacing: 2) {334                        Text(item.title).font(.editorial(16)).foregroundStyle(Theme.ink).lineLimit(2).multilineTextAlignment(.leading)335                        if let s = item.subtitle { Text(s).font(.caption).foregroundStyle(Theme.ink3).lineLimit(1) }336                        if let p = item.product {337                            Text("\(Fmt.price(p.price)) · \(p.storeName)").font(.caption).monospacedDigit().foregroundStyle(Theme.ink2).lineLimit(1)338                        } else {339                            Text("chercher un produit précis").font(.caption).foregroundStyle(Theme.brand)340                        }341                    }342                    Spacer(minLength: 0)343                }344                .contentShape(Rectangle())345            }346            .buttonStyle(.plain)347            .accessibilityElement(children: .ignore)348            .accessibilityLabel(item.title + (item.subtitle.map { ", " + $0 } ?? "") + (item.product.map { ", \(Fmt.price($0.price)) chez \($0.storeName)" } ?? ""))349            .accessibilityAddTraits(.isButton)350            .accessibilityIdentifier("basket-line-\(index)")351            stepper352        }353        .padding(.vertical, 10)354        .contextMenu {355            Button("Retirer de la liste", systemImage: "trash", role: .destructive) { list.remove(item.id) }356        }357    }358359    private var stepper: some View {360        HStack(spacing: 0) {361            Button { list.setQuantity(item.id, item.quantity - 1); Haptics.select() } label: {362                Image(systemName: item.quantity <= 1 ? "trash" : "minus").font(.system(size: 13, weight: .semibold))363                    .frame(width: 38, height: 44).contentShape(Rectangle())364            }365            .accessibilityLabel(item.quantity <= 1 ? "Retirer \(item.title)" : "Diminuer la quantité de \(item.title)")366            .accessibilityIdentifier("qty-minus-\(index)")367            Text(Fmt.quantity(item.quantity)).font(.subheadline.weight(.semibold)).monospacedDigit().frame(minWidth: 22)368                .accessibilityLabel("Quantité : \(Fmt.quantity(item.quantity))")369                .accessibilityIdentifier("qty-\(index)")370            Button { list.setQuantity(item.id, item.quantity + 1); Haptics.select() } label: {371                Image(systemName: "plus").font(.system(size: 13, weight: .semibold))372                    .frame(width: 38, height: 44).contentShape(Rectangle())373            }374            .accessibilityLabel("Augmenter la quantité de \(item.title)")375            .accessibilityIdentifier("qty-plus-\(index)")376        }377        .buttonStyle(.plain)378        .foregroundStyle(Theme.ink)379        .background(RoundedRectangle(cornerRadius: Theme.radiusSmall, style: .continuous).strokeBorder(Theme.line2, lineWidth: 1).padding(.vertical, 5))380    }381}382383/// Le détail d'une enseigne pour la liste : l'offre retenue pour chaque ligne, les substitutions signalées, les absents.384struct BasketStoreSheet: View {385    let result: BasketComparison.StoreResult386    @Environment(GroceryList.self) private var list387    @Environment(\.dismiss) private var dismiss388389    var body: some View {390        NavigationStack {391            ScrollView {392                VStack(alignment: .leading, spacing: 0) {393                    if let total = result.total {394                        HStack(alignment: .firstTextBaseline) {395                            Text("Total pour toute la liste").font(.subheadline).foregroundStyle(Theme.ink3)396                            Spacer()397                            Text(Fmt.price(total)).font(.display(26)).monospacedDigit().foregroundStyle(Theme.ink)398                        }399                        .padding(.vertical, 12)400                    } else {401                        VStack(alignment: .leading, spacing: 4) {402                            Text("Liste incomplète : pas de total").font(.editorial(19)).foregroundStyle(Theme.ink)403                            if let p = result.partialTotal {404                                Text("\(Fmt.price(p)) pour les \(result.found) articles trouvés. Ce montant ne se compare pas aux totaux des autres enseignes.")405                                    .font(.subheadline).monospacedDigit().foregroundStyle(Theme.ink2).fixedSize(horizontal: false, vertical: true)406                            }407                        }408                        .padding(.vertical, 12)409                    }410                    ShelfBar(thickness: 3)411                    ForEach(result.lines) { l in412                        line(l)413                        Hairline()414                    }415                    if !result.missing.isEmpty {416                        Text("Absents chez \(result.storeName)").eyebrowStyle().padding(.top, 20).padding(.bottom, 6)417                        ForEach(result.missing, id: \.line) { m in418                            HStack {419                                SmallTag(text: "", kind: .absent, width: 56, height: 26)420                                Text(m.label).font(.subheadline).foregroundStyle(Theme.ink2)421                                Spacer()422                            }423                            .padding(.vertical, 6)424                        }425                    }426                }427                .padding(.horizontal, Theme.margin)428                .padding(.bottom, 30)429            }430            .paper()431            .navigationTitle(result.storeName)432            .navigationBarTitleDisplayMode(.inline)433            .toolbar { ToolbarItem(placement: .topBarTrailing) { Button("Fermer") { dismiss() } } }434        }435    }436437    private func line(_ l: BasketComparison.Line) -> some View {438        VStack(alignment: .leading, spacing: 4) {439            HStack(alignment: .top, spacing: 10) {440                VStack(alignment: .leading, spacing: 2) {441                    Text(l.product?.name ?? "Article").font(.editorial(16)).foregroundStyle(Theme.ink).fixedSize(horizontal: false, vertical: true)442                    Text([l.product?.brandAndSize, l.product?.unitPrice?.label, l.product?.isFlyer == true ? "circulaire" : nil].compactMap { $0 }.joined(separator: " · "))443                        .font(.caption).monospacedDigit().foregroundStyle(Theme.ink3)444                }445                Spacer(minLength: 6)446                VStack(alignment: .trailing, spacing: 2) {447                    Text(Fmt.price(l.lineTotal)).font(.display(16)).monospacedDigit().foregroundStyle(Theme.ink)448                    if l.quantity != 1 {449                        Text("\(Fmt.quantity(l.quantity)) × \(Fmt.price(l.product?.price))").font(.caption).monospacedDigit().foregroundStyle(Theme.ink3)450                    }451                }452            }453            if let label = l.matchLabel {454                HStack(spacing: 6) {455                    Image(systemName: l.indicative ? "arrow.triangle.2.circlepath" : "checkmark").font(.caption2)456                    Text(label + (l.indicative ? (l.similarity.map { " (ressemblance " + Fmt.pct($0 * 100, signed: false) + ")" } ?? "") : ""))457                        .font(.caption.weight(.medium))458                }459                .foregroundStyle(l.indicative ? Theme.high : Theme.ink3)460            }461            if l.byWeight {462                Text("Vendu au poids : prix estimé, à la pièce, au kilo ou à la livre.").font(.caption).foregroundStyle(Theme.ink3)463            }464            // une substitution ou une réponse de recherche peut devenir le produit précis de la liste465            if l.indicative, let p = l.product, l.line < list.items.count, list.comparisonIsCurrent {466                Button("Mettre ce produit dans ma liste") {467                    // la ligne du panier ne porte pas l'enseigne : elle vient du résultat468                    var chosen = p469                    chosen.store = result.store; chosen.storeName = result.storeName470                    list.replace(list.items[l.line].id, with: chosen)471                    dismiss()472                }473                .font(.footnote.weight(.semibold)).foregroundStyle(Theme.brand).frame(minHeight: 40)474            }475        }476        .padding(.vertical, 10)477        .accessibilityElement(children: .contain)478    }479}480
Files main
Menu

Theme