Repository Public
1//2// Food-Ka iOS v23// File: FoodKa/Core/Models/Catalog.swift4// Description: recherche, facettes, rayons, autocomplétion, baisses vérifiées, et les filtres de recherche5// (paramètres de `GET /api/search`).6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9//1011import Foundation1213struct SearchResponse: Decodable, Sendable {14 var total: Int15 var page: Int16 var pages: Int17 var approximate: Bool18 var unitPriceUnit: String?19 var products: [Product]20 var facets: Facets?21 /// recherche par code-barres : part des produits qui portent un code, et note du service22 var coverageSharePct: Double?23 var coverageNote: String?2425 init(from decoder: Decoder) throws {26 let c = try decoder.container(keyedBy: AnyKey.self)27 total = c.int(AnyKey("total")) ?? 028 page = c.int(AnyKey("page")) ?? 129 pages = c.int(AnyKey("pages")) ?? 130 approximate = c.bool(AnyKey("approximate")) ?? false31 unitPriceUnit = c.text(AnyKey("unit_price_unit"))32 products = c.list(AnyKey("products"), Product.self)33 facets = c.opt(AnyKey("facets"))34 if let cov = try? c.nestedContainer(keyedBy: AnyKey.self, forKey: AnyKey("coverage")) {35 coverageSharePct = cov.dbl(AnyKey("share_pct"))36 coverageNote = cov.text(AnyKey("note"))37 }38 }39}4041struct Facets: Decodable, Sendable {42 struct Store: Decodable, Hashable, Sendable, Identifiable {43 var id: String44 var name: String45 var type: String?46 var n: Int47 }4849 struct Brand: Decodable, Hashable, Sendable, Identifiable {50 var key: String51 var name: String52 var n: Int53 var store_brand: Bool?54 var id: String { key }55 }5657 struct Bucket: Decodable, Hashable, Sendable {58 var min: Double?59 var max: Double?60 var n: Int61 }6263 var total: Int64 var stores: [Store]65 var categories: [Category]66 var brands: [Brand]67 var brandsTotal: Int?68 var tags: [String: Int]69 var onSale: Int?70 var deals: Int?71 /// produits suivis dans au moins deux enseignes72 var matched: Int?73 var inStockYes: Int?74 var tagLabels: [String: String]75 var storeTypes: [String: String]76 var buckets: [Bucket]7778 init(from decoder: Decoder) throws {79 let c = try decoder.container(keyedBy: AnyKey.self)80 total = c.int(AnyKey("total")) ?? 081 stores = c.list(AnyKey("stores"), Store.self)82 categories = c.list(AnyKey("categories"), Category.self)83 brands = c.list(AnyKey("brands"), Brand.self)84 brandsTotal = c.int(AnyKey("brands_total"))85 tags = c.opt(AnyKey("tags")) ?? [:]86 onSale = c.int(AnyKey("on_sale"))87 deals = c.int(AnyKey("deals"))88 matched = c.int(AnyKey("matched"))89 if let s = try? c.nestedContainer(keyedBy: AnyKey.self, forKey: AnyKey("in_stock")) { inStockYes = s.int(AnyKey("yes")) }90 tagLabels = c.opt(AnyKey("tag_labels")) ?? [:]91 storeTypes = c.opt(AnyKey("store_types")) ?? [:]92 if let p = try? c.nestedContainer(keyedBy: AnyKey.self, forKey: AnyKey("price")) {93 buckets = p.list(AnyKey("buckets"), Bucket.self)94 } else {95 buckets = []96 }97 }98}99100/// Rayon (et ses sous-rayons).101struct Category: Decodable, Hashable, Sendable, Identifiable {102 var name: String103 var slug: String104 var n: Int105 var subcategories: [Category]106 var id: String { slug }107108 init(name: String, slug: String, n: Int, subcategories: [Category] = []) {109 self.name = name; self.slug = slug; self.n = n; self.subcategories = subcategories110 }111112 init(from decoder: Decoder) throws {113 let c = try decoder.container(keyedBy: AnyKey.self)114 guard let name = c.text(AnyKey("name")), let slug = c.text(AnyKey("slug")) else {115 throw DecodingError.dataCorrupted(.init(codingPath: decoder.codingPath, debugDescription: "rayon incomplet"))116 }117 self.name = name; self.slug = slug118 n = c.int(AnyKey("n")) ?? 0119 subcategories = c.list(AnyKey("subcategories"), Category.self)120 }121122 /// Icône de la marque pour ce rayon (les objets reposent tous sur la même tablette).123 var icon: String { Category.icon(slug: slug) }124125 static func icon(slug: String?) -> String {126 switch slug {127 case "fruits-et-legumes": "ic-fruits-legumes"128 case "viandes-et-volailles", "charcuteries-et-fromages": "ic-viandes"129 case "poissons-et-fruits-de-mer": "ic-poissons"130 case "produits-laitiers-et-oeufs": "ic-laitiers"131 case "boulangerie": "ic-boulangerie"132 case "surgeles": "ic-surgeles"133 case "garde-manger", "pret-a-manger": "ic-garde-manger"134 case "collations-et-confiseries": "ic-format"135 case "boissons": "ic-boissons"136 case "bio-et-sante": "ic-bio"137 case "bebe": "ic-bebe"138 case "animaux": "ic-animaux"139 case "maison-et-entretien", "sante-et-beaute": "ic-hygiene"140 case "alcool": "ic-vins-bieres"141 default: "ic-tablette"142 }143 }144145 /// Icône d'après le nom du rayon (les cartes de produit portent le nom, pas le slug).146 static func icon(name: String?) -> String {147 guard let name else { return "ic-tablette" }148 let slug = name.folding(options: [.diacriticInsensitive, .caseInsensitive], locale: Locale(identifier: "fr_CA"))149 .lowercased().replacingOccurrences(of: "œ", with: "oe").replacingOccurrences(of: " ", with: "-")150 return icon(slug: slug)151 }152}153154struct CategoriesResponse: Decodable, Sendable {155 var total: Int156 var categories: [Category]157158 init(from decoder: Decoder) throws {159 let c = try decoder.container(keyedBy: AnyKey.self)160 total = c.int(AnyKey("total")) ?? 0161 categories = c.list(AnyKey("categories"), Category.self)162 }163}164165/// Autocomplétion : produits, marques, rayons, enseignes.166struct Suggestions: Decodable, Sendable {167 struct Brand: Decodable, Hashable, Sendable, Identifiable {168 var key: String169 var name: String170 var n: Int171 var id: String { key }172 }173174 struct Cat: Decodable, Hashable, Sendable, Identifiable {175 var name: String176 var slug: String177 var n: Int178 var parent: String?179 var id: String { (parent ?? "") + "/" + slug }180 }181182 struct Store: Decodable, Hashable, Sendable, Identifiable {183 var id: String184 var name: String185 var n: Int186 }187188 var q: String189 var products: [Product]190 var brands: [Brand]191 var categories: [Cat]192 var stores: [Store]193194 init(from decoder: Decoder) throws {195 let c = try decoder.container(keyedBy: AnyKey.self)196 q = c.text(AnyKey("q")) ?? ""197 products = c.list(AnyKey("products"), Product.self)198 brands = c.list(AnyKey("brands"), Brand.self)199 categories = c.list(AnyKey("categories"), Cat.self)200 stores = c.list(AnyKey("stores"), Store.self)201 }202203 var isEmpty: Bool { products.isEmpty && brands.isEmpty && categories.isEmpty && stores.isEmpty }204}205206/// Lot léger : `GET /api/products?ids=a,b,c` (produits suivis, liste d'épicerie).207struct ProductBatch: Decodable, Sendable {208 struct Entry: Decodable, Sendable {209 var product: Product210 var live: Bool211212 init(from decoder: Decoder) throws {213 product = try Product(from: decoder)214 let c = try decoder.container(keyedBy: AnyKey.self)215 live = (c.bool(AnyKey("public")) ?? true) && (c.bool(AnyKey("active")) ?? true)216 }217 }218219 var products: [Entry]220 var missing: [String]221222 init(from decoder: Decoder) throws {223 let c = try decoder.container(keyedBy: AnyKey.self)224 products = c.list(AnyKey("products"), Entry.self)225 missing = c.strings(AnyKey("missing"))226 }227}228229struct DealsResponse: Decodable, Sendable {230 var total: Int231 var page: Int232 var pages: Int233 var byStatus: [String: Int]234 var products: [Product]235236 init(from decoder: Decoder) throws {237 let c = try decoder.container(keyedBy: AnyKey.self)238 total = c.int(AnyKey("total")) ?? 0239 page = c.int(AnyKey("page")) ?? 1240 pages = c.int(AnyKey("pages")) ?? 1241 byStatus = c.opt(AnyKey("by_status")) ?? [:]242 products = c.list(AnyKey("products"), Product.self)243 }244}245246// --- Filtres ------------------------------------------------------------------------------------247248enum SortOrder: String, CaseIterable, Identifiable, Sendable, Hashable {249 case relevance, priceAsc = "price_asc", priceDesc = "price_desc", unitPrice = "unit_price", drop, recent, name250 var id: String { rawValue }251 var label: String {252 switch self {253 case .relevance: "Pertinence"254 case .priceAsc: "Prix croissant"255 case .priceDesc: "Prix décroissant"256 case .unitPrice: "Prix unitaire"257 case .drop: "Plus forte baisse"258 case .recent: "Nouveautés"259 case .name: "Nom, de A à Z"260 }261 }262}263264/// Filtres d'une recherche : exactement les paramètres de `GET /api/search`.265struct SearchFilters: Hashable, Sendable {266 var q: String = ""267 var category: String?268 var categoryName: String?269 var subcategory: String?270 var subcategoryName: String?271 var stores: [String] = []272 var brand: String?273 var tags: Set<String> = []274 var onSale = false275 var dealOnly = false276 /// produits suivis dans plusieurs enseignes (`apparie=1`)277 var matchedOnly = false278 /// écarte les ruptures connues (`in_stock=1`)279 var inStockOnly = false280 var kind: String?281 var priceMin: Double?282 var priceMax: Double?283 var sort: SortOrder = .relevance284285 /// Titre de l'écran de résultats.286 var title: String {287 if !q.isEmpty { return "« \(q) »" }288 if let s = subcategoryName { return s }289 if let c = categoryName { return c }290 if let b = brand { return b }291 if dealOnly { return "Baisses vérifiées" }292 if onSale { return "En solde" }293 return "Tous les produits"294 }295296 /// Nombre de filtres actifs dans la feuille (hors recherche, rayon de départ et tri).297 var activeCount: Int {298 var n = stores.count + tags.count299 if brand != nil { n += 1 }300 if onSale { n += 1 }301 if dealOnly { n += 1 }302 if matchedOnly { n += 1 }303 if inStockOnly { n += 1 }304 if kind != nil { n += 1 }305 if priceMin != nil || priceMax != nil { n += 1 }306 return n307 }308309 /// Retire tous les filtres de la feuille (la recherche, le rayon de départ et le tri restent).310 mutating func clearSheet() {311 stores = []; brand = nil; tags = []; onSale = false; dealOnly = false; matchedOnly = false312 inStockOnly = false; kind = nil; priceMin = nil; priceMax = nil313 }314315 func query(page: Int, pageSize: Int = 30, facets: Bool = false) -> [String: String?] {316 var o: [String: String?] = [317 "q": q.trimmingCharacters(in: .whitespaces),318 "category": category,319 "subcategory": subcategory,320 "store": stores.isEmpty ? nil : stores.sorted().joined(separator: ","),321 "brand": brand,322 "tags": tags.isEmpty ? nil : tags.sorted().joined(separator: ","),323 "kind": kind,324 "on_sale": onSale ? "1" : nil,325 "deal": dealOnly ? "1" : nil,326 "apparie": matchedOnly ? "1" : nil,327 "in_stock": inStockOnly ? "1" : nil,328 "price_min": priceMin.map { String(format: "%g", $0) },329 "price_max": priceMax.map { String(format: "%g", $0) },330 "sort": sort == .relevance ? nil : sort.rawValue,331 "page": String(page),332 "page_size": String(pageSize),333 ]334 if facets { o["facets"] = "1" }335 return o336 }337}338