SPB Git

Repository Public

Variables.swift 9.7 KB 191 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : MacLustr SMS Gateway9// File             : ios/MacLustrSMS/Core/Variables.swift10// Description      : Variables de modèles typées (texte, heure, date, montant,11//                    lien, marque…), formats du Québec, valeurs automatiques et12//                    mémorisées.13// Module           : ios14// Repository       : https://git.spboucher.ai/maclustr-sms15// Project Website  : https://sms.spboucher.ai16// Created          : 2026-12-0117// Last Modified    : 2026-12-0118//19// =============================================================================20// AUTHOR & PROFESSIONAL AFFILIATION21// =============================================================================22//23// Author           : Simon-Pierre Boucher24// Position         : Professor of Finance25// Institution      : Université du Québec en Outaouais (UQO)26// Department       : Département des sciences administratives27// Organization     : SP Boucher28//29// Website          : https://spboucher.ai30// Git              : https://git.spboucher.ai31//32// =============================================================================33// OFFICIAL CONTACT DIRECTORY34// =============================================================================35//36// General          : info@spboucher.ai37// Professional     : contact@spboucher.ai38// Direct           : simon@spboucher.ai39// Research         : research@spboucher.ai40// Development      : dev@spboucher.ai41// Support          : support@spboucher.ai42// Security/Admin   : admin@spboucher.ai43// Notifications    : notifications@spboucher.ai44//45// Preferred Contact: admin@spboucher.ai46//47// =============================================================================48// COPYRIGHT & INTELLECTUAL PROPERTY49// =============================================================================50//51// Copyright (c) 202652// Simon-Pierre Boucher53//54// All rights reserved where applicable.55//56// This file is governed by the applicable project license,57// copyright notices, institutional agreements and relevant law.58//59// Unless expressly authorized by the applicable license or60// rights holder, copying, redistribution, sublicensing,61// publication and commercial exploitation are not permitted.62//63// Existing third-party rights and notices remain unaffected.64//65// =============================================================================66// CONFIDENTIALITY & SECURITY67// =============================================================================68//69// Classification   : Public70// Distribution     : Public repository; use is governed by the project license71// Security Contact : admin@spboucher.ai72//73// Access to this source does not independently grant permission74// to redistribute or disclose confidential materials.75//76// Do not embed credentials, private keys, access tokens,77// certificates or confidential personal information.78//79// =============================================================================80// LICENSE & MAINTENANCE81// =============================================================================82//83// License          : None specified (no license file in this repository)84// Maintainer       : Simon-Pierre Boucher85// Technical Contact: dev@spboucher.ai86//87// =============================================================================88// END OF SP BOUCHER SOURCE HEADER89// =============================================================================9091import Foundation9293enum VariableKind: String, Sendable {94    case text, firstName, time, date, amount, link, brand, signature, code, number, address95    /// Le type se déduit du nom de la variable : aucune syntaxe à apprendre.96    static func of(_ name: String) -> VariableKind {97        let n = name.lowercased().folding(options: .diacriticInsensitive, locale: Locale(identifier: "fr_CA"))98        if n.hasPrefix("heure") || n == "time" { return .time }99        if ["date", "jour", "echeance", "aujourd'hui", "demain"].contains(n) || n.hasPrefix("date") { return .date }100        if ["montant", "prix", "solde", "total", "amount"].contains(n) { return .amount }101        if ["lien", "url", "link"].contains(n) { return .link }102        if ["marque", "entreprise", "brand"].contains(n) { return .brand }103        if n == "signature" { return .signature }104        if n == "code" { return .code }105        if ["minutes", "quantite", "nombre"].contains(n) { return .number }106        if ["prenom", "nom", "name"].contains(n) { return .firstName }107        if n == "adresse" { return .address }108        return .text109    }110    var symbol: String {111        switch self {112        case .time: "clock"; case .date: "calendar"; case .amount: "dollarsign.circle"; case .link: "link"; case .brand: "building.2"; case .signature: "signature"113        case .code: "number.square"; case .number: "number"; case .firstName: "person"; case .address: "mappin.and.ellipse"; case .text: "textformat"114        }115    }116    /// Variables dont la valeur se règle une fois (Réglages) et se réutilise partout.117    var isRemembered: Bool { self == .brand || self == .signature }118}119120enum VariableFormat {121    static let locale = Locale(identifier: "fr_CA")122    /// « 10 h », « 10 h 30 » — forme d'usage au Québec.123    static func time(_ d: Date, calendar: Calendar = .current) -> String {124        let c = calendar.dateComponents([.hour, .minute], from: d)125        let h = c.hour ?? 0, m = c.minute ?? 0126        return m == 0 ? "\(h) h" : "\(h) h \(String(format: "%02d", m))"127    }128    /// « jeudi 3 décembre » (« 1er » pour le premier du mois).129    static func date(_ d: Date, calendar: Calendar = .current) -> String {130        let f = DateFormatter(); f.locale = locale; f.calendar = calendar; f.timeZone = calendar.timeZone131        f.dateFormat = "EEEE"; let weekday = f.string(from: d)132        f.dateFormat = "MMMM"; let month = f.string(from: d)133        let day = calendar.component(.day, from: d)134        return "\(weekday) \(day == 1 ? "1er" : String(day)) \(month)"135    }136    /// « 125,50 $ », « 1 250 $ » : virgule décimale, espace ordinaire (l'espace insécable ferait passer le SMS en Unicode).137    static func amount(_ input: String) -> String {138        let cleaned = input.replacingOccurrences(of: "$", with: "").replacingOccurrences(of: " ", with: "").replacingOccurrences(of: "\u{00A0}", with: "").replacingOccurrences(of: ",", with: ".")139        guard let v = Double(cleaned), v >= 0 else { return input.trimmingCharacters(in: .whitespaces) }140        let whole = Int(v.rounded(.down)), cents = Int(((v - Double(whole)) * 100).rounded())141        var digits = String(whole), grouped = ""142        while digits.count > 3 { grouped = " " + digits.suffix(3) + grouped; digits = String(digits.dropLast(3)) }143        return digits + grouped + (cents == 0 ? "" : "," + String(format: "%02d", cents)) + " $"144    }145    /// Lien raccourci à l'essentiel : sans « https:// » ni barre finale (moins de caractères, même destination).146    static func link(_ input: String) -> String {147        var s = input.trimmingCharacters(in: .whitespacesAndNewlines)148        for p in ["https://", "http://"] where s.lowercased().hasPrefix(p) { s = String(s.dropFirst(p.count)) }149        if s.hasSuffix("/") { s.removeLast() }150        return s151    }152    static func normalized(_ kind: VariableKind, _ value: String) -> String {153        switch kind { case .amount: amount(value); case .link: link(value); default: value }154    }155    /// Valeurs calculées, jamais demandées à l'utilisateur.156    static func automatic(_ name: String, now: Date = .now, calendar: Calendar = .current) -> String? {157        switch name.lowercased() {158        case "aujourd'hui", "aujourd’hui": date(now, calendar: calendar)159        case "demain": date(calendar.date(byAdding: .day, value: 1, to: now) ?? now, calendar: calendar)160        default: nil161        }162    }163}164165/// Valeurs mémorisées par nom de variable (marque, signature…), gardées sur l'appareil.166enum RememberedValues {167    private static let key = "rememberedVariables"168    static func all(_ defaults: UserDefaults = .standard) -> [String: String] { (defaults.dictionary(forKey: key) as? [String: String]) ?? [:] }169    static func value(for name: String, _ defaults: UserDefaults = .standard) -> String? { let v = all(defaults)[name.lowercased()]; return (v?.isEmpty ?? true) ? nil : v }170    static func set(_ value: String, for name: String, _ defaults: UserDefaults = .standard) {171        var d = all(defaults); let v = value.trimmingCharacters(in: .whitespaces)172        if v.isEmpty { d[name.lowercased()] = nil } else { d[name.lowercased()] = v }173        defaults.set(d, forKey: key)174    }175    /// Noms proposés d'office dans Réglages.176    static let standard = ["marque", "signature"]177}178179extension TemplateEngine {180    /// Valeurs connues d'avance pour un modèle : automatiques (dates), puis mémorisées (marque, signature), puis le prénom du destinataire.181    static func prefill(_ body: String, recipientName: String = "", now: Date = .now, defaults: UserDefaults = .standard) -> [String: String] {182        var out: [String: String] = [:]183        for v in variables(in: body) {184            if let a = VariableFormat.automatic(v, now: now) { out[v] = a }185            else if let r = RememberedValues.value(for: v, defaults) { out[v] = r }186            else if VariableKind.of(v) == .firstName, v.lowercased().hasPrefix("pr"), let first = recipientName.split(separator: " ").first { out[v] = String(first) }187        }188        return out189    }190}191
Files main
Menu

Theme