Repository Public
1//2// Food-Ka iOS v23// File: FoodKa/Features/Product/ProductSections.swift4// Description: sections de la fiche — comparaison entre enseignes (le rail des prix, confiance de l'appariement5// dite, fiche digne quand il n'y a qu'une enseigne), équivalents étiquetés, historique et verdict,6// nutrition (rare), description et détails.7//8// Author: Simon-Pierre Boucher9// Contact: contact@spboucher.ai10//1112import SwiftUI1314// --- Comparaison entre enseignes ------------------------------------------------------------------------1516struct ComparisonSection: View {17 let detail: ProductDetail18 let level: ShelfLevel19 let opened: Date20 @Environment(AppModel.self) private var model2122 private var offers: [Product] { detail.allOffers }2324 var body: some View {25 VStack(alignment: .leading, spacing: 12) {26 if detail.offers.isEmpty {27 single28 } else {29 compared30 }31 if !detail.equivalents.isEmpty { equivalents.padding(.top, 14) }32 }33 }3435 private var rows: [RailRow] {36 offers.map { o in37 var parts: [String] = []38 if let u = o.unitPrice { parts.append(u.label) }39 if o.isFlyer { parts.append("circulaire") }40 if let r = o.regularPrice, let p = o.price, r > p + 0.004 { parts.append("rég. " + Fmt.price(r)) }41 let current = o.id == detail.card.id42 var caption: String?43 if current {44 caption = "cette fiche"45 } else if o.match == "identique" {46 caption = "même code"47 } else if o.match == "meme_produit" {48 // la confiance n'est chiffrée que si elle n'est pas totale49 caption = o.confidence.flatMap { $0 < 0.995 ? "nom à " + Fmt.pct($0 * 100, signed: false) : nil } ?? "même nom"50 }51 return RailRow(id: o.id, name: o.storeName, detail: parts.isEmpty ? nil : parts.joined(separator: " · "),52 value: o.price ?? 0, caption: caption, isCurrent: current)53 }54 }5556 /// Durée de la glissade et instant de départ, selon le geste joué à l'ouverture.57 private var timing: (duration: Double, notBefore: Date?) {58 switch level {59 case .signature: (1.6, opened.addingTimeInterval(ShelfChoreo.signature.rails.a / 1000))60 case .short: (1.0, opened.addingTimeInterval(ShelfChoreo.short.rails.a / 1000))61 case .compact: (0.6, nil)62 case .none: (1.6, nil)63 }64 }6566 private var compared: some View {67 let list = offers68 let n = list.count69 return VStack(alignment: .leading, spacing: 12) {70 SectionHeader("Comparaison entre enseignes", eyebrow: "Le rail des prix",71 note: "Le même produit dans \(n) enseignes. La position de chaque étiquette sur son rail est son prix.")72 AnimatedPriceRail(rows: rows, duration: timing.duration, notBefore: timing.notBefore) { row in73 guard row.id != detail.card.id, let p = list.first(where: { $0.id == row.id }) else { return }74 model.openProduct(p, trigger: .secondary)75 }76 if n >= 2, let a = list[0].price, let b = list[1].price {77 Text(b - a < 0.00578 ? "\(list[0].storeName) et \(list[1].storeName) : même prix."79 : "\(list[0].storeName) : \(Fmt.price(b - a)) de moins que \(list[1].storeName).")80 .font(.editorial(19)).foregroundStyle(Theme.ink)81 .fixedSize(horizontal: false, vertical: true)82 .accessibilityIdentifier("rail-statement")83 }84 confidence85 if list.contains(where: \.isFlyer) {86 HonestNote(text: "Un prix de circulaire vaut pour la durée de la circulaire, dans la zone de Montréal.")87 }88 }89 }9091 /// La confiance de l'appariement, dite avec les règles publiées par le service.92 @ViewBuilder private var confidence: some View {93 let s = detail.offersSummary94 let byCode = s?.identical ?? 0, byName = s?.sameProduct ?? 095 if byCode + byName > 0 {96 VStack(alignment: .leading, spacing: 4) {97 if byCode > 0 {98 HonestNote(text: "\(Fmt.plural(byCode, "enseigne appariée", "enseignes appariées")) par le code du produit : c'est certainement le même article.", icon: "checkmark.seal")99 }100 if byName > 0 {101 HonestNote(text: "\(Fmt.plural(byName, "enseigne appariée", "enseignes appariées")) par le nom (même marque, même format, noms semblables à 90 % au moins) : confiance élevée, sans certitude.")102 }103 }104 }105 }106107 /// Une seule enseigne : une fiche digne, qui dit pourquoi il n'y a rien à comparer.108 private var single: some View {109 VStack(alignment: .leading, spacing: 12) {110 SectionHeader("Comparaison entre enseignes", eyebrow: "Une seule enseigne")111 PriceRail(rows: rows, progress: 1)112 Text(detail.card.comparable113 ? "Ce produit n'est suivi que chez \(detail.card.storeName) : rien à comparer pour l'instant."114 : "Le prix de \(detail.card.storeName) est relevé hors Québec : il n'est comparé à aucune autre enseigne.")115 .font(.editorial(19)).foregroundStyle(Theme.ink).fixedSize(horizontal: false, vertical: true)116 .accessibilityIdentifier("single-store")117 if !detail.card.comparable, let r = ServiceInfo.current?.rules?.comparaison?.raison {118 HonestNote(text: Fmt.capitalized(r) + ".", icon: "exclamationmark.circle")119 }120 HonestNote(text: ServiceInfo.linkedShareText + " d'une enseigne à l'autre : le même article se vend peut-être ailleurs sous un autre nom ou un autre format."121 + (detail.equivalents.isEmpty ? "" : " Les produits équivalents ci-dessous ne sont pas le même produit."))122 }123 }124125 private var equivalents: some View {126 VStack(alignment: .leading, spacing: 6) {127 SectionHeader("Produits équivalents", eyebrow: "Pas le même produit",128 note: "Même sous-rayon, même unité, format voisin : marque et format peuvent différer. À comparer au prix unitaire.")129 ForEach(detail.equivalents) { p in130 ProductRow(product: p, trigger: .secondary,131 note: p.storeName + (p.similarity.map { " · ressemblance " + Fmt.pct($0 * 100, signed: false) } ?? ""))132 Hairline()133 }134 }135 .accessibilityIdentifier("equivalents")136 }137}138139// --- Historique et verdict ------------------------------------------------------------------------------140141struct HistorySection: View {142 let detail: ProductDetail143 @State private var showRule = false144145 var body: some View {146 VStack(alignment: .leading, spacing: 14) {147 SectionHeader("Historique du prix", note: subtitle)148 if let h = detail.history, !h.points.isEmpty {149 HistoryChart(history: h)150 facts(h)151 if !h.isSteps {152 HonestNote(text: "Chaque point est un passage en circulaire : ils ne sont pas reliés, le prix entre deux circulaires n'est pas connu.")153 }154 if h.unstable {155 HonestNote(text: "Ce prix alterne d'un relevé à l'autre (magasin différent, vente au poids ou changement de base). L'historique est montré, mais il ne sert ni au verdict ni aux baisses vérifiées.", icon: "exclamationmark.circle")156 }157 } else {158 Text("Aucun relevé de prix antérieur pour ce produit.").font(.subheadline).foregroundStyle(Theme.ink3)159 }160 verdict161 }162 }163164 private var subtitle: String? {165 guard let h = detail.history, let since = h.since else { return nil }166 let days = Int((h.days ?? 0).rounded())167 return "\(detail.card.name) chez \(detail.card.storeName) · \(days) \(days < 2 ? "jour" : "jours") de suivi, depuis le \(Fmt.date(since))."168 }169170 private func facts(_ h: PriceHistory) -> some View {171 let s = HistorySeries(h)172 return VStack(spacing: 0) {173 FactRow("Prix courant", Fmt.price(detail.card.price))174 if let l = h.low90d {175 FactRow(label: "Plus bas en 90 jours") {176 VStack(alignment: .trailing, spacing: 1) {177 Text(Fmt.price(l)).font(.subheadline.weight(.semibold)).monospacedDigit().foregroundStyle(Theme.good)178 if let span = s.lows.last, abs(span.price - l) < 0.005 {179 Text("du \(Fmt.shortDate(span.from)) au \(Fmt.shortDate(span.to))").font(.caption).foregroundStyle(Theme.ink3)180 } else if let at = h.low90dAt {181 Text("le \(Fmt.dayMonth(at))").font(.caption).foregroundStyle(Theme.ink3)182 }183 }184 }185 }186 if let m = h.median90d {187 FactRow(label: "Prix habituel") {188 VStack(alignment: .trailing, spacing: 1) {189 Text(Fmt.price(m)).font(.subheadline.weight(.semibold)).monospacedDigit().foregroundStyle(Theme.ink)190 Text("médiane sur 90 jours, pondérée par la durée").font(.caption).foregroundStyle(Theme.ink3)191 }192 }193 }194 if let hi = h.high90d {195 FactRow(label: "Plus haut en 90 jours") {196 VStack(alignment: .trailing, spacing: 1) {197 Text(Fmt.price(hi)).font(.subheadline.weight(.semibold)).monospacedDigit().foregroundStyle(Theme.ink)198 if let at = h.high90dAt { Text("le \(Fmt.dayMonth(at))").font(.caption).foregroundStyle(Theme.ink3) }199 }200 }201 }202 if let c = h.changes30d { FactRow("Changements de prix en 30 jours", String(c), divider: false) }203 }204 }205206 @ViewBuilder private var verdict: some View {207 VStack(alignment: .leading, spacing: 8) {208 Text("Verdict").eyebrowStyle().padding(.top, 6)209 if let v = detail.verdict, let position = v.position {210 VerdictBadge(position: position, label: v.label, scorePct: v.scorePct).accessibilityIdentifier("verdict-badge")211 // chaque comparaison, séparément : l'historique, puis les autres enseignes212 VStack(alignment: .leading, spacing: 3) {213 if let p = v.vsHistoryPct {214 Text((v.historyLabel ?? "Face à son prix habituel") + " : \(Fmt.pct(p, fine: true)) face à la médiane de 90 jours.")215 }216 if let p = v.vsStoresPct, let n = v.storesCompared {217 Text((v.storesLabel ?? "Face aux autres enseignes") + " : \(Fmt.pct(p, fine: true)) face au prix médian du même produit dans \(n) autres enseignes.")218 }219 if v.lowest90d { Text("Au plus bas en 90 jours.") }220 if position == .dans, v.vsHistoryPct == 0, v.vsStoresPct == nil {221 Text("Le prix n'a pas bougé depuis le début du suivi : c'est une absence de signal, pas un avis.")222 }223 }224 .font(.subheadline).monospacedDigit().foregroundStyle(Theme.ink2).fixedSize(horizontal: false, vertical: true)225 } else {226 Text("Prix non situé")227 .font(.caption.weight(.semibold)).foregroundStyle(Theme.ink3)228 .padding(.horizontal, 8).padding(.vertical, 5)229 .overlay(RoundedRectangle(cornerRadius: Theme.radiusTag, style: .continuous).strokeBorder(Theme.line2, style: StrokeStyle(lineWidth: 1, dash: [4, 3])))230 .accessibilityIdentifier("no-verdict")231 // la raison publiée par le service232 Text((detail.verdictReason?.label ?? ServiceInfo.noVerdictLabel(detail.card.verdictReason)233 ?? "Ni l'historique ni les autres enseignes ne suffisent pour situer ce prix") + ".")234 .font(.subheadline).foregroundStyle(Theme.ink2).fixedSize(horizontal: false, vertical: true)235 }236 if let d = detail.card.deal, let status = d.status {237 VStack(alignment: .leading, spacing: 4) {238 DealBadge(deal: d, long: true)239 if let ref = d.referencePrice {240 Text("Prix de référence : \(Fmt.price(ref))" + referenceNote(d) + (d.declaredRegular.map { " Prix régulier annoncé par l'enseigne : \(Fmt.price($0))." } ?? ""))241 .font(.subheadline).monospacedDigit().foregroundStyle(Theme.ink2).fixedSize(horizontal: false, vertical: true)242 }243 if showRule, d.clearance, let rule = ServiceInfo.current?.rules?.solde?["clearance"] {244 Text(Fmt.capitalized(rule) + ".").font(.footnote).foregroundStyle(Theme.ink3).fixedSize(horizontal: false, vertical: true)245 }246 if showRule, let rule = ServiceInfo.dealRule(status) {247 Text(Fmt.capitalized(rule) + ".").font(.footnote).foregroundStyle(Theme.ink3).fixedSize(horizontal: false, vertical: true)248 }249 }250 .padding(.top, 6)251 }252 Button(showRule ? "Masquer la règle" : "Comment c'est calculé") { withAnimation(.snappy) { showRule.toggle() } }253 .font(.footnote.weight(.medium)).foregroundStyle(Theme.brand).frame(minHeight: 44)254 if showRule, let r = ServiceInfo.current?.rules?.verdict {255 VStack(alignment: .leading, spacing: 6) {256 if let f = r.formule { Text(Fmt.capitalized(f) + ".") }257 if let regle = r.regle { Text(Fmt.capitalized(regle)) }258 if let b = r.base_historique { Text("Base historique : \(b).") }259 if let b = r.base_enseignes { Text("Base enseignes : \(b).") }260 if let j = r.justification { Text(j) }261 }262 .font(.footnote).monospacedDigit().foregroundStyle(Theme.ink3).fixedSize(horizontal: false, vertical: true)263 }264 }265 }266267 private func referenceNote(_ d: Deal) -> String {268 switch d.reference {269 case "historique": " (médiane observée avant la baisse)."270 case "catalogue": " (prix du même produit au catalogue de l'enseigne)."271 case "circulaires_precedentes": " (médiane de ses passages précédents en circulaire)."272 default: "."273 }274 }275}276277// --- Nutrition, description, détails --------------------------------------------------------------------278279struct DetailsSection: View {280 let detail: ProductDetail281 @Binding var safari: IdentifiedURL?282 @State private var expanded = false283284 var body: some View {285 VStack(alignment: .leading, spacing: 30) {286 if let n = detail.nutrition, n.hasContent { nutrition(n) }287 if let text = detail.description { description(text) }288 if !detail.attributes.isEmpty {289 VStack(alignment: .leading, spacing: 6) {290 SectionHeader("Caractéristiques")291 ForEach(Array(detail.attributes.enumerated()), id: \.offset) { i, a in292 FactRow(a.label, a.value, divider: i < detail.attributes.count - 1)293 }294 }295 }296 facts297 }298 }299300 private func nutrition(_ n: Nutrition) -> some View {301 VStack(alignment: .leading, spacing: 10) {302 SectionHeader("Valeur nutritive", eyebrow: "Pour 100 g ou 100 ml")303 if !n.rows.isEmpty {304 VStack(spacing: 0) {305 ForEach(Array(n.rows.enumerated()), id: \.element.id) { i, r in306 FactRow(r.label, r.value, divider: i < n.rows.count - 1)307 }308 }309 .padding(.horizontal, 12)310 .overlay(RoundedRectangle(cornerRadius: Theme.radiusSmall, style: .continuous).strokeBorder(Theme.ink, lineWidth: 1.5))311 }312 if let s = n.nutriscore { FactRow("Nutri-Score", s.uppercased()) }313 if let nova = n.nova { FactRow("Degré de transformation (NOVA)", "\(nova) sur 4") }314 if let i = n.ingredients {315 Text("Ingrédients : " + i).font(.footnote).foregroundStyle(Theme.ink2).fixedSize(horizontal: false, vertical: true)316 }317 if !n.allergens.isEmpty {318 Text("Allergènes : " + n.allergens.joined(separator: ", ")).font(.footnote.weight(.medium)).foregroundStyle(Theme.ink2)319 .fixedSize(horizontal: false, vertical: true)320 }321 // l'assise de la donnée : d'où elle vient et comment elle a été rapprochée322 HonestNote(text: "Source : \(n.source ?? "Open Food Facts")"323 + (n.matchedName.map { ", fiche « \($0) »" } ?? "")324 + (n.matchSimilarity.map { ", rapprochée à " + Fmt.pct($0 * 100, signed: false) } ?? "")325 + ". Donnée indicative : l'étiquette du produit fait foi.")326 if let u = n.sourceURL.flatMap(URL.init(string:)), u.scheme == "https" {327 Button("Voir la fiche d'Open Food Facts") { safari = IdentifiedURL(url: u) }328 .font(.footnote.weight(.medium)).foregroundStyle(Theme.brand).frame(minHeight: 44)329 }330 }331 .id("nutrition")332 .accessibilityIdentifier("nutrition")333 }334335 private func description(_ text: String) -> some View {336 VStack(alignment: .leading, spacing: 8) {337 SectionHeader("Description", note: "Texte publié par \(detail.card.storeName).")338 Text(text).font(.subheadline).foregroundStyle(Theme.ink2)339 .lineLimit(expanded ? nil : 6).fixedSize(horizontal: false, vertical: true)340 if text.count > 320 {341 Button(expanded ? "Réduire" : "Lire la suite") { withAnimation(.snappy) { expanded.toggle() } }342 .font(.footnote.weight(.medium)).foregroundStyle(Theme.brand).frame(minHeight: 44)343 }344 }345 }346347 private var facts: some View {348 let c = detail.card349 return VStack(alignment: .leading, spacing: 6) {350 SectionHeader("Détails")351 if let f = detail.format?.label ?? c.size {352 FactRow("Format", f + (detail.format?.approximate == true ? " (approximatif)" : "") + (detail.format?.variable == true ? " (au choix)" : ""))353 }354 if let b = c.brand { FactRow("Marque", b) }355 if let cat = c.category { FactRow("Rayon", [cat, c.subcategory].compactMap { $0 }.joined(separator: " · ")) }356 FactRow("Enseigne", c.storeName)357 if let u = c.unitPrice {358 FactRow(label: "Prix unitaire") {359 VStack(alignment: .trailing, spacing: 1) {360 Text(u.label).font(.subheadline.weight(.semibold)).monospacedDigit().foregroundStyle(Theme.ink)361 if let b = ServiceInfo.basisLabel(u.basis) { Text(b).font(.caption).foregroundStyle(Theme.ink3) }362 }363 }364 } else {365 FactRow("Prix unitaire", detail.format?.variable == true ? "format au choix : non calculé" : "format inconnu : non calculé")366 }367 if let s = detail.inStock { FactRow("Disponibilité", s ? "En stock au dernier relevé" : "Rupture signalée") }368 if !c.tags.isEmpty {369 FactRow("Mentions (indicatives)", c.tags.map { Self.tagLabel($0) }.joined(separator: ", "))370 }371 if let f = detail.firstSeen { FactRow("Suivi depuis", Fmt.date(f)) }372 if let l = detail.lastSeen { FactRow("Dernier relevé", Fmt.date(l) + (Fmt.ago(l).map { " (\($0))" } ?? "")) }373 if detail.duplicatesHidden > 0 {374 FactRow("Doublons masqués", "\(detail.duplicatesHidden) dans la même enseigne")375 }376 if let code = detail.barcode {377 FactRow("Code-barres", code + (detail.barcodeSource == "open_food_facts" ? " (apparié par le nom, à confirmer)" : ""))378 }379 FactRow("Identifiant", c.id, divider: false)380 if let scope = detail.priceScope, !scope.needsWarning, let note = scope.note {381 HonestNote(text: note).padding(.top, 4)382 }383 }384 }385386 static func tagLabel(_ t: String) -> String {387 switch t {388 case "bio": "biologique"389 case "local": "du Québec"390 case "sans_gluten": "sans gluten"391 case "vegane": "végane"392 case "sans_lactose": "sans lactose"393 default: t394 }395 }396}397