SPB Git

Repository Public

AccountModels.swift 15.9 KB 369 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : Lou-Ka iOS9// File             : LouKa/Core/Account/AccountModels.swift10// Description      : formes de l'API de compte (`/api/v3/compte`, voir11//                    docs/COMPTES-API.md) — utilisateur, session, appareils,12//                    favoris et recherches synchronisés. Décodage tolérant : un13//                    champ inconnu est ignoré, un champ facultatif absent reste14//                    absent.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/// Utilisateur d'un compte Lou-Ka. Les champs inconnus du serveur sont ignorés ; `role` est prévu pour la96/// suite (« locataire », « gestionnaire ») et reste facultatif.97struct AccountUser: Codable, Sendable, Equatable {98    var id: String99    /// nil pour un compte ouvert avec un numéro de cellulaire100    var email: String?101    /// `+14185550123` pour un compte ouvert avec un numéro de cellulaire102    var phone: String?103    var name: String104    var verified: Bool105    /// secondes depuis 1970106    var createdAt: Double?107    var role: String?108    /// accès de gestionnaire (`role == "gestionnaire"`)109    var manager: ManagerAccess?110111    enum CodingKeys: String, CodingKey { case id, email, phone, name, verified, role, manager; case createdAt = "created_at" }112113    init(id: String, email: String? = nil, phone: String? = nil, name: String = "", verified: Bool = true, createdAt: Double? = nil, role: String? = nil, manager: ManagerAccess? = nil) {114        self.id = id; self.email = email; self.phone = phone; self.name = name; self.verified = verified; self.createdAt = createdAt; self.role = role; self.manager = manager115    }116117    /// Compte ouvert avec un numéro de cellulaire, sans adresse courriel : il ne reçoit aucun courriel.118    var isPhoneAccount: Bool { (email ?? "").isEmpty && !(phone ?? "").isEmpty }119    /// Ce qui identifie le compte à l'écran : le courriel, sinon le numéro mis en forme (« 418 555-0123 »), sinon rien.120    var contact: String {121        if let e = email, !e.isEmpty { return e }122        return PhoneNumber.display(phone)123    }124125    /// Compte de gestionnaire (entreprise) plutôt que de chercheur de logement.126    var isManager: Bool { role == "gestionnaire" }127    /// Peut utiliser la messagerie : chercheur à l'adresse confirmée, ou gestionnaire à l'accès approuvé.128    var canUseMessaging: Bool { isManager ? manager?.state == .approved : verified }129    /// Seul un chercheur ouvre une conversation.130    var canStartConversation: Bool { !isManager }131132    init(from decoder: Decoder) throws {133        let c = try decoder.container(keyedBy: CodingKeys.self)134        id = try c.decode(String.self, forKey: .id)135        // `email` vaut null pour un compte par téléphone ; une chaîne vide est traitée comme absente136        email = ((try? c.decodeIfPresent(String.self, forKey: .email)) ?? nil).flatMap { $0.isEmpty ? nil : $0 }137        phone = ((try? c.decodeIfPresent(String.self, forKey: .phone)) ?? nil).flatMap { $0.isEmpty ? nil : $0 }138        name = (try? c.decodeIfPresent(String.self, forKey: .name)) ?? ""139        verified = (try? c.decodeIfPresent(Bool.self, forKey: .verified)) ?? true140        createdAt = try? c.decodeIfPresent(Double.self, forKey: .createdAt)141        role = try? c.decodeIfPresent(String.self, forKey: .role)142        manager = (try? c.decodeIfPresent(ManagerAccess.self, forKey: .manager)) ?? nil143    }144145    /// Nom à afficher : le nom s'il y en a un, sinon le courriel.146    var displayName: String { name.trimmingCharacters(in: .whitespaces).isEmpty ? (contact.isEmpty ? "Mon compte" : contact) : name }147}148149/// Réponse « session » (inscription vérifiée, connexion, réinitialisation). `token` n'est rendu qu'aux applications.150struct AccountSession: Decodable, Sendable {151    struct Info: Decodable, Sendable {152        var token: String?153        var expiresAt: Double?154        var client: String?155        enum CodingKeys: String, CodingKey { case token, client; case expiresAt = "expires_at" }156    }157    var user: AccountUser158    var session: Info?159}160161struct AccountUserEnvelope: Decodable, Sendable { var user: AccountUser }162163/// `202` de l'inscription, du renvoi et de l'oubli de mot de passe : rien à lire d'obligatoire.164struct AccountAccepted: Decodable, Sendable {165    var status: String?166    var email: String?167    /// `sms` pour un code envoyé par texto168    var channel: String?169    var phone: String?170    /// « 418 555-0123 »171    var phoneDisplay: String?172    var codeLength: Int?173    var expiresInMin: Int?174    enum CodingKeys: String, CodingKey { case status, email, channel, phone; case phoneDisplay = "phone_display"; case codeLength = "code_length"; case expiresInMin = "expires_in_min" }175}176177/// Un appareil connecté au compte.178struct DeviceSession: Decodable, Sendable, Identifiable, Equatable {179    var id: String180    var client: String?181    var agent: String?182    var createdAt: Double?183    var seenAt: Double?184    var current: Bool185186    enum CodingKeys: String, CodingKey { case id, client, agent, current; case createdAt = "created_at"; case seenAt = "seen_at" }187188    init(from decoder: Decoder) throws {189        let c = try decoder.container(keyedBy: CodingKeys.self)190        id = try c.decode(String.self, forKey: .id)191        client = try? c.decodeIfPresent(String.self, forKey: .client)192        agent = try? c.decodeIfPresent(String.self, forKey: .agent)193        createdAt = try? c.decodeIfPresent(Double.self, forKey: .createdAt)194        seenAt = try? c.decodeIfPresent(Double.self, forKey: .seenAt)195        current = (try? c.decodeIfPresent(Bool.self, forKey: .current)) ?? false196    }197198    /// « iPhone ou iPad », « Site web », « Android ».199    var clientLabel: String {200        switch client {201        case "ios": "iPhone ou iPad"202        case "android": "Android"203        case "web": "Site web"204        default: "Appareil"205        }206    }207}208209struct DeviceSessionList: Decodable, Sendable { var items: [DeviceSession] }210struct RevokedCount: Decodable, Sendable { var revoked: Int? }211212// MARK: - Favoris213214/// Aperçu gardé avec un favori (objet plat, 4 Ko au plus) : champs partagés par le site et les applications.215struct FavoriteSnapshot: Codable, Sendable, Equatable {216    var title: String?217    var address: String?218    var city: String?219    var sector: String?220    var unitType: String?221    var price: Double?222    var image: String?223    var source: String?224    var areaSqft: Double?225    var lat: Double?226    var lng: Double?227228    enum CodingKeys: String, CodingKey {229        case title, address, city, sector, price, image, source, lat, lng230        case unitType = "unit_type"; case areaSqft = "area_sqft"231    }232233    init(title: String? = nil, address: String? = nil, city: String? = nil, sector: String? = nil, unitType: String? = nil,234         price: Double? = nil, image: String? = nil, source: String? = nil, areaSqft: Double? = nil, lat: Double? = nil, lng: Double? = nil) {235        self.title = title; self.address = address; self.city = city; self.sector = sector; self.unitType = unitType236        self.price = price; self.image = image; self.source = source; self.areaSqft = areaSqft; self.lat = lat; self.lng = lng237    }238239    /// Tolérant : un autre client peut écrire un prix en chaîne ou omettre n'importe quel champ.240    init(from decoder: Decoder) throws {241        guard let c = try? decoder.container(keyedBy: CodingKeys.self) else { return }242        func text(_ k: CodingKeys) -> String? {243            if let s = try? c.decodeIfPresent(String.self, forKey: k) { return s.isEmpty ? nil : s }244            return nil245        }246        func number(_ k: CodingKeys) -> Double? {247            if let d = try? c.decodeIfPresent(Double.self, forKey: k) { return d }248            if let s = try? c.decodeIfPresent(String.self, forKey: k) { return Double(s) }249            return nil250        }251        title = text(.title); address = text(.address); city = text(.city); sector = text(.sector)252        unitType = text(.unitType); image = text(.image); source = text(.source)253        price = number(.price); areaSqft = number(.areaSqft); lat = number(.lat); lng = number(.lng)254    }255256    var isEmpty: Bool { self == FavoriteSnapshot() }257}258259/// Favori tel que le serveur le garde. Dates en millisecondes depuis 1970.260struct RemoteFavorite: Codable, Sendable, Equatable {261    var uid: String262    var savedAt: Int64263    var note: String?264    var snapshot: FavoriteSnapshot?265    var updatedAt: Int64?266267    enum CodingKeys: String, CodingKey { case uid, note, snapshot; case savedAt = "saved_at"; case updatedAt = "updated_at" }268269    init(uid: String, savedAt: Int64, note: String? = nil, snapshot: FavoriteSnapshot? = nil, updatedAt: Int64? = nil) {270        self.uid = uid; self.savedAt = savedAt; self.note = note; self.snapshot = snapshot; self.updatedAt = updatedAt271    }272273    init(from decoder: Decoder) throws {274        let c = try decoder.container(keyedBy: CodingKeys.self)275        uid = try c.decode(String.self, forKey: .uid)276        savedAt = Ms.decode(c, .savedAt) ?? 0277        note = try? c.decodeIfPresent(String.self, forKey: .note)278        snapshot = try? c.decodeIfPresent(FavoriteSnapshot.self, forKey: .snapshot)279        updatedAt = Ms.decode(c, .updatedAt)280    }281}282283/// Élément retiré hors ligne, à rejouer : `uid` (favori) ou `id` (recherche) et moment du retrait.284struct RemovedFavorite: Codable, Sendable, Equatable { var uid: String; var at: Int64 }285struct RemovedSearch: Codable, Sendable, Equatable { var id: String; var at: Int64 }286287struct FavoriteSyncRequest: Encodable, Sendable {288    var items: [RemoteFavorite]289    var removed: [RemovedFavorite]290}291292struct FavoriteList: Decodable, Sendable {293    var items: [RemoteFavorite]294    var limit: Int?295    var serverTime: Int64?296    var skipped: Int?297    enum CodingKeys: String, CodingKey { case items, limit, skipped; case serverTime = "server_time" }298    init(from decoder: Decoder) throws {299        let c = try decoder.container(keyedBy: CodingKeys.self)300        items = try c.decode([RemoteFavorite].self, forKey: .items)301        limit = try? c.decodeIfPresent(Int.self, forKey: .limit)302        serverTime = Ms.decode(c, .serverTime)303        skipped = try? c.decodeIfPresent(Int.self, forKey: .skipped)304    }305}306307// MARK: - Recherches enregistrées308309/// Recherche enregistrée telle que le serveur la garde. `query` : chaîne de requête de la recherche.310struct RemoteSearch: Codable, Sendable, Equatable {311    var id: String312    var label: String313    var query: String314    var origin: String315    var savedAt: Int64316    var lastTotal: Int?317    var lastVisit: Int64?318    var updatedAt: Int64?319320    enum CodingKeys: String, CodingKey {321        case id, label, query, origin322        case savedAt = "saved_at"; case lastTotal = "last_total"; case lastVisit = "last_visit"; case updatedAt = "updated_at"323    }324325    init(id: String, label: String, query: String, origin: String = "ios", savedAt: Int64, lastTotal: Int? = nil, lastVisit: Int64? = nil, updatedAt: Int64? = nil) {326        self.id = id; self.label = label; self.query = query; self.origin = origin; self.savedAt = savedAt327        self.lastTotal = lastTotal; self.lastVisit = lastVisit; self.updatedAt = updatedAt328    }329330    init(from decoder: Decoder) throws {331        let c = try decoder.container(keyedBy: CodingKeys.self)332        id = try c.decode(String.self, forKey: .id)333        label = (try? c.decodeIfPresent(String.self, forKey: .label)) ?? ""334        query = (try? c.decodeIfPresent(String.self, forKey: .query)) ?? ""335        origin = (try? c.decodeIfPresent(String.self, forKey: .origin)) ?? "web"336        savedAt = Ms.decode(c, .savedAt) ?? 0337        lastTotal = try? c.decodeIfPresent(Int.self, forKey: .lastTotal)338        lastVisit = Ms.decode(c, .lastVisit)339        updatedAt = Ms.decode(c, .updatedAt)340    }341}342343struct SearchSyncRequest: Encodable, Sendable {344    var items: [RemoteSearch]345    var removed: [RemovedSearch]346}347348struct SearchList: Decodable, Sendable {349    var items: [RemoteSearch]350    var limit: Int?351    var skipped: Int?352}353354// MARK: - Dates355356/// Millisecondes depuis 1970 (dates des éléments synchronisés).357enum Ms {358    static func from(_ date: Date) -> Int64 { Int64((date.timeIntervalSince1970 * 1000).rounded()) }359    static func date(_ ms: Int64) -> Date { Date(timeIntervalSince1970: Double(ms) / 1000) }360    static var now: Int64 { from(Date()) }361362    /// Entier ou nombre à virgule : un autre client peut avoir écrit `1796000000000.0`.363    static func decode<K: CodingKey>(_ c: KeyedDecodingContainer<K>, _ key: K) -> Int64? {364        if let i = try? c.decodeIfPresent(Int64.self, forKey: key) { return i }365        if let d = try? c.decodeIfPresent(Double.self, forKey: key) { return Int64(d.rounded()) }366        return nil367    }368}369
Files main
Menu

Theme