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/Messaging.swift10// Description : messagerie avec les gestionnaires — règles de relève11// (pures, testées), pastille des non-lus, appels de la12// messagerie, message en attente de connexion. Rien n'est13// écrit sur disque ni dans les journaux : conversations et14// messages ne vivent qu'en mémoire, le temps de l'écran. Pas15// de notification poussée : le serveur n'a pas d'émetteur16// APNs ; l'app relève quand elle est au premier plan.17// Module : LouKa18// Repository : https://git.spboucher.ai/lou-ka-ios-v319// Project Website : https://www.lou-ka.com20// Created : 2026-11-3021// Last Modified : 2026-11-3022//23// =============================================================================24// AUTHOR & PROFESSIONAL AFFILIATION25// =============================================================================26//27// Author : Simon-Pierre Boucher28// Position : Professor of Finance29// Institution : Université du Québec en Outaouais (UQO)30// Department : Département des sciences administratives31// Organization : SP Boucher32//33// Website : https://spboucher.ai34// Git : https://git.spboucher.ai35//36// =============================================================================37// OFFICIAL CONTACT DIRECTORY38// =============================================================================39//40// General : info@spboucher.ai41// Professional : contact@spboucher.ai42// Direct : simon@spboucher.ai43// Research : research@spboucher.ai44// Development : dev@spboucher.ai45// Support : support@spboucher.ai46// Security/Admin : admin@spboucher.ai47// Notifications : notifications@spboucher.ai48//49// Preferred Contact: support@spboucher.ai50//51// =============================================================================52// COPYRIGHT & INTELLECTUAL PROPERTY53// =============================================================================54//55// Copyright (c) 202656// Simon-Pierre Boucher57//58// All rights reserved where applicable.59//60// This file is governed by the applicable project license,61// copyright notices, institutional agreements and relevant law.62//63// Unless expressly authorized by the applicable license or64// rights holder, copying, redistribution, sublicensing,65// publication and commercial exploitation are not permitted.66//67// Existing third-party rights and notices remain unaffected.68//69// =============================================================================70// CONFIDENTIALITY & SECURITY71// =============================================================================72//73// Classification : Public74// Distribution : Public repository; use is governed by the project license75// Security Contact : admin@spboucher.ai76//77// Access to this source does not independently grant permission78// to redistribute or disclose confidential materials.79//80// Do not embed credentials, private keys, access tokens,81// certificates or confidential personal information.82//83// =============================================================================84// LICENSE & MAINTENANCE85// =============================================================================86//87// License : None specified (no license file in this repository)88// Maintainer : Simon-Pierre Boucher89// Technical Contact: dev@spboucher.ai90//91// =============================================================================92// END OF SP BOUCHER SOURCE HEADER93// =============================================================================9495import Foundation96import Observation97import UIKit9899/// Règles de la messagerie (pures).100enum MessagingPolicy {101 /// Pastille : au plus une lecture de `non-lus` par minute.102 static let unreadInterval: TimeInterval = 60103 /// Fil ouvert : relève toutes les 18 s (le contrat demande 15 à 20 s).104 static let threadInterval: TimeInterval = 18105 /// Boîte ouverte : relève toutes les 60 s.106 static let inboxInterval: TimeInterval = 60107 static let maxLength = 4000108 /// Un message rédigé avant la connexion est gardé en mémoire 30 minutes au plus.109 static let draftLifetime: TimeInterval = 30 * 60110111 /// Peut-on interroger la messagerie ? Jamais sans session, jamais à l'arrière-plan, jamais pour un compte112 /// qui n'y a pas droit (adresse non confirmée, gestionnaire sans accès approuvé).113 static func canPoll(user: AccountUser?, active: Bool) -> Bool {114 guard active, let user else { return false }115 return user.canUseMessaging116 }117118 /// Faut-il relire le compte des non-lus maintenant ?119 static func shouldRefreshUnread(user: AccountUser?, active: Bool, last: Date?, now: Date = Date()) -> Bool {120 guard canPoll(user: user, active: active) else { return false }121 guard let last else { return true }122 return now.timeIntervalSince(last) >= unreadInterval123 }124125 /// Ajoute les messages relevés au fil : sans doublon, dans l'ordre des identifiants.126 static func merge(_ thread: [ChatMessage], _ new: [ChatMessage]) -> [ChatMessage] {127 var byID = Dictionary(thread.map { ($0.id, $0) }, uniquingKeysWith: { a, _ in a })128 for m in new { byID[m.id] = m }129 return byID.values.sorted { $0.id < $1.id }130 }131132 /// Identifiant à passer à `?apres=` : le dernier message connu.133 static func cursor(_ thread: [ChatMessage]) -> Int64? { thread.map(\.id).max() }134135 /// Texte prêt à envoyer, ou nil s'il est vide ; borné à 4 000 caractères.136 static func clean(_ text: String) -> String? {137 let t = text.trimmingCharacters(in: .whitespacesAndNewlines)138 return t.isEmpty ? nil : String(t.prefix(maxLength))139 }140141 /// Message proposé à l'ouverture de la rédaction (modifiable).142 static func prefill(listingTitle: String?) -> String {143 if let t = listingTitle, !t.isEmpty { return "Bonjour,\n\nJe suis intéressé par ce logement (\(t)). Est-il toujours disponible ? J'aimerais le visiter.\n\nMerci." }144 return "Bonjour,\n\nJe cherche un logement et j'aimerais en savoir plus sur vos disponibilités.\n\nMerci."145 }146}147148/// L'app est-elle au premier plan ? Lu au moment de la relève : la valeur de `scenePhase` capturée par une149/// tâche de vue au lancement est périmée (souvent « inactive »).150@MainActor151enum Foreground {152 static var isActive: Bool { UIApplication.shared.applicationState == .active }153}154155/// À qui l'on écrit : au gestionnaire d'un logement (avec l'aperçu du logement) ou à une entreprise.156struct ComposeTarget: Identifiable, Equatable, Sendable {157 var uid: String?158 var sourceID: String159 var managerName: String160 var listing: FavoriteSnapshot?161 /// Texte déjà rédigé (retour de la connexion) ; nil : message proposé.162 var text: String?163 var id: String { (uid ?? "") + "|" + sourceID }164165 var listingTitle: String? { [listing?.unitType, listing?.title].compactMap { $0 }.filter { !$0.isEmpty }.first }166}167168@MainActor169@Observable170final class Messaging {171 @ObservationIgnored let api: AccountAPI172 @ObservationIgnored var user: () -> AccountUser? = { nil }173 @ObservationIgnored var onUnauthenticated: () -> Void = {}174175 /// Conversations avec du nouveau (pastille).176 private(set) var unread = 0177 @ObservationIgnored private(set) var lastUnreadCheck: Date?178 /// Message rédigé avant la connexion, gardé en mémoire seulement.179 @ObservationIgnored private var draft: (target: ComposeTarget, at: Date)?180181 init(api: AccountAPI) { self.api = api }182183 /// Déconnexion : plus de pastille, plus de brouillon, plus aucun appel.184 func reset() {185 unread = 0186 lastUnreadCheck = nil187 draft = nil188 }189190 // MARK: Brouillon en attente de connexion191192 func keepDraft(_ target: ComposeTarget, text: String, now: Date = Date()) {193 var t = target194 t.text = text195 draft = (t, now)196 }197198 /// Rend le brouillon s'il a moins de 30 minutes, et l'oublie.199 func takeDraft(now: Date = Date()) -> ComposeTarget? {200 defer { draft = nil }201 guard let d = draft, now.timeIntervalSince(d.at) <= MessagingPolicy.draftLifetime else { return nil }202 return d.target203 }204205 // MARK: Appels206207 private func call<T: Sendable>(_ work: () async throws -> T) async throws -> T {208 do { return try await work() } catch let e as AccountError {209 if e.isUnauthenticated { onUnauthenticated() }210 throw e211 }212 }213214 /// Relit la pastille si les règles le permettent (session, premier plan, une fois par minute au plus).215 func refreshUnread(active: Bool, now: Date = Date()) async {216 guard MessagingPolicy.shouldRefreshUnread(user: user(), active: active, last: lastUnreadCheck, now: now) else { return }217 lastUnreadCheck = now218 if let n = try? await call({ try await api.unreadCount() }), user() != nil { unread = max(0, n) }219 }220221 func conversations(archived: Bool) async throws -> [Conversation] {222 let list = try await call { try await api.conversations(archived: archived) }223 if !archived { unread = max(0, list.unread); lastUnreadCheck = Date() }224 return list.items225 }226227 /// Ouvre (ou reprend) une conversation. Réservé aux chercheurs de logement.228 func open(_ target: ComposeTarget, text: String) async throws -> ConversationThread {229 guard user()?.canStartConversation != false else {230 throw AccountError.api(status: 403, code: "reserve_aux_locataires", message: "Seul un chercheur de logement peut ouvrir une conversation.", param: nil, retryAfter: nil)231 }232 guard let text = MessagingPolicy.clean(text) else {233 throw AccountError.api(status: 422, code: "message_vide", message: "Écrivez un message avant de l'envoyer.", param: "text", retryAfter: nil)234 }235 return try await call { try await api.openConversation(uid: target.uid, sourceID: target.sourceID, text: text, listing: target.listing) }236 }237238 /// Le fil entier (marque la conversation comme lue), ou seulement ce qui suit `after`.239 func thread(_ id: String, after: Int64? = nil) async throws -> ConversationThread {240 let wasFull = after == nil241 let t = try await call { try await api.thread(id, after: after) }242 // ouvrir un fil le marque comme lu : la pastille suit sans attendre la minute243 if wasFull, unread > 0 { lastUnreadCheck = nil; await refreshUnread(active: true) }244 return t245 }246247 func reply(_ id: String, text: String) async throws -> ChatMessage {248 guard let text = MessagingPolicy.clean(text) else {249 throw AccountError.api(status: 422, code: "message_vide", message: "Écrivez un message avant de l'envoyer.", param: "text", retryAfter: nil)250 }251 return try await call { try await api.reply(id, text: text) }252 }253254 func setArchived(_ id: String, _ archived: Bool) async throws -> Conversation { try await call { try await api.setArchived(id, archived) } }255 func close(_ id: String) async throws -> Conversation { try await call { try await api.closeConversation(id) } }256 func delete(_ id: String) async throws { try await call { try await api.deleteConversation(id) } }257 func report(_ id: String, reason: String, messageID: Int64? = nil) async throws {258 try await call { try await api.report(id, reason: String(reason.prefix(1000)), messageID: messageID) }259 }260261 // MARK: Public (sans session)262263 /// Gestionnaire d'un logement ; nil si rien à montrer (pas de gestionnaire, serveur sans la route, panne).264 func listingManager(uid: String) async -> ListingManagerInfo? { try? await api.listingManager(uid: uid) }265 func managerFiche(sourceID: String, countView: Bool) async -> ManagerFiche? { try? await api.managerFiche(sourceID: sourceID, countView: countView) }266}267268/// Fil d'une conversation à l'écran : chargement, relève, réponse. Vit en mémoire seulement.269@MainActor270@Observable271final class ThreadModel {272 let id: String273 @ObservationIgnored private let messaging: Messaging274275 private(set) var conversation: Conversation?276 private(set) var messages: [ChatMessage] = []277 private(set) var loading = true278 /// Échec du chargement, en clair.279 private(set) var failure: String?280 /// La conversation n'existe plus (effacée).281 private(set) var gone = false282 private(set) var sending = false283284 init(id: String, messaging: Messaging) { self.id = id; self.messaging = messaging }285286 func load() async {287 do {288 let t = try await messaging.thread(id)289 conversation = t.conversation290 messages = MessagingPolicy.merge([], t.messages)291 failure = nil292 } catch let e as AccountError {293 if e.isNotFound { gone = true }294 if messages.isEmpty { failure = e.errorDescription }295 } catch {}296 loading = false297 }298299 /// Une relève : seulement les messages qui suivent le dernier connu. Sans effet si la session ou le300 /// premier plan manquent, ou si rien n'est encore chargé.301 func poll(active: Bool) async {302 guard MessagingPolicy.canPoll(user: messaging.user(), active: active), conversation != nil, !gone else { return }303 do {304 let t = try await messaging.thread(id, after: MessagingPolicy.cursor(messages) ?? 0)305 conversation = t.conversation306 messages = MessagingPolicy.merge(messages, t.messages)307 } catch let e as AccountError {308 if e.isNotFound { gone = true }309 } catch {}310 }311312 /// Envoie une réponse ; rend le message d'erreur du serveur en cas d'échec.313 func send(_ text: String) async -> String? {314 guard !sending else { return nil }315 sending = true316 defer { sending = false }317 do {318 let m = try await messaging.reply(id, text: text)319 messages = MessagingPolicy.merge(messages, [m])320 return nil321 } catch let e as AccountError {322 if e.code == "conversation_fermee" { conversation?.status = "fermee"; conversation?.canReply = false }323 return e.errorDescription324 } catch { return "Envoi impossible. Réessayez dans un instant." }325 }326327 func apply(_ c: Conversation) { conversation = c }328}329