SPB Git

Repository Public

AdminModels.swift 28.2 KB 710 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : Lou-Ka Admin iOS9// File             : LouKaAdmin/Core/AdminModels.swift10// Description      : formes de l'API d'administration (`/api/v3/admin`, contrat11//                    dans docs/API.md). Décodage tolérant : un champ inconnu12//                    est ignoré, un champ facultatif absent reste absent. Tout13//                    texte de ces formes venu d'un tiers (demandeur,14//                    gestionnaire, chercheur, correspondant) est du texte brut.15// Module           : LouKaAdmin16// Repository       : https://git.spboucher.ai/lou-ka-admin-ios17// 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 Foundation9495struct AnyKey: CodingKey {96    var stringValue: String97    var intValue: Int? { nil }98    init(_ s: String) { stringValue = s }99    init?(stringValue: String) { self.stringValue = stringValue }100    init?(intValue: Int) { nil }101}102103extension KeyedDecodingContainer where K == AnyKey {104    func text(_ k: String) -> String? {105        guard let s = (try? decodeIfPresent(String.self, forKey: AnyKey(k))) ?? nil else { return nil }106        let t = s.trimmingCharacters(in: .whitespacesAndNewlines)107        return t.isEmpty ? nil : t108    }109    /// Chaîne gardée telle quelle (corps d'un message), ou nil.110    func raw(_ k: String) -> String? { (try? decodeIfPresent(String.self, forKey: AnyKey(k))) ?? nil }111    func flag(_ k: String) -> Bool { ((try? decodeIfPresent(Bool.self, forKey: AnyKey(k))) ?? nil) ?? false }112    func int(_ k: String) -> Int? {113        if let i = (try? decodeIfPresent(Int.self, forKey: AnyKey(k))) ?? nil { return i }114        if let d = (try? decodeIfPresent(Double.self, forKey: AnyKey(k))) ?? nil { return Int(d) }115        return nil116    }117    func double(_ k: String) -> Double? { (try? decodeIfPresent(Double.self, forKey: AnyKey(k))) ?? nil }118    func value<T: Decodable>(_ k: String, _: T.Type = T.self) -> T? { (try? decodeIfPresent(T.self, forKey: AnyKey(k))) ?? nil }119    /// Tableau dont chaque élément illisible est ignoré.120    func list<T: Decodable>(_ k: String, of: T.Type = T.self) -> [T] {121        ((try? decodeIfPresent([Lossy<T>].self, forKey: AnyKey(k))) ?? nil)?.compactMap(\.value) ?? []122    }123}124125struct Lossy<T: Decodable>: Decodable {126    var value: T?127    init(from decoder: Decoder) throws { value = try? T(from: decoder) }128}129130struct ItemList<T: Decodable & Sendable>: Decodable, Sendable {131    var items: [T]132    init(from decoder: Decoder) throws { items = try decoder.container(keyedBy: AnyKey.self).list("items") }133}134135// MARK: - Session et compte136137struct Admin: Decodable, Sendable, Equatable, Identifiable {138    var id: String139    var name: String140    var email: String141    var mailboxes: [String]142    init(id: String, name: String, email: String = "", mailboxes: [String] = []) { self.id = id; self.name = name; self.email = email; self.mailboxes = mailboxes }143    init(from decoder: Decoder) throws {144        let c = try decoder.container(keyedBy: AnyKey.self)145        id = c.text("id") ?? ""146        name = c.text("name") ?? ""147        email = c.text("email") ?? ""148        mailboxes = c.list("mailboxes", of: String.self)149    }150}151152struct AdminStats: Decodable, Sendable, Equatable {153    var comptes = 0, verifies = 0, sessions = 0, favoris = 0, recherches = 0154    var gestionnairesEnAttente = 0, gestionnairesApprouves = 0, signalementsOuverts = 0155    init() {}156    init(from decoder: Decoder) throws {157        let c = try decoder.container(keyedBy: AnyKey.self)158        comptes = c.int("comptes") ?? 0; verifies = c.int("verifies") ?? 0; sessions = c.int("sessions") ?? 0159        favoris = c.int("favoris") ?? 0; recherches = c.int("recherches") ?? 0160        gestionnairesEnAttente = c.int("gestionnaires_en_attente") ?? 0161        gestionnairesApprouves = c.int("gestionnaires_approuves") ?? 0162        signalementsOuverts = c.int("signalements_ouverts") ?? 0163    }164}165166struct AccessKey: Decodable, Sendable, Equatable, Identifiable {167    var id: String168    var name: String169    var createdAt: Double?170    var usedAt: Double?171    init(from decoder: Decoder) throws {172        let c = try decoder.container(keyedBy: AnyKey.self)173        id = try c.decode(String.self, forKey: AnyKey("id"))174        name = c.text("name") ?? "Clé d'accès"175        createdAt = c.double("created_at"); usedAt = c.double("used_at")176    }177}178179/// `GET /api/v3/admin`.180struct Me: Decodable, Sendable, Equatable {181    var admin: Admin182    var stats: AdminStats183    var keys: [AccessKey]184    var mail: Bool185    init(from decoder: Decoder) throws {186        let c = try decoder.container(keyedBy: AnyKey.self)187        admin = try c.decode(Admin.self, forKey: AnyKey("admin"))188        stats = c.value("stats") ?? AdminStats()189        keys = c.list("keys")190        mail = c.flag("mail")191    }192}193194/// Réponse d'activation ou de connexion pour l'app (`X-LouKa-Client: ios-admin`) : `session.token`.195struct AdminSessionResponse: Decodable, Sendable {196    struct Info: Decodable, Sendable {197        var token: String?198        var idleHours: Double?199        var maxHours: Double?200        init(from decoder: Decoder) throws {201            let c = try decoder.container(keyedBy: AnyKey.self)202            token = c.text("token"); idleHours = c.double("idle_hours"); maxHours = c.double("max_hours")203        }204    }205    var admin: Admin206    var session: Info?207}208209/// Options d'une cérémonie de clé d'accès : `challenge_id` et `options` au format JSON de WebAuthn.210struct PasskeyChallenge: Decodable, Sendable {211    var challengeID: String212    var options: JSONValue213    var admin: Admin?214    init(from decoder: Decoder) throws {215        let c = try decoder.container(keyedBy: AnyKey.self)216        challengeID = try c.decode(String.self, forKey: AnyKey("challenge_id"))217        options = try c.decode(JSONValue.self, forKey: AnyKey("options"))218        admin = c.value("admin")219    }220}221222struct KeyInvitation: Decodable, Sendable, Equatable {223    var url: String224    var expiresInDays: Int?225    init(from decoder: Decoder) throws {226        let c = try decoder.container(keyedBy: AnyKey.self)227        url = try c.decode(String.self, forKey: AnyKey("url"))228        expiresInDays = c.int("expires_in_days")229    }230}231232struct AdminAccount: Decodable, Sendable, Equatable, Identifiable {233    var id: String234    var name: String235    var email: String236    var mailboxes: [String]237    var active: Bool238    var keys: Int239    init(from decoder: Decoder) throws {240        let c = try decoder.container(keyedBy: AnyKey.self)241        id = try c.decode(String.self, forKey: AnyKey("id"))242        name = c.text("name") ?? ""; email = c.text("email") ?? ""243        mailboxes = c.list("mailboxes", of: String.self)244        active = c.value("active") ?? true245        keys = c.int("keys") ?? 0246    }247}248249struct JournalEntry: Decodable, Sendable, Equatable, Identifiable {250    var id: Int251    var admin: String252    var action: String253    var target: String254    var detail: String255    var at: Double256    init(from decoder: Decoder) throws {257        let c = try decoder.container(keyedBy: AnyKey.self)258        id = c.int("id") ?? 0259        admin = c.text("admin") ?? ""; action = c.text("action") ?? ""; target = c.text("target") ?? ""; detail = c.text("detail") ?? ""260        at = c.double("at") ?? 0261    }262263    /// Libellé lisible d'une action du journal ; le code brut si elle est inconnue de l'app.264    var actionLabel: String {265        let known: [String: String] = [266            "cle_enregistree": "Clé d'accès enregistrée", "cle_retiree": "Clé d'accès retirée", "cle_invitation": "Invitation à ajouter une clé",267            "connexion": "Connexion", "deconnexion": "Déconnexion",268            "gestionnaire_approuver": "Demande approuvée", "gestionnaire_refuser": "Demande refusée", "gestionnaire_suspendre": "Accès suspendu",269            "gestionnaire_retablir": "Accès rétabli", "gestionnaire_remettre_en_attente": "Demande remise en attente", "gestionnaire_rattacher": "Rattachement modifié",270            "fiche_masquee": "Fiche masquée", "fiche_retablie": "Fiche rétablie",271            "signalement_classer": "Signalement classé", "signalement_bloquer": "Conversation bloquée", "courrier_envoi": "Courriel envoyé",272        ]273        return known[action] ?? action.replacingOccurrences(of: "_", with: " ")274    }275}276277// MARK: - Gestionnaires278279enum ManagerStatus: String, Sendable, CaseIterable, Identifiable {280    case pending = "en_attente", approved = "approuve", refused = "refuse", suspended = "suspendu"281    var id: String { rawValue }282    var label: String {283        switch self {284        case .pending: "En attente"285        case .approved: "Approuvé"286        case .refused: "Refusé"287        case .suspended: "Suspendu"288        }289    }290    var symbol: String {291        switch self {292        case .pending: "hourglass"293        case .approved: "checkmark.seal.fill"294        case .refused: "xmark.octagon"295        case .suspended: "pause.circle"296        }297    }298}299300/// Filtre de la liste des demandes : un état, ou toutes.301enum ManagerFilter: String, Sendable, CaseIterable, Identifiable {302    case pending = "en_attente", approved = "approuve", refused = "refuse", suspended = "suspendu", all = "toutes"303    var id: String { rawValue }304    var label: String {305        switch self {306        case .pending: "En attente"307        case .approved: "Approuvées"308        case .refused: "Refusées"309        case .suspended: "Suspendues"310        case .all: "Toutes"311        }312    }313}314315enum ManagerAction: String, Sendable {316    case approve = "approuver", refuse = "refuser", suspend = "suspendre", restore = "retablir", backToPending = "remettre_en_attente", attach = "rattacher"317318    /// Refuser et suspendre exigent un motif, transmis au demandeur.319    var needsReason: Bool { self == .refuse || self == .suspend }320    var title: String {321        switch self {322        case .approve: "Approuver"323        case .refuse: "Refuser"324        case .suspend: "Suspendre"325        case .restore: "Rétablir"326        case .backToPending: "Remettre en attente"327        case .attach: "Rattacher"328        }329    }330    var isDestructive: Bool { self == .refuse || self == .suspend }331332    /// Actions offertes selon l'état d'une demande.333    static func available(for status: ManagerStatus) -> [ManagerAction] {334        switch status {335        case .pending: [.approve, .refuse]336        case .approved: [.suspend, .backToPending]337        case .refused: [.backToPending, .approve]338        case .suspended: [.restore]339        }340    }341}342343struct ManagerRequest: Decodable, Sendable, Hashable, Identifiable {344    struct Directory: Decodable, Sendable, Hashable {345        var name: String346        var website: String?347        var listings: Int?348        init(from decoder: Decoder) throws {349            let c = try decoder.container(keyedBy: AnyKey.self)350            name = c.text("name") ?? ""; website = c.text("website"); listings = c.int("listings")351        }352    }353    var accountID: String354    var email: String355    var name: String356    var title: String?357    var phone: String?358    var company: String359    var website: String?360    var domain: String?361    var sourceID: String?362    var inDirectory: Bool363    var directory: Directory?364    var statusRaw: String365    var reason: String?366    var requestedAt: Double?367    var verifiedAt: Double?368    var decidedAt: Double?369    var decidedBy: String?370    var lastLogin: Double?371    var id: String { accountID }372373    init(from decoder: Decoder) throws {374        let c = try decoder.container(keyedBy: AnyKey.self)375        accountID = try c.decode(String.self, forKey: AnyKey("account_id"))376        email = c.text("email") ?? ""; name = c.text("name") ?? ""377        title = c.text("title"); phone = c.text("phone")378        company = c.text("company") ?? ""; website = c.text("website"); domain = c.text("domain")379        sourceID = c.text("source_id"); inDirectory = c.flag("in_directory"); directory = c.value("directory")380        statusRaw = c.text("status") ?? ManagerStatus.pending.rawValue381        reason = c.text("reason")382        requestedAt = c.double("requested_at"); verifiedAt = c.double("verified_at"); decidedAt = c.double("decided_at")383        decidedBy = c.text("decided_by"); lastLogin = c.double("last_login")384    }385386    /// Un état inconnu de l'app est traité comme une attente.387    var status: ManagerStatus { ManagerStatus(rawValue: statusRaw) ?? .pending }388    /// On ne peut approuver qu'une demande rattachée à un gestionnaire de l'annuaire.389    var canBeApproved: Bool { !(sourceID ?? "").isEmpty }390}391392struct DecisionResult: Decodable, Sendable {393    var status: String?394    var sourceID: String?395    init(from decoder: Decoder) throws {396        let c = try decoder.container(keyedBy: AnyKey.self)397        status = c.text("status"); sourceID = c.text("source_id")398    }399}400401struct DirectoryManager: Decodable, Sendable, Equatable, Identifiable {402    var sourceID: String403    var name: String404    var domain: String?405    var listings: Int?406    var id: String { sourceID }407    init(from decoder: Decoder) throws {408        let c = try decoder.container(keyedBy: AnyKey.self)409        sourceID = try c.decode(String.self, forKey: AnyKey("source_id"))410        name = c.text("name") ?? sourceID; domain = c.text("domain"); listings = c.int("listings")411    }412}413414/// Contenu d'une fiche personnalisée, pour la modération : ce qui se lit, pas ce qui s'édite.415struct FicheContent: Decodable, Sendable, Equatable {416    struct Pair: Sendable, Equatable, Identifiable { var title: String; var text: String; var id: String { title + "|" + text } }417    var tagline: String?418    var about: String?419    var founded: Int?420    var languages: [String] = []421    var phone: String?422    var email: String?423    var website: String?424    var bookingURL: String?425    var address: String?426    var hours: [Pair] = []427    var social: [Pair] = []428    var highlights: [Pair] = []429    var services: [String] = []430    var policies: [Pair] = []431    var faq: [Pair] = []432    var team: [Pair] = []433    var galleryCaptions: [String] = []434    var autoReply: String?435    var responseTime: String?436    var quickReplies: [Pair] = []437438    init(from decoder: Decoder) throws {439        let c = try decoder.container(keyedBy: AnyKey.self)440        tagline = c.text("tagline"); about = c.text("about"); founded = c.int("founded")441        languages = c.list("languages", of: String.self); services = c.list("services", of: String.self)442        func pairs(_ box: KeyedDecodingContainer<AnyKey>, _ key: String, _ a: String, _ b: String) -> [Pair] {443            box.list(key, of: [String: JSONValue].self).compactMap { d in444                let t = d[a]?.string ?? "", x = d[b]?.string ?? ""445                return t.isEmpty && x.isEmpty ? nil : Pair(title: t, text: x)446            }447        }448        if let k = try? c.nestedContainer(keyedBy: AnyKey.self, forKey: AnyKey("contact")) {449            phone = k.text("phone"); email = k.text("email"); website = k.text("website"); bookingURL = k.text("booking_url"); address = k.text("address")450            hours = pairs(k, "hours", "days", "hours")451        }452        if let s: [String: String] = c.value("social") { social = s.filter { !$0.value.isEmpty }.sorted { $0.key < $1.key }.map { Pair(title: $0.key, text: $0.value) } }453        highlights = pairs(c, "highlights", "label", "value")454        policies = pairs(c, "policies", "title", "text")455        faq = pairs(c, "faq", "q", "a")456        team = pairs(c, "team", "name", "role")457        quickReplies = pairs(c, "quick_replies", "title", "text")458        galleryCaptions = c.list("gallery", of: [String: JSONValue].self).compactMap { $0["caption"]?.string }.filter { !$0.isEmpty }459        if let m = try? c.nestedContainer(keyedBy: AnyKey.self, forKey: AnyKey("messaging")) { autoReply = m.text("auto_reply"); responseTime = m.text("response_time") }460    }461462    /// Rien à lire (fiche jamais remplie).463    var isEmpty: Bool {464        tagline == nil && about == nil && services.isEmpty && policies.isEmpty && faq.isEmpty && team.isEmpty && highlights.isEmpty && phone == nil && website == nil && autoReply == nil465    }466}467468/// `GET /fiches/{source_id}`.469struct AdminFiche: Decodable, Sendable, Equatable {470    struct Member: Decodable, Sendable, Equatable, Identifiable {471        var name: String; var email: String; var title: String?472        var id: String { email + "|" + name }473        init(from decoder: Decoder) throws {474            let c = try decoder.container(keyedBy: AnyKey.self)475            name = c.text("name") ?? ""; email = c.text("email") ?? ""; title = c.text("title")476        }477    }478    var sourceID: String479    var draft: FicheContent?480    var published: FicheContent?481    var dirty: Bool482    var draftUpdatedAt: Double?483    var publishedAt: Double?484    var hidden: Bool485    var hiddenReason: String?486    var mediaCount: Int487    var team: [Member]488489    init(from decoder: Decoder) throws {490        let c = try decoder.container(keyedBy: AnyKey.self)491        sourceID = c.text("source_id") ?? ""492        draft = c.value("draft"); published = c.value("published")493        dirty = c.flag("dirty"); hidden = c.flag("hidden"); hiddenReason = c.text("hidden_reason")494        draftUpdatedAt = c.double("draft_updated_at"); publishedAt = c.double("published_at")495        mediaCount = c.list("media", of: JSONValue.self).count496        team = c.list("team")497    }498}499500// MARK: - Signalements501502struct ReportMessage: Decodable, Sendable, Hashable, Identifiable {503    var id: Int504    var role: String505    var author: String506    var text: String507    /// millisecondes508    var createdAt: Double509    init(from decoder: Decoder) throws {510        let c = try decoder.container(keyedBy: AnyKey.self)511        id = c.int("id") ?? 0; role = c.text("role") ?? ""; author = c.text("author") ?? ""512        text = c.raw("text") ?? ""; createdAt = c.double("created_at") ?? 0513    }514}515516struct Report: Decodable, Sendable, Hashable, Identifiable {517    var id: Int518    var conversationID: String519    var messageID: Int?520    var byRole: String521    var reason: String522    /// secondes523    var createdAt: Double524    var handledAt: Double?525    var handledBy: String?526    var decision: String?527    var sourceID: String?528    var managerName: String?529    var tenantName: String?530    var tenantEmail: String?531    var conversationStatus: String?532    var messages: [ReportMessage]533534    init(from decoder: Decoder) throws {535        let c = try decoder.container(keyedBy: AnyKey.self)536        id = c.int("id") ?? 0537        conversationID = c.text("conversation_id") ?? ""; messageID = c.int("message_id")538        byRole = c.text("by_role") ?? ""; reason = c.text("reason") ?? ""539        createdAt = c.double("created_at") ?? 0; handledAt = c.double("handled_at")540        handledBy = c.text("handled_by"); decision = c.text("decision")541        sourceID = c.text("source_id"); managerName = c.text("manager_name"); conversationStatus = c.text("conversation_status")542        if let t = try? c.nestedContainer(keyedBy: AnyKey.self, forKey: AnyKey("tenant")) { tenantName = t.text("name"); tenantEmail = t.text("email") }543        messages = c.list("messages")544    }545546    var isOpen: Bool { handledAt == nil }547    /// Qui a signalé, en clair.548    var reporter: String { byRole == "gestionnaire" ? "le gestionnaire" : byRole == "locataire" ? "le chercheur de logement" : "un participant" }549    /// La conversation signalée n'existe plus (effacée par le chercheur) : il ne reste que le motif.550    var conversationGone: Bool { conversationStatus == nil && messages.isEmpty }551    var decisionLabel: String? {552        switch decision {553        case "classer": "Classé"554        case "bloquer": "Conversation bloquée"555        default: nil556        }557    }558}559560// MARK: - Courrier561562struct MailFolder: Decodable, Sendable, Equatable, Identifiable {563    var id: String564    var name: String565    var role: String?566    var total: Int?567    var unread: Int?568    init(from decoder: Decoder) throws {569        let c = try decoder.container(keyedBy: AnyKey.self)570        id = try c.decode(String.self, forKey: AnyKey("id"))571        name = c.text("name") ?? ""; role = c.text("role"); total = c.int("total"); unread = c.int("unread")572    }573574    /// Dossiers que l'API sait lister, dans l'ordre d'affichage.575    static let roles = ["inbox", "sent", "archive", "junk", "trash"]576    static func label(role: String) -> String {577        switch role {578        case "inbox": "Boîte de réception"579        case "sent": "Envoyés"580        case "archive": "Archives"581        case "junk": "Indésirables"582        case "trash": "Corbeille"583        default: role584        }585    }586    static func symbol(role: String) -> String {587        switch role {588        case "inbox": "tray"589        case "sent": "paperplane"590        case "archive": "archivebox"591        case "junk": "xmark.bin"592        case "trash": "trash"593        default: "folder"594        }595    }596}597598struct Mailbox: Decodable, Sendable, Equatable, Identifiable {599    var address: String600    var folders: [MailFolder]601    var id: String { address }602    init(from decoder: Decoder) throws {603        let c = try decoder.container(keyedBy: AnyKey.self)604        address = try c.decode(String.self, forKey: AnyKey("address"))605        folders = c.list("folders")606    }607    func folder(role: String) -> MailFolder? { folders.first { $0.role == role } }608    var unreadInbox: Int { folder(role: "inbox")?.unread ?? 0 }609}610611struct MailboxList: Decodable, Sendable {612    var mailboxes: [Mailbox]613    init(from decoder: Decoder) throws { mailboxes = try decoder.container(keyedBy: AnyKey.self).list("mailboxes") }614}615616struct MailPerson: Decodable, Sendable, Equatable {617    var email: String618    var name: String?619    init(email: String, name: String? = nil) { self.email = email; self.name = name }620    init(from decoder: Decoder) throws {621        let c = try decoder.container(keyedBy: AnyKey.self)622        email = c.text("email") ?? ""; name = c.text("name")623    }624}625626struct MailAttachment: Decodable, Sendable, Equatable, Identifiable {627    var id: String628    var name: String?629    var type: String?630    var size: Int?631    init(from decoder: Decoder) throws {632        let c = try decoder.container(keyedBy: AnyKey.self)633        id = try c.decode(String.self, forKey: AnyKey("id"))634        name = c.text("name") ?? c.text("filename"); type = c.text("type") ?? c.text("content_type"); size = c.int("size")635    }636}637638/// Un courriel : résumé dans une liste, complet (`text`, `html`, `attachments`) à la lecture.639struct MailMessage: Decodable, Sendable, Equatable, Identifiable {640    var id: String641    var mailbox: String642    var from: [MailPerson]643    var to: [MailPerson]644    var cc: [MailPerson]645    var replyTo: [MailPerson]646    var subject: String?647    var preview: String?648    var receivedAt: String?649    var unread: Bool650    var starred: Bool651    var hasAttachment: Bool652    var answered: Bool653    var text: String?654    var html: String?655    var truncated: Bool656    var attachments: [MailAttachment]657    var spf: String?658    var dkim: String?659    var dmarc: String?660661    init(id: String, mailbox: String, from: [MailPerson] = [], to: [MailPerson] = [], replyTo: [MailPerson] = [], subject: String? = nil,662         receivedAt: String? = nil, unread: Bool = false, text: String? = nil, html: String? = nil) {663        self.id = id; self.mailbox = mailbox; self.from = from; self.to = to; cc = []; self.replyTo = replyTo; self.subject = subject; preview = nil664        self.receivedAt = receivedAt; self.unread = unread; starred = false; hasAttachment = false; answered = false; self.text = text; self.html = html665        truncated = false; attachments = []666    }667668    init(from decoder: Decoder) throws {669        let c = try decoder.container(keyedBy: AnyKey.self)670        id = try c.decode(String.self, forKey: AnyKey("id"))671        mailbox = c.text("mailbox") ?? ""672        from = c.list("from"); to = c.list("to"); cc = c.list("cc"); replyTo = c.list("reply_to")673        subject = c.text("subject"); preview = c.text("preview")674        receivedAt = c.text("received_at") ?? c.text("sent_at")675        unread = c.flag("unread"); starred = c.flag("starred"); hasAttachment = c.flag("has_attachment"); answered = c.flag("answered")676        text = c.raw("text"); html = c.raw("html"); truncated = c.flag("truncated")677        attachments = c.list("attachments")678        if let a = try? c.nestedContainer(keyedBy: AnyKey.self, forKey: AnyKey("auth")) { spf = a.text("spf"); dkim = a.text("dkim"); dmarc = a.text("dmarc") }679    }680681    var date: Date? {682        guard let receivedAt else { return nil }683        let f = ISO8601DateFormatter()684        if let d = f.date(from: receivedAt) { return d }685        f.formatOptions = [.withInternetDateTime, .withFractionalSeconds]686        return f.date(from: receivedAt)687    }688}689690struct MailPage: Decodable, Sendable {691    var data: [MailMessage]692    var nextCursor: String?693    var hasMore: Bool694    init(from decoder: Decoder) throws {695        let c = try decoder.container(keyedBy: AnyKey.self)696        data = c.list("data"); nextCursor = c.text("next_cursor"); hasMore = c.flag("has_more")697    }698}699700/// Courriel à envoyer. L'expéditeur doit être une des boîtes de l'administrateur.701struct MailDraft: Encodable, Sendable, Equatable {702    var from: String703    var to: [String]704    var cc: [String]?705    var subject: String706    var text: String707    var replyToMessageID: String?708    enum CodingKeys: String, CodingKey { case from, to, cc, subject, text; case replyToMessageID = "reply_to_message_id" }709}710
Files main
Menu

Theme