Repository Public
1//2// Food-Ka iOS v23// File: FoodKa/Core/Util/Format.swift4// Description: écriture des prix, des écarts, des quantités et des dates en français du Québec5// (« 4,97 $ », « −0,96 $ », « −16 % », « 26 novembre 2026 », « 19 nov. »).6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9//1011import Foundation1213enum Fmt {14 /// espace insécable (entre le nombre et « $ » ou « % »)15 static let nbsp = "\u{00A0}"16 /// vrai signe moins17 static let minus = "\u{2212}"1819 private static let locale = Locale(identifier: "fr_CA")20 private static let zone = TimeZone(identifier: "America/Toronto") ?? .current2122 private static func decimal(_ v: Double, _ digits: Int) -> String {23 let neg = v < 024 let a = abs(v)25 let p = pow(10.0, Double(digits))26 let r = (a * p).rounded() / p27 let whole = Int(r.rounded(.down))28 var s = group(whole)29 if digits > 0 {30 let frac = Int(((r - Double(whole)) * p).rounded())31 let f = String(frac)32 s += "," + String(repeating: "0", count: max(0, digits - f.count)) + f33 }34 return (neg && r != 0 ? minus : "") + s35 }3637 /// Milliers séparés par une espace insécable (à partir de 10 000, comme l'usage québécois : 1234 mais 49 203).38 static func group(_ n: Int) -> String {39 let s = String(abs(n))40 guard s.count > 4 else { return (n < 0 ? minus : "") + s }41 var out = ""42 for (i, c) in s.reversed().enumerated() {43 if i > 0, i % 3 == 0 { out.append(nbsp) }44 out.append(c)45 }46 return (n < 0 ? minus : "") + String(out.reversed())47 }4849 static func count(_ n: Int?) -> String { n.map(group) ?? "—" }5051 /// « 4,97 $ »52 static func price(_ v: Double?) -> String {53 guard let v else { return "—" }54 return decimal(v, 2) + nbsp + "$"55 }5657 /// Écart signé en dollars : « +0,52 $ », « −0,96 $ », « 0,00 $ ».58 static func diff(_ v: Double?) -> String {59 guard let v else { return "—" }60 let r = (v * 100).rounded() / 10061 if r == 0 { return decimal(0, 2) + nbsp + "$" }62 return (r > 0 ? "+" : minus) + decimal(abs(r), 2) + nbsp + "$"63 }6465 /// Pourcentage signé : « −16 % », « +9 % » ; une décimale sous 10 % si `fine`.66 static func pct(_ v: Double?, fine: Bool = false, signed: Bool = true) -> String {67 guard let v else { return "—" }68 let digits = fine && abs(v) < 10 ? 1 : 069 let p = pow(10.0, Double(digits))70 let r = (v * p).rounded() / p71 let sign = !signed || r == 0 ? "" : (r > 0 ? "+" : minus)72 return sign + decimal(abs(r), digits) + nbsp + "%"73 }7475 /// Nombre à décimales fixes : « 100,14 ».76 static func number(_ v: Double?, digits: Int = 1) -> String {77 guard let v else { return "—" }78 return decimal(v, digits)79 }8081 /// Quantité d'une ligne de liste : « 2 », « 1,5 ».82 static func quantity(_ q: Double) -> String {83 q == q.rounded() ? String(Int(q)) : decimal(q, 1)84 }8586 static func plural(_ n: Int, _ one: String, _ many: String) -> String {87 group(n) + " " + (n < 2 ? one : many)88 }8990 // --- Dates -------------------------------------------------------------------------------9192 private static func formatter(_ template: String) -> DateFormatter {93 let f = DateFormatter()94 f.locale = locale95 f.timeZone = zone96 f.dateFormat = template97 return f98 }99100 private nonisolated(unsafe) static let longF = formatter("d MMMM yyyy")101 private nonisolated(unsafe) static let dayMonthF = formatter("d MMMM")102 private nonisolated(unsafe) static let shortF = formatter("d MMM")103 private nonisolated(unsafe) static let isoF = formatter("yyyy-MM-dd")104 private static let lock = NSLock()105106 private static func fix(_ s: String) -> String {107 // « 1 novembre » → « 1er novembre »108 s.hasPrefix("1 ") ? "1er " + s.dropFirst(2) : s109 }110111 /// « 26 novembre 2026 »112 static func date(_ t: Double?) -> String {113 guard let t else { return "—" }114 lock.lock(); defer { lock.unlock() }115 return fix(longF.string(from: Date(timeIntervalSince1970: t)))116 }117118 /// « 26 novembre »119 static func dayMonth(_ t: Double?) -> String {120 guard let t else { return "—" }121 lock.lock(); defer { lock.unlock() }122 return fix(dayMonthF.string(from: Date(timeIntervalSince1970: t)))123 }124125 /// « 19 nov. »126 static func shortDate(_ t: Double?) -> String {127 guard let t else { return "—" }128 lock.lock(); defer { lock.unlock() }129 return fix(shortF.string(from: Date(timeIntervalSince1970: t)))130 }131132 static func shortDate(_ d: Date) -> String { shortDate(d.timeIntervalSince1970) }133134 /// Date d'une chaîne « 2026-11-23 ».135 static func isoDay(_ s: String?) -> Date? {136 guard let s else { return nil }137 lock.lock(); defer { lock.unlock() }138 return isoF.date(from: s)139 }140141 /// Plage de validité d'une circulaire : « du 26 nov. au 2 déc. ».142 static func range(_ from: Double?, _ to: Double?) -> String? {143 switch (from, to) {144 case let (a?, b?): "du \(shortDate(a)) au \(shortDate(b))"145 case let (nil, b?): "jusqu'au \(shortDate(b))"146 case let (a?, nil): "depuis le \(shortDate(a))"147 default: nil148 }149 }150151 /// Ancienneté d'un relevé : « il y a 12 min », « il y a 3 h », « il y a 2 jours ».152 static func ago(_ t: Double?, now: Date = Date()) -> String? {153 guard let t else { return nil }154 let s = max(0, now.timeIntervalSince1970 - t)155 if s < 90 { return "à l'instant" }156 if s < 3600 { return "il y a \(Int(s / 60)) min" }157 if s < 36 * 3600 { return "il y a \(Int((s / 3600).rounded())) h" }158 let d = Int((s / 86400).rounded())159 return "il y a \(d) jours"160 }161162 /// Ancienneté en heures (fraîcheur d'une enseigne).163 static func age(hours: Double?) -> String? {164 guard let h = hours else { return nil }165 if h < 1 { return "il y a moins d'une heure" }166 if h < 36 { return "il y a \(Int(h.rounded())) h" }167 return "il y a \(Int((h / 24).rounded())) jours"168 }169170 /// Jours restants avant la fin d'une validité : « se termine aujourd'hui », « encore 3 jours ».171 static func remaining(_ to: Double?, now: Date = Date()) -> String? {172 guard let to else { return nil }173 let s = to - now.timeIntervalSince1970174 if s < 0 { return "terminée" }175 let d = Int(s / 86400)176 if d == 0 { return "se termine aujourd'hui" }177 if d == 1 { return "encore 1 jour" }178 return "encore \(d) jours"179 }180181 /// Première lettre en majuscule (libellés du serveur écrits en minuscules : « bon prix »).182 static func capitalized(_ s: String) -> String {183 guard let f = s.first else { return s }184 return f.uppercased() + s.dropFirst()185 }186}187