Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : Immo-Ka iOS9// File : ImmoKa/Core/Account/MessagingModels.swift10// Description : courtiers vérifiés et messagerie (contrat dans11// docs/COMPTES-API.md, deuxième partie) — pastille d'une12// propriété, fiche publique d'un courtier, conversations,13// messages. Décodage tolérant. Tout texte de ces formes est14// du texte brut saisi par un tiers.15// Module : ImmoKa16// Repository : https://git.spboucher.ai/immo-ka-ios-v317// Project Website : https://www.immo-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 courtier (`user.broker`).96struct BrokerAccess: Codable, Sendable, Equatable {97 enum Status: String, Sendable { case pending = "en_attente", approved = "approuve", refused = "refuse", suspended = "suspendu" }9899 var brokerID: String?100 /// nom du courtier tel qu'il figure à son permis101 var company: String?102 var agency: String?103 var title: String?104 var phone: String?105 var status: String?106 var reason: String?107108 enum CodingKeys: String, CodingKey { case company, agency, title, phone, status, reason; case brokerID = "broker_id" }109110 init(brokerID: String? = nil, company: String? = nil, agency: String? = nil, title: String? = nil, phone: String? = nil, status: String? = nil, reason: String? = nil) {111 self.brokerID = brokerID; self.company = company; self.agency = agency; self.title = title; self.phone = phone; self.status = status; self.reason = reason112 }113114 init(from decoder: Decoder) throws {115 guard let c = try? decoder.container(keyedBy: CodingKeys.self) else { return }116 brokerID = (try? c.decodeIfPresent(String.self, forKey: .brokerID)) ?? Ms.decode(c, .brokerID).map { String($0) }117 company = try? c.decodeIfPresent(String.self, forKey: .company)118 agency = try? c.decodeIfPresent(String.self, forKey: .agency)119 title = try? c.decodeIfPresent(String.self, forKey: .title)120 phone = try? c.decodeIfPresent(String.self, forKey: .phone)121 status = try? c.decodeIfPresent(String.self, forKey: .status)122 reason = try? c.decodeIfPresent(String.self, forKey: .reason)123 }124125 /// Un état inconnu, ou un accès approuvé sans courtier de l'annuaire rattaché, est traité comme une attente.126 var state: Status {127 let s = status.flatMap(Status.init(rawValue:)) ?? .pending128 return s == .approved && (brokerID ?? "").isEmpty ? .pending : s129 }130}131132/// Image d'une fiche : adresse relative au site. Seules les images servies par Immo-Ka (`/media/pro/…`) s'affichent.133struct MediaImage: Decodable, Sendable, Equatable {134 var url: String135 var width: Double?136 var height: Double?137138 init(url: String, width: Double? = nil, height: Double? = nil) { self.url = url; self.width = width; self.height = height }139140 init(from decoder: Decoder) throws {141 let c = try decoder.container(keyedBy: AnyCodingKey.self)142 url = try c.decode(String.self, forKey: AnyCodingKey("url"))143 width = try? c.decodeIfPresent(Double.self, forKey: AnyCodingKey("width"))144 height = try? c.decodeIfPresent(Double.self, forKey: AnyCodingKey("height"))145 }146147 var isSafe: Bool { url.hasPrefix("/media/pro/") && !url.contains("..") && !url.contains("//") }148149 /// Adresse absolue, ou nil si l'image ne vient pas de `/media/pro/`.150 func absolute(base: URL) -> String? {151 guard isSafe else { return nil }152 var s = base.absoluteString153 while s.hasSuffix("/") { s.removeLast() }154 return s + url155 }156157 var aspect: CGFloat? {158 guard let w = width, let h = height, w > 0, h > 0 else { return nil }159 return CGFloat(w / h)160 }161}162163struct AnyCodingKey: CodingKey {164 var stringValue: String165 var intValue: Int? { nil }166 init(_ s: String) { stringValue = s }167 init?(stringValue: String) { self.stringValue = stringValue }168 init?(intValue: Int) { nil }169}170171private extension KeyedDecodingContainer where K == AnyCodingKey {172 func text(_ k: String) -> String? {173 guard let s = try? decodeIfPresent(String.self, forKey: AnyCodingKey(k)) else { return nil }174 let t = s.trimmingCharacters(in: .whitespacesAndNewlines)175 return t.isEmpty ? nil : t176 }177 /// Identifiant : une chaîne d'après le contrat ; un nombre est accepté et rendu en chaîne.178 func ident(_ k: String) -> String? { text(k) ?? Ms.decode(self, AnyCodingKey(k)).map { String($0) } }179 func flag(_ k: String) -> Bool { ((try? decodeIfPresent(Bool.self, forKey: AnyCodingKey(k))) ?? nil) ?? false }180 func image(_ k: String) -> MediaImage? { (try? decodeIfPresent(MediaImage.self, forKey: AnyCodingKey(k))) ?? nil }181 /// Tableau dont chaque élément illisible est ignoré.182 func list<T: Decodable>(_ k: String, of: T.Type = T.self) -> [T] {183 ((try? decodeIfPresent([Failable<T>].self, forKey: AnyCodingKey(k))) ?? nil)?.compactMap(\.value) ?? []184 }185}186187private struct Failable<T: Decodable>: Decodable {188 var value: T?189 init(from decoder: Decoder) throws { value = try? T(from: decoder) }190}191192/// `GET /courtiers/annonce/{uid}` : ce que la fiche d'une propriété montre de son courtier.193struct ListingBrokerInfo: Decodable, Sendable, Equatable {194 struct Broker: Decodable, Sendable, Equatable {195 var brokerID: String196 var name: String197 var agency: String?198 var verified: Bool199 var messaging: Bool200 var logo: MediaImage?201 var responseTime: String?202203 init(brokerID: String, name: String, agency: String? = nil, verified: Bool, messaging: Bool, logo: MediaImage? = nil, responseTime: String? = nil) {204 self.brokerID = brokerID; self.name = name; self.agency = agency; self.verified = verified; self.messaging = messaging; self.logo = logo; self.responseTime = responseTime205 }206207 init(from decoder: Decoder) throws {208 let c = try decoder.container(keyedBy: AnyCodingKey.self)209 // chaîne d'après le contrat ; un nombre (identifiant de l'annuaire) est accepté210 guard let i = c.ident("broker_id") else {211 throw DecodingError.dataCorrupted(.init(codingPath: decoder.codingPath, debugDescription: "courtier sans identifiant"))212 }213 brokerID = i214 name = c.text("name") ?? ""215 agency = c.text("agency")216 verified = c.flag("verified")217 messaging = c.flag("messaging")218 logo = c.image("logo")219 responseTime = c.text("response_time")220 }221222 /// On n'écrit qu'à un courtier vérifié qui a laissé sa messagerie ouverte.223 var canMessage: Bool { verified && messaging }224 }225226 var broker: Broker?227 var note: String?228229 init(broker: Broker?, note: String?) { self.broker = broker; self.note = note }230231 init(from decoder: Decoder) throws {232 let c = try decoder.container(keyedBy: AnyCodingKey.self)233 broker = (try? c.decodeIfPresent(Broker.self, forKey: AnyCodingKey("broker"))) ?? nil234 note = c.text("note")235 }236}237238/// Fiche publique d'un courtier (`GET /courtiers/{broker_id}/fiche`).239struct BrokerFiche: Decodable, Sendable, Equatable {240 struct Pair: Decodable, Sendable, Equatable, Identifiable {241 var title: String242 var text: String243 var id: String { title + "|" + text }244 }245 struct Member: Sendable, Equatable, Identifiable { var name: String; var role: String?; var photo: MediaImage?; var id: String { name + "|" + (role ?? "") } }246 struct Photo: Sendable, Equatable, Identifiable { var image: MediaImage; var caption: String?; var id: String { image.url + "|" + (caption ?? "") } }247 struct Hours: Sendable, Equatable, Identifiable { var days: String; var hours: String; var id: String { days + "|" + hours } }248 struct LinkItem: Sendable, Equatable, Identifiable { var label: String; var url: String; var id: String { label + "|" + url } }249250 struct Content: Decodable, Sendable, Equatable {251 var tagline: String?252 var about: String?253 var founded: Int?254 var languages: [String] = []255 var phone: String?256 var email: String?257 var website: String?258 var bookingURL: String?259 var address: String?260 var hours: [Hours] = []261 var social: [LinkItem] = []262 var highlights: [Pair] = []263 var services: [String] = []264 var policies: [Pair] = []265 var faq: [Pair] = []266 var team: [Member] = []267 var logo: MediaImage?268 var cover: MediaImage?269 var gallery: [Photo] = []270 var responseTime: String?271272 init() {}273274 init(from decoder: Decoder) throws {275 let c = try decoder.container(keyedBy: AnyCodingKey.self)276 tagline = c.text("tagline"); about = c.text("about")277 founded = (try? c.decodeIfPresent(Int.self, forKey: AnyCodingKey("founded"))) ?? nil278 languages = c.list("languages", of: String.self).filter { !$0.isEmpty }279 services = c.list("services", of: String.self).filter { !$0.isEmpty }280 logo = c.image("logo"); cover = c.image("cover")281 if let k = try? c.nestedContainer(keyedBy: AnyCodingKey.self, forKey: AnyCodingKey("contact")) {282 phone = k.text("phone"); email = k.text("email"); website = k.text("website")283 bookingURL = k.text("booking_url"); address = k.text("address")284 hours = k.list("hours", of: [String: String].self).compactMap { d in285 guard let days = d["days"], let h = d["hours"], !days.isEmpty || !h.isEmpty else { return nil }286 return Hours(days: days, hours: h)287 }288 }289 if let s = (try? c.decodeIfPresent([String: String].self, forKey: AnyCodingKey("social"))) ?? nil {290 let names = ["facebook": "Facebook", "instagram": "Instagram", "linkedin": "LinkedIn", "youtube": "YouTube", "tiktok": "TikTok", "x": "X"]291 social = ["facebook", "instagram", "linkedin", "youtube", "tiktok", "x"].compactMap { k in292 guard let u = s[k], !u.isEmpty, let n = names[k] else { return nil }293 return LinkItem(label: n, url: u)294 }295 }296 func pairs(_ key: String, _ a: String, _ b: String) -> [Pair] {297 c.list(key, of: [String: String].self).compactMap { d in298 guard let t = d[a], let x = d[b], !t.isEmpty, !x.isEmpty else { return nil }299 return Pair(title: t, text: x)300 }301 }302 highlights = pairs("highlights", "label", "value")303 policies = pairs("policies", "title", "text")304 faq = pairs("faq", "q", "a")305 struct RawMember: Decodable { var name: String?; var role: String?; var photo: MediaImage?306 init(from d: Decoder) throws {307 let c = try d.container(keyedBy: AnyCodingKey.self)308 name = c.text("name"); role = c.text("role"); photo = c.image("photo")309 } }310 team = c.list("team", of: RawMember.self).compactMap { m in m.name.map { Member(name: $0, role: m.role, photo: m.photo) } }311 struct RawPhoto: Decodable { var image: MediaImage?; var caption: String?312 init(from d: Decoder) throws {313 let c = try d.container(keyedBy: AnyCodingKey.self)314 image = c.image("image"); caption = c.text("caption")315 } }316 gallery = c.list("gallery", of: RawPhoto.self).compactMap { p in p.image.flatMap { $0.isSafe ? Photo(image: $0, caption: p.caption) : nil } }317 if let m = try? c.nestedContainer(keyedBy: AnyCodingKey.self, forKey: AnyCodingKey("messaging")) { responseTime = m.text("response_time") }318 }319320 /// Paragraphes de la présentation : les retours à la ligne séparent les paragraphes.321 var aboutParagraphs: [String] { BrokerFiche.paragraphs(about) }322 }323324 var brokerID: String325 var verified: Bool326 var messaging: Bool327 var content: Content?328329 init(brokerID: String, verified: Bool, messaging: Bool, content: Content?) {330 self.brokerID = brokerID; self.verified = verified; self.messaging = messaging; self.content = content331 }332333 init(from decoder: Decoder) throws {334 let c = try decoder.container(keyedBy: AnyCodingKey.self)335 brokerID = c.ident("broker_id") ?? ""336 verified = c.flag("verified")337 messaging = c.flag("messaging")338 content = (try? c.decodeIfPresent(Content.self, forKey: AnyCodingKey("content"))) ?? nil339 }340341 var canMessage: Bool { verified && messaging }342343 static func paragraphs(_ text: String?) -> [String] {344 (text ?? "").components(separatedBy: .newlines).map { $0.trimmingCharacters(in: .whitespaces) }.filter { !$0.isEmpty }345 }346}347348// MARK: - Messagerie349350/// Un message d'une conversation. `role` : `acheteur`, `courtier` ou `systeme` (réponse automatique).351struct ChatMessage: Decodable, Sendable, Equatable, Identifiable {352 var id: Int64353 var role: String354 var author: String355 var text: String356 var createdAt: Int64357 var mine: Bool358359 init(id: Int64, role: String, author: String = "", text: String, createdAt: Int64 = 0, mine: Bool = false) {360 self.id = id; self.role = role; self.author = author; self.text = text; self.createdAt = createdAt; self.mine = mine361 }362363 init(from decoder: Decoder) throws {364 let c = try decoder.container(keyedBy: AnyCodingKey.self)365 id = Ms.decode(c, AnyCodingKey("id")) ?? 0366 role = (try? c.decodeIfPresent(String.self, forKey: AnyCodingKey("role"))) ?? "courtier"367 author = (try? c.decodeIfPresent(String.self, forKey: AnyCodingKey("author"))) ?? ""368 text = (try? c.decodeIfPresent(String.self, forKey: AnyCodingKey("text"))) ?? ""369 createdAt = Ms.decode(c, AnyCodingKey("created_at")) ?? 0370 mine = c.flag("mine")371 }372373 /// Réponse automatique du courtier : présentée comme telle, jamais comme un message écrit à la main.374 var isAutomatic: Bool { role == "systeme" }375}376377struct Conversation: Decodable, Sendable, Equatable, Identifiable {378 var id: String379 var brokerID: String380 var brokerName: String381 var uid: String?382 var listing: FavoriteSnapshot?383 var updatedAt: Int64384 var lastMessage: String385 var lastRole: String?386 var status: String387 var unread: Bool388 var archived: Bool389 var canReply: Bool?390 /// pour un courtier seulement391 var tenantName: String?392393 init(id: String, brokerID: String = "", brokerName: String = "", uid: String? = nil, listing: FavoriteSnapshot? = nil, updatedAt: Int64 = 0,394 lastMessage: String = "", lastRole: String? = nil, status: String = "ouverte", unread: Bool = false, archived: Bool = false,395 canReply: Bool? = nil, tenantName: String? = nil) {396 self.id = id; self.brokerID = brokerID; self.brokerName = brokerName; self.uid = uid; self.listing = listing; self.updatedAt = updatedAt397 self.lastMessage = lastMessage; self.lastRole = lastRole; self.status = status; self.unread = unread; self.archived = archived398 self.canReply = canReply; self.tenantName = tenantName399 }400401 init(from decoder: Decoder) throws {402 let c = try decoder.container(keyedBy: AnyCodingKey.self)403 id = try c.decode(String.self, forKey: AnyCodingKey("id"))404 brokerID = c.ident("broker_id") ?? ""405 brokerName = c.text("broker_name") ?? ""406 uid = c.text("uid")407 listing = (try? c.decodeIfPresent(FavoriteSnapshot.self, forKey: AnyCodingKey("listing"))) ?? nil408 updatedAt = Ms.decode(c, AnyCodingKey("updated_at")) ?? Ms.decode(c, AnyCodingKey("created_at")) ?? 0409 lastMessage = (try? c.decodeIfPresent(String.self, forKey: AnyCodingKey("last_message"))) ?? ""410 lastRole = c.text("last_role")411 status = c.text("status") ?? "ouverte"412 unread = c.flag("unread")413 archived = c.flag("archived")414 canReply = (try? c.decodeIfPresent(Bool.self, forKey: AnyCodingKey("can_reply"))) ?? nil415 tenantName = c.text("tenant_name")416 }417418 var isClosed: Bool { status == "fermee" }419 var isBlocked: Bool { status == "bloquee" }420 /// Peut-on répondre ? `can_reply` du serveur fait foi ; à défaut, l'état de la conversation.421 var acceptsReplies: Bool { canReply ?? (status == "ouverte") }422423 /// Interlocuteur à afficher : l'acheteur pour un courtier, le courtier pour un acheteur.424 func counterpart(forBroker: Bool) -> String {425 if forBroker { return tenantName ?? "Acheteur" }426 return brokerName.isEmpty ? "Courtier" : brokerName427 }428429 /// « Maison · Gatineau » : la propriété dont on parle, d'après l'aperçu envoyé à l'ouverture.430 var listingLine: String? {431 guard let l = listing else { return nil }432 let parts = [l.propertyType, l.title == l.propertyType ? nil : l.title, l.city].compactMap { $0 }.filter { !$0.isEmpty }433 return parts.isEmpty ? nil : parts.joined(separator: " · ")434 }435}436437struct ConversationList: Decodable, Sendable {438 var items: [Conversation]439 var unread: Int440 init(from decoder: Decoder) throws {441 let c = try decoder.container(keyedBy: AnyCodingKey.self)442 items = c.list("items", of: Conversation.self)443 unread = ((try? c.decodeIfPresent(Int.self, forKey: AnyCodingKey("unread"))) ?? nil) ?? 0444 }445}446447struct ConversationThread: Decodable, Sendable {448 var conversation: Conversation449 var messages: [ChatMessage]450 var created: Bool?451 init(from decoder: Decoder) throws {452 let c = try decoder.container(keyedBy: AnyCodingKey.self)453 conversation = try c.decode(Conversation.self, forKey: AnyCodingKey("conversation"))454 messages = c.list("messages", of: ChatMessage.self)455 created = (try? c.decodeIfPresent(Bool.self, forKey: AnyCodingKey("created"))) ?? nil456 }457}458459struct UnreadCount: Decodable, Sendable { var unread: Int }460struct MessageEnvelope: Decodable, Sendable { var message: ChatMessage }461struct ConversationEnvelope: Decodable, Sendable { var conversation: Conversation }462463extension Listing {464 /// Aperçu de la propriété jointe à un message (mêmes champs que l'aperçu d'un favori).465 var snapshot: FavoriteSnapshot {466 func t(_ s: String) -> String? { s.isEmpty ? nil : String(s.prefix(300)) }467 return FavoriteSnapshot(title: t(displayTitle), address: t(address), city: t(cleanCity), sector: t(sector), propertyType: t(kind),468 price: plausiblePrice, image: images.first.flatMap(t), source: t(source), areaSqft: areaSqft,469 lat: coordinate?.latitude, lng: coordinate?.longitude)470 }471}472