Repository Public
1//2// Food-Ka iOS v23// File: FoodKa/Core/Models/Basket.swift4// Description: comparaison d'un panier (`POST /api/panier/comparer`). Règle du service, respectée partout :5// `total` est nul dès qu'un article manque ; `partial_total` ne se classe jamais avec les totaux.6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9//1011import Foundation1213/// Requête : la liste quitte l'appareil le temps du calcul, rien n'est conservé par le serveur.14struct BasketRequest: Encodable, Sendable {15 struct Item: Encodable, Sendable {16 var id: String?17 var q: String?18 var quantity: Double19 }2021 var items: [Item]22 var stores: [String]?23 var substitutions = true24}2526struct BasketComparison: Codable, Sendable {27 struct Item: Codable, Sendable, Hashable {28 var line: Int29 var id: String?30 var q: String?31 var quantity: Double32 var resolved: Bool33 var label: String34 var error: String?3536 init(from decoder: Decoder) throws {37 let c = try decoder.container(keyedBy: AnyKey.self)38 line = c.int(AnyKey("line")) ?? 039 id = c.text(AnyKey("id"))40 q = c.text(AnyKey("q"))41 quantity = c.dbl(AnyKey("quantity")) ?? 142 resolved = c.bool(AnyKey("resolved")) ?? false43 label = c.text(AnyKey("label")) ?? q ?? id ?? "Article"44 error = c.text(AnyKey("error"))45 }46 }4748 struct Missing: Codable, Sendable, Hashable {49 var line: Int50 var label: String51 }5253 /// L'offre retenue pour une ligne dans une enseigne.54 struct Line: Codable, Sendable, Hashable, Identifiable {55 var line: Int56 var match: String57 var similarity: Double?58 var substitution: Bool59 var quantity: Double60 var lineTotal: Double?61 var byWeight: Bool62 var product: Product?63 var id: Int { line }6465 init(from decoder: Decoder) throws {66 let c = try decoder.container(keyedBy: AnyKey.self)67 line = c.int(AnyKey("line")) ?? 068 match = c.text(AnyKey("match")) ?? "exact"69 similarity = c.dbl(AnyKey("similarity"))70 substitution = c.bool(AnyKey("substitution")) ?? false71 quantity = c.dbl(AnyKey("quantity")) ?? 172 lineTotal = c.dbl(AnyKey("line_total"))73 byWeight = c.bool(AnyKey("by_weight")) ?? false74 product = c.opt(AnyKey("product"))75 }7677 func encode(to encoder: Encoder) throws {78 var c = encoder.container(keyedBy: AnyKey.self)79 try c.encode(line, forKey: AnyKey("line"))80 try c.encode(match, forKey: AnyKey("match"))81 try c.encodeIfPresent(similarity, forKey: AnyKey("similarity"))82 try c.encode(substitution, forKey: AnyKey("substitution"))83 try c.encode(quantity, forKey: AnyKey("quantity"))84 try c.encodeIfPresent(lineTotal, forKey: AnyKey("line_total"))85 try c.encode(byWeight, forKey: AnyKey("by_weight"))86 try c.encodeIfPresent(product, forKey: AnyKey("product"))87 }8889 /// Ce n'est pas le produit demandé : à signaler (substitution ou meilleure réponse à une recherche).90 var indicative: Bool { match == "equivalent" || match == "recherche" }9192 var matchLabel: String? {93 switch match {94 case "equivalent": "Produit équivalent, pas le même"95 case "recherche": "Choisi par la recherche"96 case "meme_produit": "Même produit, apparié par le nom"97 default: nil98 }99 }100 }101102 struct StoreResult: Codable, Sendable, Hashable, Identifiable {103 var store: String104 var storeName: String105 var type: String?106 var found: Int107 var missing: [Missing]108 var complete: Bool109 var substitutions: Int110 /// Nul dès qu'un article manque.111 var total: Double?112 /// Ne porte que sur les articles trouvés : jamais classé avec les totaux.113 var partialTotal: Double?114 var lines: [Line]115 var id: String { store }116117 init(from decoder: Decoder) throws {118 let c = try decoder.container(keyedBy: AnyKey.self)119 store = c.text(AnyKey("store")) ?? ""120 storeName = c.text(AnyKey("store_name")) ?? store121 type = c.text(AnyKey("type"))122 found = c.int(AnyKey("found")) ?? 0123 missing = c.list(AnyKey("missing"), Missing.self)124 complete = c.bool(AnyKey("complete")) ?? false125 substitutions = c.int(AnyKey("substitutions")) ?? 0126 let t = c.dbl(AnyKey("total"))127 // garde-fou : jamais de total si la liste n'est pas couverte en entier128 total = complete ? t : nil129 partialTotal = c.dbl(AnyKey("partial_total"))130 lines = c.list(AnyKey("lines"), Line.self)131 }132133 func encode(to encoder: Encoder) throws {134 var c = encoder.container(keyedBy: AnyKey.self)135 try c.encode(store, forKey: AnyKey("store"))136 try c.encode(storeName, forKey: AnyKey("store_name"))137 try c.encodeIfPresent(type, forKey: AnyKey("type"))138 try c.encode(found, forKey: AnyKey("found"))139 try c.encode(missing, forKey: AnyKey("missing"))140 try c.encode(complete, forKey: AnyKey("complete"))141 try c.encode(substitutions, forKey: AnyKey("substitutions"))142 try c.encodeIfPresent(total, forKey: AnyKey("total"))143 try c.encodeIfPresent(partialTotal, forKey: AnyKey("partial_total"))144 try c.encode(lines, forKey: AnyKey("lines"))145 }146147 func line(_ index: Int) -> Line? { lines.first { $0.line == index } }148 }149150 struct BestSingle: Codable, Sendable, Hashable {151 var store: String152 var store_name: String153 var total: Double?154 var substitutions: Int?155 }156157 struct BestCoverage: Codable, Sendable, Hashable {158 var store: String159 var store_name: String160 var found: Int161 var of: Int162 }163164 struct Pair: Codable, Sendable, Hashable {165 struct Part: Codable, Sendable, Hashable, Identifiable {166 var store: String167 var store_name: String168 var lines: [Int]169 var subtotal: Double?170 var id: String { store }171 }172173 var stores: [String]174 var store_names: [String]?175 var covered: Int?176 var total: Double?177 var split: [Part]?178 var complete: Bool?179 var savings_vs_best_single: Double?180 }181182 var items: [Item]183 var linesRequested: Int184 var linesResolved: Int185 var storesCompared: Int186 var bestSingle: BestSingle?187 var bestPair: Pair?188 var bestCoverage: BestCoverage?189 var stores: [StoreResult]190 var notes: [String]191 /// enseignes sorties de la comparaison (prix relevés hors Québec), avec la raison du service192 var excludedStores: [Excluded] = []193194 struct Excluded: Codable, Sendable, Hashable {195 var store: String196 var store_name: String197 var reason: String?198 }199200 init(from decoder: Decoder) throws {201 let c = try decoder.container(keyedBy: AnyKey.self)202 items = c.list(AnyKey("items"), Item.self)203 linesRequested = c.int(AnyKey("lines_requested")) ?? items.count204 linesResolved = c.int(AnyKey("lines_resolved")) ?? 0205 storesCompared = c.int(AnyKey("stores_compared")) ?? 0206 bestSingle = c.opt(AnyKey("best_single"))207 bestPair = c.opt(AnyKey("best_pair"))208 bestCoverage = c.opt(AnyKey("best_coverage"))209 stores = c.list(AnyKey("stores"), StoreResult.self)210 notes = c.strings(AnyKey("notes"))211 excludedStores = c.list(AnyKey("excluded_stores"), Excluded.self)212 }213214 func encode(to encoder: Encoder) throws {215 var c = encoder.container(keyedBy: AnyKey.self)216 try c.encode(items, forKey: AnyKey("items"))217 try c.encode(linesRequested, forKey: AnyKey("lines_requested"))218 try c.encode(linesResolved, forKey: AnyKey("lines_resolved"))219 try c.encode(storesCompared, forKey: AnyKey("stores_compared"))220 try c.encodeIfPresent(bestSingle, forKey: AnyKey("best_single"))221 try c.encodeIfPresent(bestPair, forKey: AnyKey("best_pair"))222 try c.encodeIfPresent(bestCoverage, forKey: AnyKey("best_coverage"))223 try c.encode(stores, forKey: AnyKey("stores"))224 try c.encode(notes, forKey: AnyKey("notes"))225 try c.encode(excludedStores, forKey: AnyKey("excluded_stores"))226 }227228 /// Enseignes qui couvrent toute la liste, de la moins chère à la plus chère : les seules qui portent un total.229 var complete: [StoreResult] {230 stores.filter { $0.complete && $0.total != nil }.sorted { ($0.total ?? 0) < ($1.total ?? 0) }231 }232233 /// Enseignes incomplètes, les mieux pourvues d'abord (jamais classées par prix).234 var incomplete: [StoreResult] {235 stores.filter { !$0.complete && $0.found > 0 }.sorted { ($0.found, $1.storeName) > ($1.found, $0.storeName) }236 }237238 var unresolved: [Item] { items.filter { !$0.resolved } }239240 /// Phrase de constat, à partir des seuls totaux complets.241 var statement: String? {242 let c = complete243 if c.count >= 2, let a = c.first?.total, let b = c[1].total {244 let d = b - a245 if d < 0.005 { return "\(c[0].storeName) et \(c[1].storeName) : même total." }246 return "\(c[0].storeName) : \(Fmt.price(d)) de moins que \(c[1].storeName)."247 }248 if c.count == 1 { return "\(c[0].storeName) est la seule enseigne à offrir toute la liste." }249 if let cov = bestCoverage, linesResolved > 0 {250 return "Aucune enseigne n'offre toute la liste. \(cov.store_name) en trouve \(cov.found) sur \(cov.of)."251 }252 return nil253 }254}255