SPB Git

Repository Public

Templates.swift 10.4 KB 207 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/Templates.swift10// Description      : Modèles de messages à variables {{nom}}, signature,11//                    destinataires récents (SwiftData, stockage local12//                    seulement).13// Module           : ios14// Repository       : https://git.spboucher.ai/maclustr-sms15// Project Website  : https://sms.spboucher.ai16// Created          : 2026-11-3017// 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 Foundation92import SwiftData9394enum TemplateEngine {95    /// Variables d'un modèle, dans l'ordre de première apparition, sans doublon. Syntaxe : {{ nom }} (lettres, chiffres, espaces, tirets).96    static func variables(in body: String) -> [String] {97        var seen = Set<String>(), out: [String] = []98        for m in body.matches(of: /\{\{\s*([\p{L}\p{N} _\-]{1,40}?)\s*\}\}/) {99            let name = String(m.1)100            if seen.insert(name.lowercased()).inserted { out.append(name) }101        }102        return out103    }104    /// Remplace chaque variable par sa valeur ; une variable sans valeur est laissée visible pour ne jamais partir en silence.105    static func fill(_ body: String, values: [String: String]) -> String {106        let lower = Dictionary(values.map { ($0.key.lowercased(), $0.value) }, uniquingKeysWith: { a, _ in a })107        return body.replacing(/\{\{\s*([\p{L}\p{N} _\-]{1,40}?)\s*\}\}/) { m in108            let v = lower[String(m.1).lowercased()]?.trimmingCharacters(in: .whitespaces) ?? ""109            return v.isEmpty ? String(m.0) : v110        }111    }112    static func unresolved(in text: String) -> [String] { variables(in: text) }113    static func withSignature(_ text: String, signature: String) -> String {114        let s = signature.trimmingCharacters(in: .whitespacesAndNewlines)115        guard !s.isEmpty, !text.hasSuffix(s) else { return text }116        return text.trimmingCharacters(in: .whitespacesAndNewlines) + "\n" + s117    }118}119120@Model final class MessageTemplate {121    var id: UUID = UUID()122    var name: String = ""123    var body: String = ""124    var symbol: String = "text.bubble"125    var order: Int = 0126    var uses: Int = 0127    var createdAt: Date = Date.now128    // Ajouts du build 2 : tous ont une valeur par défaut, la migration SwiftData est donc automatique (les modèles du build 1 sont conservés).129    var category: String = "Mes modèles"130    var bodyEN: String = ""131    var favorite: Bool = false132    var lastUsed: Date? = nil133    /// Clé du modèle de départ dont celui-ci provient ; nil pour un modèle créé par l'utilisateur.134    var starterKey: String? = nil135    init(name: String, body: String, symbol: String = "text.bubble", order: Int = 0, category: String = TemplateCategory.mine, bodyEN: String = "", starterKey: String? = nil) {136        self.name = name; self.body = body; self.symbol = symbol; self.order = order; self.category = category; self.bodyEN = bodyEN; self.starterKey = starterKey137    }138    var hasEnglish: Bool { !bodyEN.trimmingCharacters(in: .whitespaces).isEmpty }139    func text(english: Bool) -> String { english && hasEnglish ? bodyEN : body }140}141142enum TemplateSeeder {143    /// Met la bibliothèque de départ à jour sans jamais toucher aux modèles de l'utilisateur :144    ///  - les modèles de départ absents (par clé) sont ajoutés ; ceux déjà présents ne sont pas réécrits (l'utilisateur a pu les modifier) ;145    ///  - les cinq modèles du build 1 restés intacts sont retirés (remplacés par la nouvelle bibliothèque) ; modifiés, ils sont gardés dans « Mes modèles ».146    @MainActor @discardableResult147    static func sync(_ ctx: ModelContext) -> (added: Int, removedLegacy: Int) {148        let existing = (try? ctx.fetch(FetchDescriptor<MessageTemplate>())) ?? []149        var removed = 0150        for t in existing where t.starterKey == nil && StarterTemplates.legacyBodies.contains(t.body) && t.uses == 0 { ctx.delete(t); removed += 1 }151        let keys = Set(existing.compactMap(\.starterKey))152        var added = 0153        for (i, s) in StarterTemplates.all.enumerated() where !keys.contains(s.key) {154            ctx.insert(MessageTemplate(name: s.name, body: s.fr, symbol: s.symbol, order: i, category: s.category, bodyEN: s.en, starterKey: s.key)); added += 1155        }156        try? ctx.save()157        return (added, removed)158    }159}160161/// Sauvegarde et restauration des modèles (fichier JSON, feuille de partage).162struct TemplateArchive: Codable, Equatable {163    struct Item: Codable, Equatable { var name: String; var body: String; var bodyEN: String?; var category: String?; var symbol: String?; var favorite: Bool?; var starterKey: String? }164    var format = "maclustr-sms-templates"165    var version = 1166    var exportedAt = Date.now167    var templates: [Item]168169    @MainActor static func export(_ templates: [MessageTemplate]) throws -> Data {170        let a = TemplateArchive(templates: templates.sorted { ($0.category, $0.order) < ($1.category, $1.order) }.map {171            Item(name: $0.name, body: $0.body, bodyEN: $0.bodyEN.isEmpty ? nil : $0.bodyEN, category: $0.category, symbol: $0.symbol, favorite: $0.favorite ? true : nil, starterKey: $0.starterKey) })172        let e = JSONEncoder(); e.outputFormatting = [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes]; e.dateEncodingStrategy = .iso8601173        return try e.encode(a)174    }175    static func decode(_ data: Data) throws -> TemplateArchive {176        let d = JSONDecoder(); d.dateDecodingStrategy = .iso8601177        let a = try d.decode(TemplateArchive.self, from: data)178        guard a.format == "maclustr-sms-templates" else { throw CocoaError(.fileReadCorruptFile) }179        return a180    }181    /// Importe sans doublon : un modèle déjà présent (même clé de départ, ou même nom et même texte) est ignoré.182    @MainActor @discardableResult static func importInto(_ ctx: ModelContext, data: Data) throws -> (added: Int, skipped: Int) {183        let a = try decode(data)184        let existing = (try? ctx.fetch(FetchDescriptor<MessageTemplate>())) ?? []185        var seen = Set(existing.map { $0.name + "\u{1F}" + $0.body }), keys = Set(existing.compactMap(\.starterKey))186        var order = (existing.map(\.order).max() ?? -1) + 1, added = 0, skipped = 0187        for i in a.templates.prefix(500) {188            let name = String(i.name.prefix(80)), body = String(i.body.prefix(1600))189            if name.trimmingCharacters(in: .whitespaces).isEmpty || body.trimmingCharacters(in: .whitespaces).isEmpty || seen.contains(name + "\u{1F}" + body) || (i.starterKey.map(keys.contains) ?? false) { skipped += 1; continue }190            let t = MessageTemplate(name: name, body: body, symbol: i.symbol ?? "text.bubble", order: order, category: i.category ?? TemplateCategory.mine, bodyEN: i.bodyEN ?? "", starterKey: i.starterKey)191            t.favorite = i.favorite ?? false192            ctx.insert(t); seen.insert(name + "\u{1F}" + body); if let k = i.starterKey { keys.insert(k) }193            order += 1; added += 1194        }195        try? ctx.save()196        return (added, skipped)197    }198}199200@Model final class RecentRecipient {201    @Attribute(.unique) var number: String = ""202    var name: String = ""203    var lastUsed: Date = Date.now204    var uses: Int = 0205    init(number: String, name: String = "") { self.number = number; self.name = name }206}207
Files main
Menu

Theme