Repository Public
1//2// Auto-Ka iOS v23// File: AutoKa/Core/Util/Format.swift4// Description: formats d'affichage (français du Québec) — prix, kilométrage, écarts signés, dates, unités.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8//910import Foundation1112/// Unité de distance choisie dans les réglages. Les données du service sont toujours en kilomètres.13enum DistanceUnit: String, CaseIterable, Identifiable, Sendable {14 case km, mi15 var id: String { rawValue }16 var label: String { self == .km ? "Kilomètres" : "Milles" }17 var symbol: String { rawValue }18 /// kilomètres → valeur dans l'unité19 func value(_ km: Double) -> Double { self == .km ? km : km / 1.609344 }2021 static var current: DistanceUnit {22 DistanceUnit(rawValue: UserDefaults.standard.string(forKey: "units") ?? "") ?? .km23 }24}2526enum Fmt {27 static let locale = Locale(identifier: "fr_CA")28 /// espace insécable étroite entre un nombre et son symbole29 static let nbsp = "\u{00A0}"30 private static let intStyle = IntegerFormatStyle<Int>.number.locale(locale).grouping(.automatic)3132 /// 1 23433 static func int(_ n: Int?) -> String {34 guard let n else { return "—" }35 return n.formatted(intStyle)36 }3738 static func int(_ d: Double?) -> String { int(d.map { Int($0.rounded()) }) }3940 /// 28 939 $41 static func money(_ d: Double?) -> String {42 guard let d else { return "—" }43 return "\(int(d))\(nbsp)$"44 }4546 /// Montant signé : « −1 846 $ », « +3 195 $ » (vrai signe moins).47 static func signedMoney(_ d: Double?) -> String {48 guard let d else { return "—" }49 let v = Int(d.rounded())50 return "\(v > 0 ? "+" : (v < 0 ? "−" : ""))\(int(abs(v)))\(nbsp)$"51 }5253 /// Étiquettes de carte et graduations : 28 939 → « 28,9 k$ », 30 000 → « 30 k$ », 850 → « 850 $ », 125 400 → « 125 k$ »54 static func kPrice(_ d: Double?) -> String {55 guard let d else { return "—" }56 if abs(d) < 1000 { return "\(Int(d.rounded()))\(nbsp)$" }57 let k = d / 100058 if abs(k) >= 100 { return "\(Int(k.rounded()))\(nbsp)k$" }59 let r = (k * 10).rounded() / 1060 let s = r == r.rounded() ? String(Int(r)) : String(format: "%.1f", r).replacingOccurrences(of: ".", with: ",")61 return "\(s)\(nbsp)k$"62 }6364 /// Kilométrage dans l'unité des réglages : « 110 641 km », « 68 749 mi ».65 static func mileage(_ km: Double?, unit: DistanceUnit = .current) -> String {66 guard let km else { return "Kilométrage non indiqué" }67 return "\(int(unit.value(km)))\(nbsp)\(unit.symbol)"68 }6970 /// Kilométrage court pour une ligne de faits (« — » si inconnu).71 static func mileageShort(_ km: Double?, unit: DistanceUnit = .current) -> String? {72 guard let km else { return nil }73 return "\(int(unit.value(km)))\(nbsp)\(unit.symbol)"74 }7576 /// Distance : 0,5 → « 500 m », 12,4 → « 12 km », en milles selon les réglages.77 static func distance(km: Double?, unit: DistanceUnit = .current) -> String {78 guard let km else { return "—" }79 if unit == .km {80 if km < 1 { return "\(max(100, Int((km * 10).rounded()) * 100))\(nbsp)m" }81 if km < 10 { return String(format: "%.1f", km).replacingOccurrences(of: ".", with: ",") + "\(nbsp)km" }82 return "\(int(km))\(nbsp)km"83 }84 let mi = unit.value(km)85 if mi < 10 { return String(format: "%.1f", mi).replacingOccurrences(of: ".", with: ",") + "\(nbsp)mi" }86 return "\(int(mi))\(nbsp)mi"87 }8889 /// Écart en pourcentage déjà exprimé en points : −6 → « −6,0 % », 10.4 → « +10,4 % » (une décimale, vrai signe moins).90 static func signedPct(_ p: Double?, digits: Int = 1) -> String {91 guard let p else { return "—" }92 let r = (p * pow(10, Double(digits))).rounded() / pow(10, Double(digits))93 let body = String(format: "%.\(digits)f", abs(r)).replacingOccurrences(of: ".", with: ",")94 return "\(r > 0 ? "+" : (r < 0 ? "−" : ""))\(body)\(nbsp)%"95 }9697 /// Part : 36.3 → « 36,3 % »98 static func pct(_ p: Double?, digits: Int = 1) -> String {99 guard let p else { return "—" }100 return String(format: "%.\(digits)f", p).replacingOccurrences(of: ".", with: ",") + "\(nbsp)%"101 }102103 /// 24.7 → « 24,7 »104 static func decimal(_ d: Double?, digits: Int = 1) -> String {105 guard let d else { return "—" }106 if d == d.rounded() { return int(d) }107 return String(format: "%.\(digits)f", d).replacingOccurrences(of: ".", with: ",")108 }109110 static func plural(_ n: Int, _ one: String, _ many: String) -> String { "\(int(n)) \(n > 1 ? many : one)" }111112 /// Horodatage Unix → « il y a 3 h »113 static func ago(_ ts: Double?) -> String {114 guard let ts, ts > 0 else { return "—" }115 let s = max(0, Date().timeIntervalSince1970 - ts)116 if s < 90 { return "à l'instant" }117 if s < 3600 { return "il y a \(Int((s / 60).rounded())) min" }118 if s < 86400 { return "il y a \(Int((s / 3600).rounded())) h" }119 let d = Int((s / 86400).rounded())120 if d < 31 { return "il y a \(d) j" }121 if d < 365 { return "il y a \(Int((Double(d) / 30).rounded())) mois" }122 let y = Int((Double(d) / 365).rounded())123 return "il y a \(y) an\(y > 1 ? "s" : "")"124 }125126 /// « 12 novembre 2026 »127 static func date(_ ts: Double?) -> String {128 guard let ts, ts > 0 else { return "—" }129 return Date(timeIntervalSince1970: ts).formatted(.dateTime.day().month(.wide).year().locale(locale))130 }131132 /// « 12 novembre »133 static func dayMonth(_ ts: Double?) -> String {134 guard let ts, ts > 0 else { return "—" }135 return Date(timeIntervalSince1970: ts).formatted(.dateTime.day().month(.wide).locale(locale))136 }137138 /// « 2019-09-13 » → « 13 septembre 2019 »139 static func isoDay(_ s: String?) -> String {140 guard let s else { return "—" }141 let p = s.prefix(10).split(separator: "-").compactMap { Int($0) }142 guard p.count == 3 else { return s }143 var c = DateComponents(); c.year = p[0]; c.month = p[1]; c.day = p[2]144 guard let d = Calendar(identifier: .gregorian).date(from: c) else { return s }145 return d.formatted(.dateTime.day().month(.wide).year().locale(locale))146 }147148 static func isoDate(_ s: String) -> Date? {149 let p = s.prefix(10).split(separator: "-").compactMap { Int($0) }150 guard p.count == 3 else { return nil }151 var c = DateComponents(); c.year = p[0]; c.month = p[1]; c.day = p[2]152 return Calendar(identifier: .gregorian).date(from: c)153 }154155 /// « En vente depuis 34 jours »156 static func daysListed(_ d: Int?) -> String? {157 guard let d else { return nil }158 if d <= 0 { return "En vente depuis aujourd'hui" }159 return "En vente depuis \(d) jour\(d > 1 ? "s" : "")"160 }161162 /// Version (« trim ») lisible : les sources y collent du texte de vente (« FWD // Mags // Cruise adaptatif »,163 /// « LX *AWD* Mags Camera Bluetooth »). On garde la tête, quatre mots et 26 caractères au plus.164 static func cleanTrim(_ raw: String?) -> String {165 guard var t = raw?.trimmingCharacters(in: .whitespacesAndNewlines), !t.isEmpty else { return "" }166 for sep in ["//", "|", "*", " - ", ",", "(", "+", " /"] {167 if let r = t.range(of: sep) { t = String(t[..<r.lowerBound]) }168 }169 var words: [Substring] = []170 var len = 0171 for w in t.split(separator: " ") {172 if words.count == 4 || len + w.count > 26 { break }173 words.append(w); len += w.count + 1174 }175 return words.joined(separator: " ").trimmingCharacters(in: .whitespacesAndNewlines)176 }177178 /// Identifiant d'annonce encodé pour un chemin d'URL (« hgregoire:82984866 » → « hgregoire%3A82984866 »).179 static func pathComponent(_ s: String) -> String {180 var allowed = CharacterSet.alphanumerics181 allowed.insert(charactersIn: "-._~")182 return s.addingPercentEncoding(withAllowedCharacters: allowed) ?? s183 }184185 /// Slug identique à celui du serveur : minuscules, sans accents, le reste devient « - ».186 static func slug(_ text: String) -> String {187 let t = text.replacingOccurrences(of: "œ", with: "oe").replacingOccurrences(of: "Œ", with: "oe")188 .folding(options: [.diacriticInsensitive, .caseInsensitive], locale: Locale(identifier: "en_US")).lowercased()189 var out = ""190 var dash = false191 for ch in t.unicodeScalars {192 if (ch.value >= 97 && ch.value <= 122) || (ch.value >= 48 && ch.value <= 57) {193 out.unicodeScalars.append(ch); dash = false194 } else if !dash, !out.isEmpty {195 out.append("-"); dash = true196 }197 }198 if out.hasSuffix("-") { out.removeLast() }199 return String(out.prefix(70))200 }201202 /// Numéro de téléphone → adresse `tel:` (chiffres seulement).203 static func telURL(_ phone: String?) -> URL? {204 guard let phone else { return nil }205 let digits = phone.filter(\.isNumber)206 guard digits.count >= 10 else { return nil }207 return URL(string: "tel:\(digits)")208 }209210 /// NIV : 17 caractères, sans I, O ni Q.211 static func isValidVIN(_ s: String) -> Bool {212 let v = s.uppercased()213 guard v.count == 17 else { return false }214 return v.allSatisfy { ($0.isASCII && ($0.isLetter || $0.isNumber)) && !"IOQ".contains($0) }215 }216}217