SPB Git

Repository Public

Format.swift 11.6 KB 263 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : Valo-Plex iOS9// File             : ValoPlex/Core/Format.swift10// Description      : formats fr-CA (montants, pourcentages, dates, adresses),11//                    identiques à ceux du site (src/lib/format.ts).12// Module           : ValoPlex13// Repository       : https://git.spboucher.ai/valo-plex-ios14// Project Website  : https://www.valo-plex.com15// Created          : 2026-12-0116// Last Modified    : 2026-12-0117//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    /// Espace insécable, comme sur le site : un montant ne se coupe jamais en fin de ligne.94    static let nb = "\u{00A0}"95    static let vide = "—"9697    /// Nombre à décimales fixes, milliers séparés par une espace insécable, virgule décimale.98    static func nombre(_ v: Double?, _ decimales: Int = 0) -> String {99        guard let v, v.isFinite else { return vide }100        let facteur = pow(10.0, Double(decimales))101        let arrondi = (abs(v) * facteur).rounded() / facteur102        let entier = arrondi.rounded(.towardZero)103        var chiffres = String(format: "%.0f", entier)104        var groupes: [String] = []105        while chiffres.count > 3 {106            groupes.insert(String(chiffres.suffix(3)), at: 0)107            chiffres = String(chiffres.dropLast(3))108        }109        groupes.insert(chiffres, at: 0)110        var s = groupes.joined(separator: nb)111        if decimales > 0 {112            let frac = Int(((arrondi - entier) * facteur).rounded())113            let f = String(frac)114            s += "," + String(repeating: "0", count: max(0, decimales - f.count)) + f115        }116        let nul = arrondi == 0117        return (v < 0 && !nul ? "−" : "") + s118    }119120    static func nombre(_ v: Int?) -> String { nombre(v.map(Double.init)) }121122    /// 955000 → « 955 000 $ ».123    static func dollars(_ v: Double?) -> String {124        guard let v, v.isFinite else { return vide }125        return nombre(v.rounded()) + nb + "$"126    }127128    /// 1 250 000 → « 1,25 M$ » ; 426 000 000 000 → « 426,6 G$ » ; 318 333 → « 318 k$ ».129    static func grand(_ v: Double?) -> String {130        guard let v, v.isFinite else { return vide }131        if abs(v) >= 1e9 { return nombre(v / 1e9, 1) + nb + "G$" }132        if abs(v) >= 1e6 { return nombre(v / 1e6, 2) + nb + "M$" }133        if abs(v) >= 1e3 { return nombre(v / 1e3, 0) + nb + "k$" }134        return dollars(v)135    }136137    /// Fraction → pourcentage : 0.0417 → « 4,17 % ».138    static func pct(_ fraction: Double?, _ decimales: Int = 1, signe: Bool = false) -> String {139        guard let fraction, fraction.isFinite else { return vide }140        let v = fraction * 100141        let s = nombre(v, decimales)142        let positif = signe && v > 0 && s != nombre(0, decimales)143        return (positif ? "+" : "") + s + nb + "%"144    }145146    /// Valeur déjà exprimée en pour cent (mesures du modèle) : 10.49 → « 10,5 % ».147    static func pourcent(_ v: Double?, _ decimales: Int = 1, signe: Bool = false) -> String {148        guard let v, v.isFinite else { return vide }149        return (signe && v > 0 ? "+" : "") + nombre(v, decimales) + nb + "%"150    }151152    static let mois = ["janvier", "février", "mars", "avril", "mai", "juin", "juillet", "août", "septembre", "octobre", "novembre", "décembre"]153154    /// « 2026-11-18 » → « 18 novembre 2026 ».155    static func dateLongue(_ iso: String?) -> String {156        guard let iso, !iso.isEmpty else { return vide }157        let p = iso.prefix(10).split(separator: "-").compactMap { Int($0) }158        guard p.count == 3, (1...12).contains(p[1]), p[2] > 0 else { return iso }159        return "\(p[2] == 1 ? "1er" : String(p[2])) \(mois[p[1] - 1]) \(p[0])"160    }161162    /// « 2026-11-18 » → « nov. 2026 », pour les tableaux étroits.163    static func dateCourte(_ iso: String?) -> String {164        guard let iso, !iso.isEmpty else { return vide }165        let p = iso.prefix(10).split(separator: "-").compactMap { Int($0) }166        guard p.count >= 2, (1...12).contains(p[1]) else { return iso }167        let abr = ["janv.", "févr.", "mars", "avr.", "mai", "juin", "juill.", "août", "sept.", "oct.", "nov.", "déc."]168        return "\(abr[p[1] - 1]) \(p[0])"169    }170171    static func distance(_ km: Double?) -> String {172        guard let km, km.isFinite else { return vide }173        return km < 1 ? "\(Int((km * 1000).rounded()))\(nb)m" : nombre(km, 1) + nb + "km"174    }175176    // MARK: adresses177178    private static let particules: Set<String> = ["De", "Du", "Des", "La", "Le", "Les", "D", "L", "Et", "Au", "Aux", "En", "Sur"]179    private static let voies: Set<String> = ["Rue", "Avenue", "Boulevard", "Chemin", "Place", "Rang", "Route", "Montée", "Côte", "Terrasse", "Impasse", "Croissant", "Allée", "Carré", "Cours", "Promenade", "Ruelle", "Voie"]180    private static let separateurs: Set<Character> = [" ", "-", "'", "’"]181    // même découpe que le site : numéro civique (éventuellement double), puis le reste182    private static let civique = try? NSRegularExpression(pattern: "^([\\d\\-–A-Za-z/ ]*?\\d[\\dA-Za-z\\-–/]*)\\s+(.*)$")183184    /// Casse de titre à la française : majuscule après une espace, un trait d'union ou une apostrophe,185    /// particules (de, du, la…) en minuscules lorsqu'elles sont suivies d'un autre mot.186    static func titre(_ s: String) -> String {187        var mots: [(mot: String, sep: Character?)] = []188        var courant = ""189        for c in s.lowercased() {190            if separateurs.contains(c) {191                mots.append((courant, c))192                courant = ""193            } else {194                courant.append(c)195            }196        }197        mots.append((courant, nil))198        var sortie = ""199        for (mot, sep) in mots {200            var m = mot201            if let premier = m.first, premier.isLetter {202                m = premier.uppercased() + m.dropFirst()203            }204            if sep != nil, particules.contains(m) { m = m.lowercased() }205            sortie += m206            if let sep { sortie.append(sep) }207        }208        return sortie209    }210211    /// « 2335-2339 Rue WELLINGTON » → « 2335-2339, rue Wellington ».212    static func adresse(_ brute: String?) -> String {213        guard let brute, !brute.trimmingCharacters(in: .whitespaces).isEmpty else { return "Adresse inconnue" }214        let b = brute.trimmingCharacters(in: .whitespaces)215        let ns = b as NSString216        guard let m = civique?.firstMatch(in: b, range: NSRange(location: 0, length: ns.length)), m.numberOfRanges == 3 else {217            return titre(b)218        }219        let numero = ns.substring(with: m.range(at: 1))220        var reste = titre(ns.substring(with: m.range(at: 2)))221        if let fin = reste.firstIndex(where: { !$0.isLetter }) ?? Optional(reste.endIndex) {222            let premier = String(reste[reste.startIndex..<fin])223            if voies.contains(premier) { reste = premier.lowercased() + reste[fin...] }224        }225        return "\(numero), \(reste)"226    }227228    // MARK: classes d'immeubles229230    static let classes: [(cle: String, nom: String)] = [231        ("duplex", "Duplex"), ("triplex", "Triplex"), ("quadruplex", "Quadruplex"), ("quintuplex", "Quintuplex"),232        ("6-11", "6 à 11 logements"), ("12-23", "12 à 23 logements"), ("24+", "24 logements et plus"),233    ]234    static let groupes = ["Duplex", "Triplex", "4 et 5 logements", "6 à 11 logements", "12 logements et plus"]235236    static func libelleClasse(_ classe: String?, _ logements: Int? = nil) -> String {237        if let logements, logements >= 6 { return "Immeuble de \(logements) logements" }238        guard let classe else { return "Immeuble à revenus" }239        return classes.first { $0.cle == classe }?.nom ?? classe240    }241242    static func groupe(_ indice: Int) -> String {243        groupes.indices.contains(indice) ? groupes[indice] : "Groupe \(indice)"244    }245246    static func logements(_ n: Int?) -> String {247        guard let n else { return vide }248        return "\(n)\(nb)logement\(n > 1 ? "s" : "")"249    }250251    /// Les avertissements du service écrivent les décimales à l'anglaise (« 1.06 ») : virgule décimale à l'affichage.252    static func virgules(_ s: String) -> String {253        s.replacingOccurrences(of: "(?<=\\d)\\.(?=\\d)", with: ",", options: .regularExpression)254    }255256    /// Saisie d'un nombre : accepte la virgule décimale et les espaces de milliers.257    static func lire(_ s: String) -> Double? {258        let net = s.replacingOccurrences(of: ",", with: ".").filter { $0.isNumber || $0 == "." }259        guard !net.isEmpty, let v = Double(net), v.isFinite, v >= 0 else { return nil }260        return v261    }262}263
Files main
Menu

Theme