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/MessagingModels.swift10// Description : gestionnaires vérifiés et messagerie (contrat dans11// docs/COMPTES-API.md, deuxième partie) — pastille d'un12// logement, fiche publique d'un gestionnaire, conversations,13// messages. Décodage tolérant. Tout texte de ces formes est14// du texte brut saisi par un tiers.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/// Accès d'un compte de gestionnaire (`user.manager`).96struct ManagerAccess: Codable, Sendable, Equatable {97 enum Status: String, Sendable { case pending = "en_attente", approved = "approuve", refused = "refuse", suspended = "suspendu" }9899 var sourceID: String?100 var company: String?101 var website: String?102 var status: String?103 var reason: String?104105 enum CodingKeys: String, CodingKey { case company, website, status, reason; case sourceID = "source_id" }106107 init(sourceID: String? = nil, company: String? = nil, website: String? = nil, status: String? = nil, reason: String? = nil) {108 self.sourceID = sourceID; self.company = company; self.website = website; self.status = status; self.reason = reason109 }110111 init(from decoder: Decoder) throws {112 guard let c = try? decoder.container(keyedBy: CodingKeys.self) else { return }113 sourceID = try? c.decodeIfPresent(String.self, forKey: .sourceID)114 company = try? c.decodeIfPresent(String.self, forKey: .company)115 website = try? c.decodeIfPresent(String.self, forKey: .website)116 status = try? c.decodeIfPresent(String.self, forKey: .status)117 reason = try? c.decodeIfPresent(String.self, forKey: .reason)118 }119120 /// Un état inconnu, ou un accès approuvé sans entreprise rattachée, est traité comme une attente.121 var state: Status {122 let s = status.flatMap(Status.init(rawValue:)) ?? .pending123 return s == .approved && (sourceID ?? "").isEmpty ? .pending : s124 }125}126127/// Image d'une fiche : adresse relative au site. Seules les images servies par Lou-Ka (`/media/pro/…`) s'affichent.128struct MediaImage: Decodable, Sendable, Equatable {129 var url: String130 var width: Double?131 var height: Double?132133 init(url: String, width: Double? = nil, height: Double? = nil) { self.url = url; self.width = width; self.height = height }134135 init(from decoder: Decoder) throws {136 let c = try decoder.container(keyedBy: AnyCodingKey.self)137 url = try c.decode(String.self, forKey: AnyCodingKey("url"))138 width = try? c.decodeIfPresent(Double.self, forKey: AnyCodingKey("width"))139 height = try? c.decodeIfPresent(Double.self, forKey: AnyCodingKey("height"))140 }141142 var isSafe: Bool { url.hasPrefix("/media/pro/") && !url.contains("..") && !url.contains("//") }143144 /// Adresse absolue, ou nil si l'image ne vient pas de `/media/pro/`.145 func absolute(base: URL) -> String? {146 guard isSafe else { return nil }147 var s = base.absoluteString148 while s.hasSuffix("/") { s.removeLast() }149 return s + url150 }151152 var aspect: CGFloat? {153 guard let w = width, let h = height, w > 0, h > 0 else { return nil }154 return CGFloat(w / h)155 }156}157158struct AnyCodingKey: CodingKey {159 var stringValue: String160 var intValue: Int? { nil }161 init(_ s: String) { stringValue = s }162 init?(stringValue: String) { self.stringValue = stringValue }163 init?(intValue: Int) { nil }164}165166private extension KeyedDecodingContainer where K == AnyCodingKey {167 func text(_ k: String) -> String? {168 guard let s = try? decodeIfPresent(String.self, forKey: AnyCodingKey(k)) else { return nil }169 let t = s.trimmingCharacters(in: .whitespacesAndNewlines)170 return t.isEmpty ? nil : t171 }172 func flag(_ k: String) -> Bool { ((try? decodeIfPresent(Bool.self, forKey: AnyCodingKey(k))) ?? nil) ?? false }173 func image(_ k: String) -> MediaImage? { (try? decodeIfPresent(MediaImage.self, forKey: AnyCodingKey(k))) ?? nil }174 /// Tableau dont chaque élément illisible est ignoré.175 func list<T: Decodable>(_ k: String, of: T.Type = T.self) -> [T] {176 ((try? decodeIfPresent([Failable<T>].self, forKey: AnyCodingKey(k))) ?? nil)?.compactMap(\.value) ?? []177 }178}179180private struct Failable<T: Decodable>: Decodable {181 var value: T?182 init(from decoder: Decoder) throws { value = try? T(from: decoder) }183}184185/// `GET /gestionnaires/annonce/{uid}` : ce que la fiche d'un logement montre de son gestionnaire.186struct ListingManagerInfo: Decodable, Sendable, Equatable {187 struct Manager: Decodable, Sendable, Equatable {188 var sourceID: String189 var name: String190 var verified: Bool191 var messaging: Bool192 var logo: MediaImage?193 var responseTime: String?194195 init(sourceID: String, name: String, verified: Bool, messaging: Bool, logo: MediaImage? = nil, responseTime: String? = nil) {196 self.sourceID = sourceID; self.name = name; self.verified = verified; self.messaging = messaging; self.logo = logo; self.responseTime = responseTime197 }198199 init(from decoder: Decoder) throws {200 let c = try decoder.container(keyedBy: AnyCodingKey.self)201 sourceID = try c.decode(String.self, forKey: AnyCodingKey("source_id"))202 name = c.text("name") ?? ""203 verified = c.flag("verified")204 messaging = c.flag("messaging")205 logo = c.image("logo")206 responseTime = c.text("response_time")207 }208209 /// On n'écrit qu'à un gestionnaire vérifié qui a laissé sa messagerie ouverte.210 var canMessage: Bool { verified && messaging }211 }212213 var manager: Manager?214 var note: String?215216 init(manager: Manager?, note: String?) { self.manager = manager; self.note = note }217218 init(from decoder: Decoder) throws {219 let c = try decoder.container(keyedBy: AnyCodingKey.self)220 manager = (try? c.decodeIfPresent(Manager.self, forKey: AnyCodingKey("manager"))) ?? nil221 note = c.text("note")222 }223}224225/// Fiche publique d'un gestionnaire (`GET /gestionnaires/{source_id}/fiche`).226struct ManagerFiche: Decodable, Sendable, Equatable {227 struct Pair: Decodable, Sendable, Equatable, Identifiable {228 var title: String229 var text: String230 var id: String { title + "|" + text }231 }232 struct Member: Sendable, Equatable, Identifiable { var name: String; var role: String?; var photo: MediaImage?; var id: String { name + "|" + (role ?? "") } }233 struct Photo: Sendable, Equatable, Identifiable { var image: MediaImage; var caption: String?; var id: String { image.url + "|" + (caption ?? "") } }234 struct Hours: Sendable, Equatable, Identifiable { var days: String; var hours: String; var id: String { days + "|" + hours } }235 struct LinkItem: Sendable, Equatable, Identifiable { var label: String; var url: String; var id: String { label + "|" + url } }236237 struct Content: Decodable, Sendable, Equatable {238 var tagline: String?239 var about: String?240 var founded: Int?241 var languages: [String] = []242 var phone: String?243 var email: String?244 var website: String?245 var bookingURL: String?246 var address: String?247 var hours: [Hours] = []248 var social: [LinkItem] = []249 var highlights: [Pair] = []250 var services: [String] = []251 var policies: [Pair] = []252 var faq: [Pair] = []253 var team: [Member] = []254 var logo: MediaImage?255 var cover: MediaImage?256 var gallery: [Photo] = []257 var responseTime: String?258259 init() {}260261 init(from decoder: Decoder) throws {262 let c = try decoder.container(keyedBy: AnyCodingKey.self)263 tagline = c.text("tagline"); about = c.text("about")264 founded = (try? c.decodeIfPresent(Int.self, forKey: AnyCodingKey("founded"))) ?? nil265 languages = c.list("languages", of: String.self).filter { !$0.isEmpty }266 services = c.list("services", of: String.self).filter { !$0.isEmpty }267 logo = c.image("logo"); cover = c.image("cover")268 if let k = try? c.nestedContainer(keyedBy: AnyCodingKey.self, forKey: AnyCodingKey("contact")) {269 phone = k.text("phone"); email = k.text("email"); website = k.text("website")270 bookingURL = k.text("booking_url"); address = k.text("address")271 hours = k.list("hours", of: [String: String].self).compactMap { d in272 guard let days = d["days"], let h = d["hours"], !days.isEmpty || !h.isEmpty else { return nil }273 return Hours(days: days, hours: h)274 }275 }276 if let s = (try? c.decodeIfPresent([String: String].self, forKey: AnyCodingKey("social"))) ?? nil {277 let names = ["facebook": "Facebook", "instagram": "Instagram", "linkedin": "LinkedIn", "youtube": "YouTube", "tiktok": "TikTok", "x": "X"]278 social = ["facebook", "instagram", "linkedin", "youtube", "tiktok", "x"].compactMap { k in279 guard let u = s[k], !u.isEmpty, let n = names[k] else { return nil }280 return LinkItem(label: n, url: u)281 }282 }283 func pairs(_ key: String, _ a: String, _ b: String) -> [Pair] {284 c.list(key, of: [String: String].self).compactMap { d in285 guard let t = d[a], let x = d[b], !t.isEmpty, !x.isEmpty else { return nil }286 return Pair(title: t, text: x)287 }288 }289 highlights = pairs("highlights", "label", "value")290 policies = pairs("policies", "title", "text")291 faq = pairs("faq", "q", "a")292 struct RawMember: Decodable { var name: String?; var role: String?; var photo: MediaImage?293 init(from d: Decoder) throws {294 let c = try d.container(keyedBy: AnyCodingKey.self)295 name = c.text("name"); role = c.text("role"); photo = c.image("photo")296 } }297 team = c.list("team", of: RawMember.self).compactMap { m in m.name.map { Member(name: $0, role: m.role, photo: m.photo) } }298 struct RawPhoto: Decodable { var image: MediaImage?; var caption: String?299 init(from d: Decoder) throws {300 let c = try d.container(keyedBy: AnyCodingKey.self)301 image = c.image("image"); caption = c.text("caption")302 } }303 gallery = c.list("gallery", of: RawPhoto.self).compactMap { p in p.image.flatMap { $0.isSafe ? Photo(image: $0, caption: p.caption) : nil } }304 if let m = try? c.nestedContainer(keyedBy: AnyCodingKey.self, forKey: AnyCodingKey("messaging")) { responseTime = m.text("response_time") }305 }306307 /// Paragraphes de la présentation : les retours à la ligne séparent les paragraphes.308 var aboutParagraphs: [String] { ManagerFiche.paragraphs(about) }309 }310311 var sourceID: String312 var verified: Bool313 var messaging: Bool314 var content: Content?315316 init(sourceID: String, verified: Bool, messaging: Bool, content: Content?) {317 self.sourceID = sourceID; self.verified = verified; self.messaging = messaging; self.content = content318 }319320 init(from decoder: Decoder) throws {321 let c = try decoder.container(keyedBy: AnyCodingKey.self)322 sourceID = c.text("source_id") ?? ""323 verified = c.flag("verified")324 messaging = c.flag("messaging")325 content = (try? c.decodeIfPresent(Content.self, forKey: AnyCodingKey("content"))) ?? nil326 }327328 var canMessage: Bool { verified && messaging }329330 static func paragraphs(_ text: String?) -> [String] {331 (text ?? "").components(separatedBy: .newlines).map { $0.trimmingCharacters(in: .whitespaces) }.filter { !$0.isEmpty }332 }333}334335// MARK: - Messagerie336337/// Un message d'une conversation. `role` : `locataire`, `gestionnaire` ou `systeme` (réponse automatique).338struct ChatMessage: Decodable, Sendable, Equatable, Identifiable {339 var id: Int64340 var role: String341 var author: String342 var text: String343 var createdAt: Int64344 var mine: Bool345346 init(id: Int64, role: String, author: String = "", text: String, createdAt: Int64 = 0, mine: Bool = false) {347 self.id = id; self.role = role; self.author = author; self.text = text; self.createdAt = createdAt; self.mine = mine348 }349350 init(from decoder: Decoder) throws {351 let c = try decoder.container(keyedBy: AnyCodingKey.self)352 id = Ms.decode(c, AnyCodingKey("id")) ?? 0353 role = (try? c.decodeIfPresent(String.self, forKey: AnyCodingKey("role"))) ?? "gestionnaire"354 author = (try? c.decodeIfPresent(String.self, forKey: AnyCodingKey("author"))) ?? ""355 text = (try? c.decodeIfPresent(String.self, forKey: AnyCodingKey("text"))) ?? ""356 createdAt = Ms.decode(c, AnyCodingKey("created_at")) ?? 0357 mine = c.flag("mine")358 }359360 /// Réponse automatique du gestionnaire : présentée comme telle, jamais comme un message écrit à la main.361 var isAutomatic: Bool { role == "systeme" }362}363364struct Conversation: Decodable, Sendable, Equatable, Identifiable {365 var id: String366 var sourceID: String367 var managerName: String368 var uid: String?369 var listing: FavoriteSnapshot?370 var updatedAt: Int64371 var lastMessage: String372 var lastRole: String?373 var status: String374 var unread: Bool375 var archived: Bool376 var canReply: Bool?377 /// pour un gestionnaire seulement378 var tenantName: String?379380 init(id: String, sourceID: String = "", managerName: String = "", uid: String? = nil, listing: FavoriteSnapshot? = nil, updatedAt: Int64 = 0,381 lastMessage: String = "", lastRole: String? = nil, status: String = "ouverte", unread: Bool = false, archived: Bool = false,382 canReply: Bool? = nil, tenantName: String? = nil) {383 self.id = id; self.sourceID = sourceID; self.managerName = managerName; self.uid = uid; self.listing = listing; self.updatedAt = updatedAt384 self.lastMessage = lastMessage; self.lastRole = lastRole; self.status = status; self.unread = unread; self.archived = archived385 self.canReply = canReply; self.tenantName = tenantName386 }387388 init(from decoder: Decoder) throws {389 let c = try decoder.container(keyedBy: AnyCodingKey.self)390 id = try c.decode(String.self, forKey: AnyCodingKey("id"))391 sourceID = c.text("source_id") ?? ""392 managerName = c.text("manager_name") ?? ""393 uid = c.text("uid")394 listing = (try? c.decodeIfPresent(FavoriteSnapshot.self, forKey: AnyCodingKey("listing"))) ?? nil395 updatedAt = Ms.decode(c, AnyCodingKey("updated_at")) ?? Ms.decode(c, AnyCodingKey("created_at")) ?? 0396 lastMessage = (try? c.decodeIfPresent(String.self, forKey: AnyCodingKey("last_message"))) ?? ""397 lastRole = c.text("last_role")398 status = c.text("status") ?? "ouverte"399 unread = c.flag("unread")400 archived = c.flag("archived")401 canReply = (try? c.decodeIfPresent(Bool.self, forKey: AnyCodingKey("can_reply"))) ?? nil402 tenantName = c.text("tenant_name")403 }404405 var isClosed: Bool { status == "fermee" }406 var isBlocked: Bool { status == "bloquee" }407 /// Peut-on répondre ? `can_reply` du serveur fait foi ; à défaut, l'état de la conversation.408 var acceptsReplies: Bool { canReply ?? (status == "ouverte") }409410 /// Interlocuteur à afficher : le chercheur pour un gestionnaire, l'entreprise pour un chercheur.411 func counterpart(forManager: Bool) -> String {412 if forManager { return tenantName ?? "Chercheur de logement" }413 return managerName.isEmpty ? "Gestionnaire" : managerName414 }415416 /// « Studio · Montréal » : le logement dont on parle, d'après l'aperçu envoyé à l'ouverture.417 var listingLine: String? {418 guard let l = listing else { return nil }419 let parts = [l.unitType, l.title == l.unitType ? nil : l.title, l.city].compactMap { $0 }.filter { !$0.isEmpty }420 return parts.isEmpty ? nil : parts.joined(separator: " · ")421 }422}423424struct ConversationList: Decodable, Sendable {425 var items: [Conversation]426 var unread: Int427 init(from decoder: Decoder) throws {428 let c = try decoder.container(keyedBy: AnyCodingKey.self)429 items = c.list("items", of: Conversation.self)430 unread = ((try? c.decodeIfPresent(Int.self, forKey: AnyCodingKey("unread"))) ?? nil) ?? 0431 }432}433434struct ConversationThread: Decodable, Sendable {435 var conversation: Conversation436 var messages: [ChatMessage]437 var created: Bool?438 init(from decoder: Decoder) throws {439 let c = try decoder.container(keyedBy: AnyCodingKey.self)440 conversation = try c.decode(Conversation.self, forKey: AnyCodingKey("conversation"))441 messages = c.list("messages", of: ChatMessage.self)442 created = (try? c.decodeIfPresent(Bool.self, forKey: AnyCodingKey("created"))) ?? nil443 }444}445446struct UnreadCount: Decodable, Sendable { var unread: Int }447struct MessageEnvelope: Decodable, Sendable { var message: ChatMessage }448struct ConversationEnvelope: Decodable, Sendable { var conversation: Conversation }449450extension Listing {451 /// Aperçu du logement joint à un message (mêmes champs que l'aperçu d'un favori).452 var snapshot: FavoriteSnapshot {453 func t(_ s: String) -> String? { s.isEmpty ? nil : String(s.prefix(300)) }454 return FavoriteSnapshot(title: t(displayTitle), address: t(address), city: t(cleanCity), sector: t(sector), unitType: t(unitType),455 price: plausiblePrice, image: images.first.flatMap(t), source: t(source), areaSqft: areaSqft,456 lat: coordinate?.latitude, lng: coordinate?.longitude)457 }458}459