SPB Git

Repository Public

Format.swift 12.5 KB 276 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : Immo-Ka iOS9// File             : ImmoKa/Core/Util/Format.swift10// Description      : formats d'affichage (français du Québec) et petites aides11//                    de texte.12// Module           : ImmoKa13// Repository       : https://git.spboucher.ai/immo-ka-ios-v314// Project Website  : https://www.immo-ka.com15// Created          : 2026-11-2516// Last Modified    : 2026-11-2817//18// =============================================================================19// AUTHOR & PROFESSIONAL AFFILIATION20// =============================================================================21//22// Author           : Simon-Pierre Boucher23// Position         : Professor of Finance24// Institution      : Université du Québec en Outaouais (UQO)25// Department       : Département des sciences administratives26// Organization     : SP Boucher27//28// Website          : https://spboucher.ai29// Git              : https://git.spboucher.ai30//31// =============================================================================32// OFFICIAL CONTACT DIRECTORY33// =============================================================================34//35// General          : info@spboucher.ai36// Professional     : contact@spboucher.ai37// Direct           : simon@spboucher.ai38// Research         : research@spboucher.ai39// Development      : dev@spboucher.ai40// Support          : support@spboucher.ai41// Security/Admin   : admin@spboucher.ai42// Notifications    : notifications@spboucher.ai43//44// Preferred Contact: support@spboucher.ai45//46// =============================================================================47// COPYRIGHT & INTELLECTUAL PROPERTY48// =============================================================================49//50// Copyright (c) 202651// Simon-Pierre Boucher52//53// All rights reserved where applicable.54//55// This file is governed by the applicable project license,56// copyright notices, institutional agreements and relevant law.57//58// Unless expressly authorized by the applicable license or59// rights holder, copying, redistribution, sublicensing,60// publication and commercial exploitation are not permitted.61//62// Existing third-party rights and notices remain unaffected.63//64// =============================================================================65// CONFIDENTIALITY & SECURITY66// =============================================================================67//68// Classification   : Public69// Distribution     : Public repository; use is governed by the project license70// Security Contact : admin@spboucher.ai71//72// Access to this source does not independently grant permission73// to redistribute or disclose confidential materials.74//75// Do not embed credentials, private keys, access tokens,76// certificates or confidential personal information.77//78// =============================================================================79// LICENSE & MAINTENANCE80// =============================================================================81//82// License          : None specified (no license file in this repository)83// Maintainer       : Simon-Pierre Boucher84// Technical Contact: dev@spboucher.ai85//86// =============================================================================87// END OF SP BOUCHER SOURCE HEADER88// =============================================================================8990import Foundation9192enum Fmt {93    static let locale = Locale(identifier: "fr_CA")9495    private static let intStyle = IntegerFormatStyle<Int>.number.locale(locale).grouping(.automatic)9697    /// 1 23498    static func int(_ n: Int?) -> String {99        guard let n else { return "—" }100        return n.formatted(intStyle)101    }102103    static func int(_ d: Double?) -> String { int(d.map { Int($0.rounded()) }) }104105    /// 1 234 $106    static func money(_ d: Double?) -> String {107        guard let d else { return "—" }108        return "\(int(d)) $"109    }110111    /// Étiquette de carte et prix compacts : 425 000 → « 425 k », 1 195 000 → « 1,2 M », 12 400 000 → « 12 M »112    static func shortPrice(_ d: Double?) -> String {113        guard let d, Listing.priceIsPlausible(d) else { return "•" }114        func one(_ v: Double) -> String {115            let r = (v * 10).rounded() / 10116            return r == r.rounded() ? String(Int(r)) : String(format: "%.1f", r).replacingOccurrences(of: ".", with: ",")117        }118        if d < 999_500 { return "\(Int((d / 1000).rounded())) k" }119        if d < 9_950_000 { return "\(one(d / 1_000_000)) M" }120        return "\(Int((d / 1_000_000).rounded())) M"121    }122123    /// Prix compact avec devise : « 425 k$ », « 1,2 M$ »124    static func compactMoney(_ d: Double?) -> String {125        guard let d else { return "—" }126        if abs(d) < 1000 { return money(d) }127        func one(_ v: Double) -> String {128            let r = (v * 10).rounded() / 10129            return r == r.rounded() ? String(Int(r)) : String(format: "%.1f", r).replacingOccurrences(of: ".", with: ",")130        }131        if abs(d) < 999_500 { return "\(Int((d / 1000).rounded())) k$" }132        return "\(one(d / 1_000_000)) M$"133    }134135    /// 4,74 → « 4,74 % »136    static func rate(_ r: Double?, digits: Int = 2) -> String {137        guard let r else { return "—" }138        return String(format: "%.\(digits)f", r).replacingOccurrences(of: ".", with: ",") + " %"139    }140141    /// 1234,5 → « 1 234,5 » (une décimale au plus)142    static func decimal(_ d: Double) -> String {143        if d == d.rounded() { return int(d) }144        return d.formatted(.number.locale(locale).precision(.fractionLength(0...1)))145    }146147    /// 60 → « 5 ans », 6 → « 6 mois »148    static func term(_ months: Int) -> String {149        if months % 12 == 0 { let y = months / 12; return "\(y) an\(y > 1 ? "s" : "")" }150        return "\(months) mois"151    }152153    /// « 2026-11-25 » → date154    /// « 2026-07-27 » → « 27 juillet 2026 » (la chaîne d'origine si elle n'est pas une date).155    static func day(_ iso: String?) -> String {156        guard let iso else { return "" }157        guard let d = isoDay(String(iso.prefix(10))) else { return iso }158        let t = d.formatted(.dateTime.day().month(.wide).year().locale(locale))159        return t.hasPrefix("1 ") ? "1er " + t.dropFirst(2) : t160    }161162    static func isoDay(_ s: String) -> Date? {163        let p = s.prefix(10).split(separator: "-").compactMap { Int($0) }164        guard p.count == 3 else { return nil }165        var c = DateComponents(); c.year = p[0]; c.month = p[1]; c.day = p[2]166        return Calendar(identifier: .gregorian).date(from: c)167    }168169    /// Superficie : pieds carrés, et acres pour les grands terrains.170    static func area(_ sqft: Double?) -> String? {171        guard let a = sqft, a > 0 else { return nil }172        if a >= 43_560 * 1.5 { return String(format: "%.1f acres", a / 43_560).replacingOccurrences(of: ".", with: ",") }173        return "\(int(a)) pi²"174    }175176    /// « EXP AGENCE IMMOBILIÈRE » → « EXP Agence Immobilière », « RE/MAX DU CARTIER INC. » → « RE/MAX du Cartier inc. »177    /// (les registres publient en capitales). Un nom déjà en casse mixte est laissé tel quel.178    static func titleCase(_ s: String) -> String {179        guard s == s.uppercased(), s.count > 4, s.contains(" ") else { return s }180        let small: Set<String> = ["de", "du", "des", "la", "le", "les", "et", "en", "au", "aux", "inc.", "inc", "ltée", "enr."]181        let acronyms: Set<String> = ["kw", "exp", "rlp", "bsl", "c21"]182        func cap(_ w: String) -> String { w.prefix(1).uppercased() + w.dropFirst() }183        return s.split(separator: " ").enumerated().map { i, w in184            let raw = String(w), word = raw.lowercased()185            // sigles, marques à barre oblique (RE/MAX) et initiales (P.M.) gardent leurs capitales186            if raw.contains("/") || acronyms.contains(word) { return raw }187            if raw.dropLast().contains("."), raw.count <= 5 { return raw }188            if i > 0, small.contains(word) { return word }189            // « l'expert » → « L'Expert », « d'agences » → « d'Agences »190            if let q = word.firstIndex(where: { $0 == "'" || $0 == "’" }), word.distance(from: word.startIndex, to: q) == 1 {191                let head = String(word[...q]), tail = String(word[word.index(after: q)...])192                return (i == 0 ? head.uppercased() : head) + cap(tail)193            }194            return word.split(separator: "-").map { cap(String($0)) }.joined(separator: "-")195        }.joined(separator: " ")196    }197198    /// Une « ville » publiée par une source en est-elle une ? (écarte « 5 », « A », « Acheter Condo … »)199    static func isPlausibleCity(_ c: String) -> Bool {200        let t = c.trimmingCharacters(in: .whitespacesAndNewlines)201        guard t.count >= 3, t.count <= 48, let f = t.unicodeScalars.first, CharacterSet.uppercaseLetters.contains(f) else { return false }202        if t.contains(where: \.isNumber) { return false }203        // zones des petites annonces, pas des villes : « Laval / North Shore », « City of Montréal », « Québec City »204        if t.contains("/") || t.hasPrefix("City of ") || t.hasSuffix(" City") { return false }205        let low = t.lowercased()206        return !["acheter", "vendre", "louer", "http", "maison", "condo "].contains { low.hasPrefix($0) }207    }208209    /// -0,167 → « −17 % »210    static func pct(_ x: Double?, signed: Bool = true) -> String {211        guard let x else { return "—" }212        let v = Int((x * 100).rounded())213        let sign = (!signed || v == 0) ? "" : (v > 0 ? "+" : "−")214        return "\(sign)\(abs(v)) %"215    }216217    /// 250 → « 250 m », 1240 → « 1,2 km »218    static func distance(_ m: Double?) -> String {219        guard let m else { return "—" }220        if m < 1000 { return "\(Int((m / 10).rounded()) * 10) m" }221        return String(format: "%.1f km", m / 1000).replacingOccurrences(of: ".", with: ",")222    }223224    /// Horodatage Unix → « il y a 3 h »225    static func ago(_ ts: Double?) -> String {226        guard let ts, ts > 0 else { return "—" }227        let s = max(0, Date().timeIntervalSince1970 - ts)228        if s < 90 { return "à l'instant" }229        if s < 3600 { return "il y a \(Int((s / 60).rounded())) min" }230        if s < 86400 { return "il y a \(Int((s / 3600).rounded())) h" }231        let d = Int((s / 86400).rounded())232        if d < 31 { return "il y a \(d) j" }233        if d < 365 { return "il y a \(Int((Double(d) / 30).rounded())) mois" }234        let y = Int((Double(d) / 365).rounded())235        return "il y a \(y) an\(y > 1 ? "s" : "")"236    }237238    static func date(_ ts: Double?) -> String {239        guard let ts, ts > 0 else { return "—" }240        return Date(timeIntervalSince1970: ts).formatted(.dateTime.day().month(.wide).year().locale(locale))241    }242243    static func plural(_ n: Int, _ one: String, _ many: String) -> String {244        "\(int(n)) \(n > 1 ? many : one)"245    }246247    /// Nettoie les libellés de ville mal formés publiés par certaines sources.248    static func cleanCity(_ c: String?) -> String {249        (c ?? "").replacingOccurrences(of: "(", with: "").replacingOccurrences(of: ")", with: "")250            .replacingOccurrences(of: "*", with: "")251            .trimmingCharacters(in: .whitespacesAndNewlines)252    }253254    /// Slug identique à celui du serveur (seo.slugify).255    static func slug(_ text: String) -> String {256        var t = text.replacingOccurrences(of: "½", with: "-1-2").replacingOccurrences(of: "+", with: "-plus")257            .replacingOccurrences(of: "œ", with: "oe").replacingOccurrences(of: "Œ", with: "Oe")258        t = t.folding(options: [.diacriticInsensitive, .caseInsensitive], locale: Locale(identifier: "en_US")).lowercased()259        var out = ""260        var dash = false261        for ch in t.unicodeScalars {262            if (ch.value >= 97 && ch.value <= 122) || (ch.value >= 48 && ch.value <= 57) {263                out.unicodeScalars.append(ch); dash = false264            } else if !dash, !out.isEmpty {265                out.append("-"); dash = true266            }267        }268        return out.hasSuffix("-") ? String(out.dropLast()) : out269    }270271    /// Nom lisible de repli pour un identifiant de source (« groupe_xyz » → « Groupe Xyz »).272    static func prettySource(_ id: String) -> String {273        id.replacingOccurrences(of: "_", with: " ").capitalized(with: locale)274    }275}276
Files main
Menu

Theme