Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : Lou-Ka iOS9// File : LouKa/Core/Account/PhoneNumber.swift10// Description : comptes par numéro de cellulaire (3.1.1) — normalisation11// et mise en forme d'un numéro du Canada ou des États-Unis,12// identifiant d'un compte (courriel ou cellulaire), options13// du serveur. Le serveur fait foi : la normalisation locale14// évite un aller-retour pour une faute évidente.15// Module : LouKa16// Repository : https://git.spboucher.ai/lou-ka-ios-v317// Project Website : https://www.lou-ka.com18// Created : 2026-11-3019// Last Modified : 2026-11-3020//21// =============================================================================22// AUTHOR & PROFESSIONAL AFFILIATION23// =============================================================================24//25// Author : Simon-Pierre Boucher26// Position : Professor of Finance27// Institution : Université du Québec en Outaouais (UQO)28// Department : Département des sciences administratives29// Organization : SP Boucher30//31// Website : https://spboucher.ai32// Git : https://git.spboucher.ai33//34// =============================================================================35// OFFICIAL CONTACT DIRECTORY36// =============================================================================37//38// General : info@spboucher.ai39// Professional : contact@spboucher.ai40// Direct : simon@spboucher.ai41// Research : research@spboucher.ai42// Development : dev@spboucher.ai43// Support : support@spboucher.ai44// Security/Admin : admin@spboucher.ai45// Notifications : notifications@spboucher.ai46//47// Preferred Contact: support@spboucher.ai48//49// =============================================================================50// COPYRIGHT & INTELLECTUAL PROPERTY51// =============================================================================52//53// Copyright (c) 202654// Simon-Pierre Boucher55//56// All rights reserved where applicable.57//58// This file is governed by the applicable project license,59// copyright notices, institutional agreements and relevant law.60//61// Unless expressly authorized by the applicable license or62// rights holder, copying, redistribution, sublicensing,63// publication and commercial exploitation are not permitted.64//65// Existing third-party rights and notices remain unaffected.66//67// =============================================================================68// CONFIDENTIALITY & SECURITY69// =============================================================================70//71// Classification : Public72// Distribution : Public repository; use is governed by the project license73// Security Contact : admin@spboucher.ai74//75// Access to this source does not independently grant permission76// to redistribute or disclose confidential materials.77//78// Do not embed credentials, private keys, access tokens,79// certificates or confidential personal information.80//81// =============================================================================82// LICENSE & MAINTENANCE83// =============================================================================84//85// License : None specified (no license file in this repository)86// Maintainer : Simon-Pierre Boucher87// Technical Contact: dev@spboucher.ai88//89// =============================================================================90// END OF SP BOUCHER SOURCE HEADER91// =============================================================================9293import Foundation9495/// Numéro du plan nord-américain (`+1`, dix chiffres).96enum PhoneNumber {97 /// Indicatifs sans frais et surtaxés, refusés par le serveur.98 static let refusedAreaCodes: Set<String> = ["800", "822", "833", "844", "855", "866", "877", "888", "900"]99100 /// Les dix chiffres nationaux d'une saisie (« 418 555-0123 », « (418) 555-0123 », « +1 418 555 0123 »), ou nil.101 static func nationalDigits(_ input: String) -> String? {102 let trimmed = input.trimmingCharacters(in: .whitespacesAndNewlines)103 // seuls chiffres, espaces et ponctuation usuelle ; un « + » seulement en tête104 guard !trimmed.isEmpty, trimmed.allSatisfy({ $0.isNumber || " -.()+".contains($0) }),105 !trimmed.dropFirst().contains("+") else { return nil }106 var digits = trimmed.filter(\.isASCII).filter(\.isNumber)107 if trimmed.hasPrefix("+") {108 guard digits.hasPrefix("1") else { return nil } // autre pays109 digits.removeFirst()110 } else if digits.count == 11, digits.hasPrefix("1") {111 digits.removeFirst()112 }113 guard digits.count == 10 else { return nil }114 let area = String(digits.prefix(3)), exchange = digits.dropFirst(3).prefix(3)115 // indicatif régional et central : premier chiffre de 2 à 9116 guard let a = area.first, let e = exchange.first, a != "0", a != "1", e != "0", e != "1" else { return nil }117 guard !refusedAreaCodes.contains(area) else { return nil }118 return digits119 }120121 /// Forme envoyée au serveur : `+14185550123`, ou nil si la saisie n'est pas un numéro du Canada ou des États-Unis.122 static func normalize(_ input: String) -> String? { nationalDigits(input).map { "+1" + $0 } }123124 static func looksValid(_ input: String) -> Bool { normalize(input) != nil }125126 /// « 418 555-0123 » à partir de n'importe quelle écriture valide ; la saisie telle quelle sinon.127 static func display(_ input: String?) -> String {128 guard let input, !input.isEmpty else { return "" }129 guard let d = nationalDigits(input) else { return input }130 return "\(d.prefix(3)) \(d.dropFirst(3).prefix(3))-\(d.suffix(4))"131 }132133 /// Mise en forme douce pendant la frappe : « 4185 » → « 418 5 », « 4185550 » → « 418 555-0 ». Un « +1 » ou134 /// un « 1 » de tête est gardé ; rien n'est inventé ni retiré au-delà de dix chiffres.135 static func formatTyping(_ input: String) -> String {136 let plus = input.trimmingCharacters(in: .whitespaces).hasPrefix("+")137 var digits = input.filter(\.isASCII).filter(\.isNumber)138 var prefix = ""139 if plus {140 guard digits.hasPrefix("1") else { return "+" + digits } // autre pays : laissé tel quel, le serveur le dira141 prefix = "+1 "; digits.removeFirst()142 } else if digits.hasPrefix("1") {143 prefix = "1 "; digits.removeFirst()144 }145 digits = String(digits.prefix(10))146 var out = String(digits.prefix(3))147 if digits.count > 3 { out += " " + digits.dropFirst(3).prefix(3) }148 if digits.count > 6 { out += "-" + digits.dropFirst(6) }149 return (prefix + out).trimmingCharacters(in: .whitespaces)150 }151}152153/// Avec quoi un compte s'identifie : une adresse courriel ou un numéro de cellulaire.154enum AccountIdentifier: Hashable, Sendable {155 case email(String)156 case phone(String)157158 enum Mode: String, Sendable, CaseIterable { case email, phone }159160 var mode: Mode { if case .phone = self { return .phone }; return .email }161162 /// Valeur envoyée au serveur : courriel nettoyé, ou numéro normalisé (la saisie telle quelle s'il ne se163 /// normalise pas : le serveur répondra `telephone_invalide`).164 var value: String {165 switch self {166 case .email(let e): e.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()167 case .phone(let p): PhoneNumber.normalize(p) ?? p.trimmingCharacters(in: .whitespacesAndNewlines)168 }169 }170171 /// Ce qu'on montre à l'utilisateur : le courriel, ou « 418 555-0123 ».172 var display: String {173 switch self {174 case .email: value175 case .phone(let p): PhoneNumber.display(p)176 }177 }178179 /// Plausible avant l'envoi ?180 var looksValid: Bool {181 switch self {182 case .email(let e): Account.emailLooksValid(e)183 case .phone(let p): PhoneNumber.looksValid(p)184 }185 }186187 /// Champ fautif nommé par le serveur (`error.param`).188 var param: String { mode == .phone ? "phone" : "email" }189}190191/// `GET /api/v3/compte/options` : ce que le serveur offre à l'inscription.192struct AccountOptions: Decodable, Sendable, Equatable {193 var emailSignup: Bool194 var phoneSignup: Bool195 var phoneCountries: [String]196 var codeLength: Int197198 /// Tant que le serveur n'a pas répondu (ou s'il ne répond pas) : le courriel seulement.199 static let fallback = AccountOptions(emailSignup: true, phoneSignup: false, phoneCountries: [], codeLength: 6)200201 init(emailSignup: Bool, phoneSignup: Bool, phoneCountries: [String], codeLength: Int) {202 self.emailSignup = emailSignup; self.phoneSignup = phoneSignup; self.phoneCountries = phoneCountries; self.codeLength = codeLength203 }204205 enum CodingKeys: String, CodingKey { case emailSignup = "email_signup", phoneSignup = "phone_signup", phoneCountries = "phone_countries", codeLength = "code_length" }206207 init(from decoder: Decoder) throws {208 let c = try decoder.container(keyedBy: CodingKeys.self)209 emailSignup = ((try? c.decodeIfPresent(Bool.self, forKey: .emailSignup)) ?? nil) ?? true210 // absent ou illisible : le téléphone n'est pas offert211 phoneSignup = ((try? c.decodeIfPresent(Bool.self, forKey: .phoneSignup)) ?? nil) ?? false212 phoneCountries = ((try? c.decodeIfPresent([String].self, forKey: .phoneCountries)) ?? nil) ?? []213 codeLength = ((try? c.decodeIfPresent(Int.self, forKey: .codeLength)) ?? nil) ?? 6214 }215}216