Repository Public
1//2// Fabri-Ka iOS v23// File: FabriKa/Core/Models/Product.swift4// Description: produit — la carte des listes (aussi gardée sur l'appareil pour les favoris) et la fiche complète.5// Décodage tolérant : une fiche écartée des listes peut n'avoir ni photo ni prix.6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9//1011import Foundation1213/// État de disponibilité au dernier relevé. Un état porte toujours un mot et une forme, jamais la couleur seule.14enum Availability: Sendable, Equatable {15 case inStock, soldOut, unknown16}1718/// Carte de produit (listes, favoris). Clés du contrat : `uid`, `title`, `price`, `store_id`…19struct Product: Codable, Hashable, Sendable, Identifiable {20 var uid: String21 var title: String22 var price: Double?23 var priceMax: Double?24 var compareAtPrice: Double?25 var discountPct: Double?26 var available: Bool?27 var img: String?28 var nImg: Int = 129 var category: String?30 var categoryLabel: String?31 var categorySlug: String?32 var subcategory: String?33 var subcategoryLabel: String?34 var storeId: String = ""35 var storeName: String = ""36 var city: String?37 var region: String?38 var origin: String?39 var firstSeen: Double?40 var daysListed: Int?41 var isNew = false42 var variantsGrouped: Int = 143 var url: String?44 var path: String?45 /// dans `similar` : le nom est identique à celui de la fiche (un fabricant et ses détaillants)46 var sameTitle = false4748 var id: String { uid }4950 enum CodingKeys: String, CodingKey {51 case uid, title, price, available, img, category, subcategory, city, region, origin, url, path52 case priceMax = "price_max", compareAtPrice = "compare_at_price", discountPct = "discount_pct", nImg = "n_img"53 case categoryLabel = "category_label", categorySlug = "category_slug", subcategoryLabel = "subcategory_label"54 case storeId = "store_id", storeName = "store_name", firstSeen = "first_seen", daysListed = "days_listed"55 case isNew = "is_new", variantsGrouped = "variants_grouped", sameTitle = "same_title"56 }5758 init(uid: String, title: String, price: Double? = nil, storeId: String = "", storeName: String = "") {59 self.uid = uid; self.title = title; self.price = price; self.storeId = storeId; self.storeName = storeName60 }6162 init(from decoder: Decoder) throws {63 let c = try decoder.container(keyedBy: CodingKeys.self)64 guard let uid = c.text(.uid) else {65 throw DecodingError.dataCorruptedError(forKey: .uid, in: c, debugDescription: "produit sans identifiant")66 }67 self.uid = uid68 title = c.text(.title) ?? "Produit sans nom"69 price = c.dbl(.price)70 priceMax = c.dbl(.priceMax)71 compareAtPrice = c.dbl(.compareAtPrice)72 discountPct = c.dbl(.discountPct)73 available = c.bool(.available)74 img = c.text(.img)75 nImg = c.int(.nImg) ?? (img == nil ? 0 : 1)76 category = c.text(.category)77 categoryLabel = c.text(.categoryLabel)78 categorySlug = c.text(.categorySlug)79 subcategory = c.text(.subcategory)80 subcategoryLabel = c.text(.subcategoryLabel)81 storeId = c.text(.storeId) ?? ""82 storeName = c.text(.storeName) ?? ""83 city = c.text(.city)84 region = c.text(.region)85 origin = c.text(.origin)86 firstSeen = c.dbl(.firstSeen)87 daysListed = c.int(.daysListed)88 isNew = c.bool(.isNew) ?? false89 variantsGrouped = c.int(.variantsGrouped) ?? 190 url = c.text(.url)91 path = c.text(.path)92 sameTitle = c.bool(.sameTitle) ?? false93 }9495 var availability: Availability {96 switch available {97 case true?: .inStock98 case false?: .soldOut99 case nil: .unknown100 }101 }102103 /// Lieu de la boutique : la ville, sinon la région ; nil plutôt qu'une ville devinée.104 var place: String? { city ?? region }105106 /// « 10,00 $ » ou « de 39,50 $ à 192 $ ».107 var priceText: String { Fmt.priceRange(price, priceMax) }108109 /// Rabais affichable (prix d'avant plausible rendu par le service).110 var discount: Int? {111 guard let d = discountPct, d >= 1, compareAtPrice != nil else { return nil }112 return Int(d.rounded())113 }114115 /// Icône de la grande catégorie (enseignes parlantes de la marque).116 var categoryIcon: String { CategoryIcon.name(for: category) }117118 /// Description lue par VoiceOver pour une carte.119 var spoken: String {120 var parts = [title, priceText]121 switch availability {122 case .soldOut: parts.append("épuisé")123 case .inStock where isNew: parts.append("nouveau")124 default: break125 }126 if !storeName.isEmpty { parts.append("chez \(storeName)") }127 if let place { parts.append(place) }128 return parts.joined(separator: ", ")129 }130}131132/// Correspondance des 21 catégories du service avec les onze enseignes parlantes de la marque.133enum CategoryIcon {134 static func name(for key: String?) -> String {135 switch key {136 case "epicerie", "cafe_the", "alcool", "boissons", "erable", "viande_poisson", "chocolat", "fromage_laitier", "boulangerie":137 "ic-alimentation"138 case "maison": "ic-maison"139 case "mode": "ic-vetements"140 case "bijoux": "ic-bijoux"141 case "sante_beaute": "ic-beaute"142 case "enfants": "ic-enfants"143 case "art", "livres": "ic-art"144 case "plein_air": "ic-plein-air"145 case "animaux": "ic-animaux"146 case "jardin": "ic-jardin"147 case "industriel": "ic-outils"148 default: "ic-boutique"149 }150 }151}152153/// Fiche complète d'un produit (`GET /api/products/{uid}`).154struct ProductDetail: Decodable, Sendable {155 struct Variant: Decodable, Hashable, Sendable {156 var name: String157 var price: Double?158 var available: Bool?159 var sku: String?160161 enum CodingKeys: String, CodingKey { case name, price, available, sku }162 init(from decoder: Decoder) throws {163 let c = try decoder.container(keyedBy: CodingKeys.self)164 name = c.text(.name) ?? "Variante"165 price = c.dbl(.price)166 available = c.bool(.available)167 sku = c.text(.sku)168 }169 }170171 struct Option: Decodable, Hashable, Sendable {172 var name: String173 var values: [String]174175 enum CodingKeys: String, CodingKey { case name, values }176 init(from decoder: Decoder) throws {177 let c = try decoder.container(keyedBy: CodingKeys.self)178 name = c.text(.name) ?? "Option"179 values = c.strings(.values)180 }181 }182183 struct Fact: Decodable, Hashable, Sendable {184 var label: String185 var value: String186187 enum CodingKeys: String, CodingKey { case label, value }188 init(from decoder: Decoder) throws {189 let c = try decoder.container(keyedBy: CodingKeys.self)190 guard let l = c.text(.label), let v = c.text(.value) else {191 throw DecodingError.dataCorruptedError(forKey: .label, in: c, debugDescription: "fait incomplet")192 }193 label = l; value = v194 }195 }196197 /// Produit de même nom regroupé sous celui-ci.198 struct Grouped: Decodable, Hashable, Sendable {199 var uid: String200 var url: String?201 var price: Double?202 var available: Bool?203204 enum CodingKeys: String, CodingKey { case uid, url, price, available }205 init(from decoder: Decoder) throws {206 let c = try decoder.container(keyedBy: CodingKeys.self)207 uid = c.text(.uid) ?? ""208 url = c.text(.url)209 price = c.dbl(.price)210 available = c.bool(.available)211 }212 }213214 var card: Product215 var images: [String]216 var description: String?217 var paragraphs: [String]218 var vendor: String?219 var productType: String?220 var tags: [String]221 var variants: [Variant]222 var options: [Option]223 var facts: [Fact]224 var grouped: [Grouped]225 var sameStore: [Product]226 var similar: [Product]227 var store: Store?228 var lastSeen: Double?229 /// `false` : fiche atteignable mais écartée des listes (sans photo, sans prix…) ; à afficher sobrement.230 var isPublic: Bool231 var reason: String?232 var reasonLabel: String?233234 enum CodingKeys: String, CodingKey {235 case images, description, vendor, tags, variants, options, facts, grouped, similar, store, reason236 case paragraphs = "description_paragraphs", productType = "product_type", sameStore = "same_store"237 case lastSeen = "last_seen", isPublic = "public", reasonLabel = "reason_label"238 }239240 init(from decoder: Decoder) throws {241 card = try Product(from: decoder)242 let c = try decoder.container(keyedBy: CodingKeys.self)243 var imgs = c.strings(.images)244 if imgs.isEmpty, let i = card.img { imgs = [i] }245 images = imgs246 description = c.text(.description)247 var paras = c.strings(.paragraphs).map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }.filter { !$0.isEmpty }248 if paras.isEmpty, let d = description { paras = [d] }249 paragraphs = paras250 vendor = c.text(.vendor)251 productType = c.text(.productType)252 tags = c.strings(.tags)253 variants = c.list(.variants)254 options = c.list(.options, Option.self).filter { !$0.values.isEmpty }255 facts = c.list(.facts)256 grouped = c.list(.grouped)257 sameStore = c.list(.sameStore)258 similar = c.list(.similar)259 store = c.opt(.store)260 lastSeen = c.dbl(.lastSeen)261 isPublic = c.bool(.isPublic) ?? true262 reason = c.text(.reason)263 reasonLabel = c.text(.reasonLabel)264 }265266 /// Variantes utiles à montrer : plus d'une, ou une seule qui porte un vrai nom.267 var shownVariants: [Variant] {268 if variants.count > 1 { return variants }269 return variants.filter { !["default title", "default", "défaut"].contains($0.name.lowercased()) }270 }271272 /// Options utiles (Shopify publie « Title : Default Title » pour un produit sans option).273 var shownOptions: [Option] {274 options.filter { !($0.values.count == 1 && $0.values[0].lowercased() == "default title") }275 }276}277