Repository Public
1//2// Food-Ka iOS v23// File: FoodKa/Core/Store/GroceryList.swift4// Description: la liste d'épicerie — articles (un produit précis ou une recherche libre), quantités, cases cochées5// en magasin, dernière comparaison reçue. Tout vit sur l'appareil et fonctionne sans réseau ; la liste6// n'est envoyée au service que le temps de `POST /api/panier/comparer`.7//8// Author: Simon-Pierre Boucher9// Contact: contact@spboucher.ai10//1112import Foundation13import Observation1415/// Une ligne de la liste.16struct GroceryItem: Codable, Hashable, Sendable, Identifiable {17 var id: UUID18 /// produit précis (carte gardée pour l'affichage hors ligne) ; nul pour une recherche libre19 var product: Product?20 /// recherche libre : « bananes », « beurre salé 454 g »21 var query: String?22 var quantity: Double23 var checked: Bool24 var added: Date2526 init(product: Product, quantity: Double = 1) {27 id = UUID(); self.product = product; query = nil; self.quantity = quantity; checked = false; added = Date()28 }2930 init(query: String, quantity: Double = 1) {31 id = UUID(); product = nil; self.query = query; self.quantity = quantity; checked = false; added = Date()32 }3334 var title: String { product?.name ?? query ?? "Article" }35 var subtitle: String? { product?.brandAndSize ?? (query != nil ? "Recherche libre" : nil) }36 var category: String { product?.category ?? "Sans rayon" }37 var isFree: Bool { product == nil }38}3940@MainActor41@Observable42final class GroceryList {43 static let maxItems = 60 // limite du service44 static let maxQuantity = 99.04546 private(set) var items: [GroceryItem] = []47 /// dernière comparaison reçue et la signature de la liste qu'elle décrit48 private(set) var comparison: BasketComparison?49 private(set) var comparedAt: Date?50 private var comparedSignature: String?51 var comparing = false52 var compareError: String?53 /// enseignes auxquelles limiter la comparaison (réglage « enseignes préférées ») ; vide = toutes54 var stores: [String] = [] {55 didSet { if stores != oldValue { persist() } }56 }5758 private let file: URL?5960 private struct Snapshot: Codable {61 var items: [GroceryItem]62 var stores: [String]63 var comparison: BasketComparison?64 var comparedAt: Date?65 var comparedSignature: String?66 }6768 init(inMemory: Bool = false) {69 if inMemory {70 file = nil71 } else {72 let dir = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0]73 try? FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)74 file = dir.appending(path: "liste-epicerie.json")75 if let f = file, let d = try? Data(contentsOf: f), let s = try? JSONDecoder().decode(Snapshot.self, from: d) {76 items = s.items; stores = s.stores77 comparison = s.comparison; comparedAt = s.comparedAt; comparedSignature = s.comparedSignature78 }79 }80 }8182 private func persist() {83 guard let file else { return }84 let s = Snapshot(items: items, stores: stores, comparison: comparison, comparedAt: comparedAt, comparedSignature: comparedSignature)85 if let d = try? JSONEncoder().encode(s) { try? d.write(to: file, options: .atomic) }86 }8788 // --- Lecture -------------------------------------------------------------------------------------8990 var isEmpty: Bool { items.isEmpty }91 var count: Int { items.count }92 var remaining: Int { items.filter { !$0.checked }.count }93 var isFull: Bool { items.count >= GroceryList.maxItems }9495 func contains(_ productID: String) -> Bool { items.contains { $0.product?.id == productID } }96 func item(for productID: String) -> GroceryItem? { items.first { $0.product?.id == productID } }9798 /// Signature de la liste (articles et quantités, sans les cases cochées) : dit si la comparaison est à jour.99 var signature: String {100 items.map { ($0.product?.id ?? "q:" + ($0.query ?? "")) + "×" + Fmt.quantity($0.quantity) }.joined(separator: "|")101 + "#" + stores.sorted().joined(separator: ",")102 }103104 /// La comparaison affichée décrit-elle la liste actuelle ?105 var comparisonIsCurrent: Bool { comparison != nil && comparedSignature == signature }106107 /// Articles groupés par rayon (mode « à l'épicerie »), rayons en ordre alphabétique, cochés à la fin.108 var byCategory: [(category: String, items: [GroceryItem])] {109 Dictionary(grouping: items, by: \.category)110 .map { (category: $0.key, items: $0.value.sorted { ($0.checked ? 1 : 0, $0.title) < ($1.checked ? 1 : 0, $1.title) }) }111 .sorted { $0.category.localizedCompare($1.category) == .orderedAscending }112 }113114 /// Estimation locale du coût aux prix des cartes gardées (une seule enseigne par article : ce n'est pas un total).115 var knownSum: Double { items.reduce(0) { $0 + ($1.product?.price ?? 0) * $1.quantity } }116117 // --- Écriture ------------------------------------------------------------------------------------118119 /// Ajoute un produit, ou augmente sa quantité s'il y est déjà. Rend faux si la liste est pleine.120 @discardableResult121 func add(_ product: Product, quantity: Double = 1) -> Bool {122 if let i = items.firstIndex(where: { $0.product?.id == product.id }) {123 items[i].quantity = min(GroceryList.maxQuantity, items[i].quantity + quantity)124 items[i].product = product125 } else {126 guard !isFull else { return false }127 items.append(GroceryItem(product: product, quantity: quantity))128 }129 persist()130 return true131 }132133 @discardableResult134 func add(query: String) -> Bool {135 let q = query.trimmingCharacters(in: .whitespacesAndNewlines)136 guard !q.isEmpty, !isFull else { return false }137 if let i = items.firstIndex(where: { $0.query?.caseInsensitiveCompare(q) == .orderedSame }) {138 items[i].quantity = min(GroceryList.maxQuantity, items[i].quantity + 1)139 } else {140 items.append(GroceryItem(query: String(q.prefix(120))))141 }142 persist()143 return true144 }145146 func remove(_ id: UUID) {147 items.removeAll { $0.id == id }148 persist()149 }150151 func remove(productID: String) {152 items.removeAll { $0.product?.id == productID }153 persist()154 }155156 func setQuantity(_ id: UUID, _ q: Double) {157 guard let i = items.firstIndex(where: { $0.id == id }) else { return }158 if q < 1 { items.remove(at: i) } else { items[i].quantity = min(GroceryList.maxQuantity, q) }159 persist()160 }161162 func toggleChecked(_ id: UUID) {163 guard let i = items.firstIndex(where: { $0.id == id }) else { return }164 items[i].checked.toggle()165 persist()166 }167168 /// Remplace une ligne (recherche libre ou substitution) par un produit précis.169 func replace(_ id: UUID, with product: Product) {170 guard let i = items.firstIndex(where: { $0.id == id }) else { return }171 items[i].product = product172 items[i].query = nil173 persist()174 }175176 func uncheckAll() {177 for i in items.indices { items[i].checked = false }178 persist()179 }180181 func removeChecked() {182 items.removeAll { $0.checked }183 persist()184 }185186 func clear() {187 items = []188 comparison = nil; comparedAt = nil; comparedSignature = nil189 persist()190 }191192 /// Relit, en un lot, le prix des produits de la liste (à l'ouverture). Sans réseau, la liste garde ses prix.193 func refreshPrices() async {194 let ids = items.compactMap { $0.product?.id }195 guard !ids.isEmpty, let batch = try? await APIClient.shared.products(ids: ids) else { return }196 apply(batch.products.filter(\.live).map(\.product))197 }198199 /// Applique des cartes fraîches aux lignes correspondantes (pur, testé seul).200 func apply(_ fresh: [Product]) {201 let byID = Dictionary(fresh.map { ($0.id, $0) }, uniquingKeysWith: { a, _ in a })202 var changed = false203 for i in items.indices {204 guard let old = items[i].product, let f = byID[old.id] else { continue }205 let new = old.refreshed(with: f)206 if new != old { items[i].product = new; changed = true }207 }208 if changed { persist() }209 }210211 // --- Comparaison ---------------------------------------------------------------------------------212213 var request: BasketRequest {214 BasketRequest(items: items.map { .init(id: $0.product?.id, q: $0.product == nil ? $0.query : nil, quantity: $0.quantity) },215 stores: stores.isEmpty ? nil : stores.sorted())216 }217218 /// Demande le coût par enseigne. Hors ligne, la dernière comparaison reste affichée, datée.219 func compare() async {220 guard !items.isEmpty, !comparing else { return }221 comparing = true222 compareError = nil223 let sig = signature224 do {225 let (c, _) = try await APIClient.shared.compareBasket(request)226 comparison = c227 comparedAt = Date()228 comparedSignature = sig229 persist()230 } catch is CancellationError {231 } catch {232 compareError = (error as? APIError)?.errorDescription ?? "La comparaison a échoué."233 }234 comparing = false235 }236237 /// Pose une comparaison (tests).238 func setComparison(_ c: BasketComparison?) {239 comparison = c240 comparedAt = c == nil ? nil : Date()241 comparedSignature = c == nil ? nil : signature242 }243244 // --- Partage -------------------------------------------------------------------------------------245246 /// La liste en texte brut, par rayon.247 var shareText: String {248 var out = ["Liste d'épicerie"]249 for group in byCategory {250 out.append("")251 out.append(group.category)252 for i in group.items.sorted(by: { $0.title < $1.title }) {253 var l = (i.checked ? "[x] " : "[ ] ") + i.title254 if let s = i.product?.brandAndSize { l += " (\(s))" }255 if i.quantity != 1 { l += " × " + Fmt.quantity(i.quantity) }256 if let p = i.product?.price, let store = i.product?.storeName { l += " — \(Fmt.price(p)) chez \(store)" }257 out.append(l)258 }259 }260 if let c = comparison, comparisonIsCurrent, let s = c.statement {261 out.append("")262 out.append(s)263 }264 out.append("")265 out.append("Prix relevés par Food-Ka — www.food-ka.com")266 return out.joined(separator: "\n")267 }268}269