SPB Git

Repository Public

MessagingTests.swift 29.0 KB 383 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : Lou-Ka iOS9// File             : LouKaTests/MessagingTests.swift10// Description      : gestionnaires vérifiés et messagerie — client contre un11//                    serveur simulé (`URLProtocol`), règles de relève et de12//                    non-lus, garde de rôle, fil d'une conversation, décodage13//                    des réponses réelles de la préproduction (2026-11-30),14//                    liens.15// Module           : LouKaTests16// 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 Foundation94import Testing95@testable import LouKa9697private let base = URL(string: "https://compte.test")!98private func api(token: String? = "jeton-1") -> AccountAPI { AccountAPI(session: StubServer.session(), base: { base }, token: { token }) }99100private let annonceJSON = #"{"uid":"cogir:73-studio","manager":{"source_id":"cogir","name":"Cogir Immobilier","verified":true,"messaging":true,"logo":{"url":"/media/pro/cogir/172ab1c42bf0506ff203d261.webp","width":240,"height":240},"response_time":"moins de 24 heures"},"note":"Visites sur rendez-vous le samedi. Premier mois offert pour un bail signé avant le 15 décembre."}"#101private let ficheJSON = #"{"source_id":"cogir","verified":true,"messaging":true,"content":{"tagline":"Des logements bien tenus, partout au Québec","about":"Premier paragraphe.\n\nDeuxième paragraphe avec du <b>balisage</b> et un [lien](https://exemple.test) qui doivent rester du texte.","founded":1995,"languages":["Français","English"],"contact":{"phone":"514 555-0100","email":"info@cogir.net","website":"https://www.cogir.net","booking_url":"javascript:alert(1)","address":"7250, boul. Taschereau, Brossard","hours":[{"days":"Lun-ven","hours":"9 h à 17 h"},{"days":"Samedi","hours":"10 h à 16 h"}]},"social":{"facebook":"https://www.facebook.com/cogir","linkedin":"https://www.linkedin.com/company/cogir","x":"ftp://pas-un-lien"},"highlights":[{"label":"Immeubles","value":"42"},{"label":"Logements","value":"3 800"}],"services":["Entretien 24 h","Portail des locataires"],"policies":[{"title":"Animaux","text":"Chats acceptés."}],"faq":[{"q":"Le chauffage est-il inclus ?","a":"Dans la majorité des immeubles, oui."}],"team":[{"name":"Essai Gestion","role":"Location","photo":null}],"logo":{"url":"/media/pro/cogir/logo.webp","width":240,"height":240},"cover":{"url":"/media/pro/cogir/couv.webp","width":1200,"height":480},"gallery":[{"image":{"url":"/media/pro/cogir/a.webp","width":1200,"height":480},"caption":"Le hall d'entrée"},{"image":{"url":"https://ailleurs.test/x.png"},"caption":"refusée"}],"messaging":{"enabled":true,"response_time":"moins de 24 heures"},"champ_futur":{"x":1}},"published_at":1796081673}"#102private func conversationJSON(unread: Bool = false, status: String = "ouverte", extra: String = "") -> String {103    #"{"id":"c12d","source_id":"cogir","manager_name":"Cogir Immobilier","uid":"cogir:73-studio","listing":{"title":"Studio lumineux","city":"Montréal","price":1200,"unit_type":"Studio","source":"cogir"},"created_at":1796082175064,"updated_at":1796082175146,"last_message":"Oui, il est libre.","last_role":"gestionnaire","messages":3,"status":"\#(status)","unread":\#(unread),"archived":false\#(extra)}"#104}105private func messageJSON(_ id: Int, _ role: String, _ text: String, mine: Bool = false) -> String {106    #"{"id":\#(id),"role":"\#(role)","author":"\#(role == "locataire" ? "Léa" : "Cogir Immobilier")","text":"\#(text)","created_at":\#(1_796_082_175_000 + id),"mine":\#(mine)}"#107}108private func threadJSON(_ messages: [String], status: String = "ouverte", canReply: Bool = true) -> String {109    #"{"conversation":\#(conversationJSON(status: status, extra: #","can_reply":\#(canReply)"#)),"messages":[\#(messages.joined(separator: ","))],"server_time":1796082175433,"created":true}"#110}111112private let tenant = AccountUser(id: "u1", email: "lea@example.org", name: "Léa", role: "locataire")113private func manager(_ status: String, source: String? = "cogir", reason: String? = nil) -> AccountUser {114    AccountUser(id: "g1", email: "g@cogir.net", name: "Essai Gestion", role: "gestionnaire", manager: ManagerAccess(sourceID: source, company: "Cogir Immobilier", status: status, reason: reason))115}116117extension StubbedAccountTests {118@Suite("Messagerie : client d'API")119struct MessagingAPITests {120    @Test("gestionnaire d'un logement : route publique sans jeton, uid tel quel, pastille, mot, logo ; rien quand manager est nul")121    func listingManager() async throws {122        StubServer.install { r in r.path.contains("kangalou") ? .json(#"{"uid":"kangalou:1","manager":null,"note":""}"#) : .json(annonceJSON) }123        let info = try await api().listingManager(uid: "cogir:73-studio")124        let r = try #require(StubServer.seen.first)125        #expect(r.method == "GET" && r.url == "https://compte.test/api/v3/gestionnaires/annonce/cogir:73-studio")126        #expect(r.headers["Authorization"] == nil && r.headers["X-LouKa-Client"] == "ios", "route publique : le jeton n'est pas envoyé")127        let m = try #require(info.manager)128        #expect(m.sourceID == "cogir" && m.name == "Cogir Immobilier" && m.verified && m.messaging && m.canMessage && m.responseTime == "moins de 24 heures")129        #expect(m.logo?.absolute(base: URL(string: "https://www.lou-ka.com/")!) == "https://www.lou-ka.com/media/pro/cogir/172ab1c42bf0506ff203d261.webp")130        #expect(info.note?.hasPrefix("Visites sur rendez-vous") == true)131        let none = try await api().listingManager(uid: "kangalou:1")132        #expect(none.manager == nil && none.note == nil, "une note vide n'est pas un mot du gestionnaire")133        let unverified = try JSONDecoder().decode(ListingManagerInfo.self, from: Data(#"{"manager":{"source_id":"x","name":"X","verified":false,"messaging":true}}"#.utf8))134        #expect(unverified.manager?.canMessage == false, "on n'écrit qu'à un gestionnaire vérifié")135    }136137    @Test("fiche publique : une vue comptée par ouverture, contenu décodé, champs inconnus ignorés, images et liens filtrés")138    func fiche() async throws {139        StubServer.install { _ in .json(ficheJSON) }140        let f = try await api().managerFiche(sourceID: "cogir", countView: true)141        #expect(StubServer.seen.first?.url == "https://compte.test/api/v3/gestionnaires/cogir/fiche?vue=1" && StubServer.seen.first?.headers["Authorization"] == nil)142        _ = try await api().managerFiche(sourceID: "cogir", countView: false)143        #expect(StubServer.seen.last?.url == "https://compte.test/api/v3/gestionnaires/cogir/fiche")144        let c = try #require(f.content)145        #expect(f.verified && f.messaging && f.canMessage && c.tagline == "Des logements bien tenus, partout au Québec" && c.founded == 1995)146        #expect(c.aboutParagraphs.count == 2 && c.aboutParagraphs[1].contains("<b>balisage</b>") && c.aboutParagraphs[1].contains("[lien](https://exemple.test)"),147                "le texte d'un tiers reste du texte : balises et Markdown ne sont pas interprétés")148        #expect(c.languages == ["Français", "English"] && c.services.count == 2 && c.phone == "514 555-0100" && c.address?.hasPrefix("7250") == true)149        #expect(c.hours.map(\.days) == ["Lun-ven", "Samedi"] && c.highlights.map(\.text) == ["42", "3 800"] && c.policies.first?.title == "Animaux")150        #expect(c.faq.first?.title == "Le chauffage est-il inclus ?" && c.team.first?.name == "Essai Gestion" && c.team.first?.photo == nil)151        #expect(c.gallery.count == 1 && c.gallery[0].caption == "Le hall d'entrée", "une image qui ne vient pas de /media/pro/ n'est pas affichée")152        #expect(c.cover?.aspect == 2.5 && c.responseTime == "moins de 24 heures")153        #expect(ExternalLink(c.website) != nil && ExternalLink(c.bookingURL) == nil, "un lien ne s'ouvre que s'il commence par http:// ou https://")154        #expect(c.social.map(\.label) == ["Facebook", "LinkedIn", "X"] && c.social.filter { ExternalLink($0.url) != nil }.count == 2)155        for bad in ["https://x.test/a.png", "/autre/a.png", "/media/pro/../secret", "//x.test/media/pro/a"] { #expect(MediaImage(url: bad).absolute(base: base) == nil, "\(bad)") }156        let bare = try JSONDecoder().decode(ManagerFiche.self, from: Data(#"{"source_id":"x","verified":true,"messaging":false,"content":null}"#.utf8))157        #expect(bare.verified && bare.content == nil && !bare.canMessage)158    }159160    @Test("ouvrir une conversation : uid, text et listing (aperçu d'un favori) ; ou source_id et text ; jeton Bearer")161    func open() async throws {162        StubServer.install { _ in .json(threadJSON([messageJSON(7, "locataire", "Bonjour", mine: true), messageJSON(8, "systeme", "Merci de votre message.")]), status: 201) }163        let t = try await api().openConversation(uid: "cogir:73-studio", sourceID: "cogir", text: "Bonjour", listing: FavoriteSnapshot(title: "Studio lumineux", city: "Montréal", unitType: "Studio", price: 1200, source: "cogir"))164        let r = try #require(StubServer.seen.first)165        #expect(r.method == "POST" && r.url == "https://compte.test/api/v3/messagerie" && r.headers["Authorization"] == "Bearer jeton-1" && r.headers["X-LouKa-Client"] == "ios")166        #expect(r.json["uid"] as? String == "cogir:73-studio" && r.json["text"] as? String == "Bonjour" && r.json["source_id"] == nil)167        let l = try #require(r.json["listing"] as? [String: Any])168        #expect(l["title"] as? String == "Studio lumineux" && l["unit_type"] as? String == "Studio" && l["price"] as? Double == 1200 && l["source"] as? String == "cogir")169        #expect(t.created == true && t.conversation.id == "c12d" && t.conversation.acceptsReplies && t.messages.count == 2)170        #expect(t.messages[0].mine && !t.messages[0].isAutomatic && t.messages[1].isAutomatic, "le message « systeme » est la réponse automatique")171        #expect(t.conversation.listingLine == "Studio · Studio lumineux · Montréal" && t.conversation.counterpart(forManager: false) == "Cogir Immobilier")172        _ = try await api().openConversation(uid: nil, sourceID: "cogir", text: "Bonjour", listing: FavoriteSnapshot(title: "ignoré"))173        let r2 = try #require(StubServer.seen.last)174        #expect(r2.json["source_id"] as? String == "cogir" && r2.json["uid"] == nil && r2.json["listing"] == nil)175    }176177    @Test("boîte, archives, non-lus, fil et relève par ?apres=, réponse, archiver, fermer, effacer, signaler")178    func routes() async throws {179        StubServer.install { r in180            if r.path.hasSuffix("/non-lus") { return .json(#"{"unread":2}"#) }181            if r.path.hasSuffix("/messagerie") { return .json(#"{"items":[\#(conversationJSON(unread: true, extra: #","tenant_name":"Léa""#)),{"illisible":true}],"unread":1,"server_time":1}"#) }182            if r.path.hasSuffix("/messages") { return .json(#"{"message":\#(messageJSON(10, "locataire", "Parfait", mine: true))}"#, status: 201) }183            if r.path.hasSuffix("/signalement") { return .json(#"{"status":"signalement_recu"}"#, status: 202) }184            if r.method == "DELETE" { return .noContent }185            if r.method == "PATCH" { return .json(#"{"conversation":\#(conversationJSON(status: r.json["status"] as? String ?? "ouverte", extra: #","can_reply":false"#)),"messages":[]}"#) }186            return .json(threadJSON([messageJSON(9, "gestionnaire", "Oui, il est libre.")]))187        }188        let a = api()189        let list = try await a.conversations()190        #expect(list.items.count == 1 && list.unread == 1 && list.items[0].unread && list.items[0].tenantName == "Léa", "un élément illisible est ignoré")191        #expect(list.items[0].counterpart(forManager: true) == "Léa")192        _ = try await a.conversations(archived: true)193        #expect(StubServer.seen.last?.url == "https://compte.test/api/v3/messagerie?archives=1")194        #expect(try await a.unreadCount() == 2)195        _ = try await a.thread("c12d")196        #expect(StubServer.seen.last?.url == "https://compte.test/api/v3/messagerie/c12d")197        let after = try await a.thread("c12d", after: 8)198        #expect(StubServer.seen.last?.url == "https://compte.test/api/v3/messagerie/c12d?apres=8" && after.messages.map(\.id) == [9])199        let sent = try await a.reply("c12d", text: "Parfait")200        #expect(sent.id == 10 && sent.mine && StubServer.seen.last?.url == "https://compte.test/api/v3/messagerie/c12d/messages" && StubServer.seen.last?.json["text"] as? String == "Parfait")201        _ = try await a.setArchived("c12d", true)202        #expect(StubServer.seen.last?.method == "PATCH" && StubServer.seen.last?.json["archived"] as? Bool == true && StubServer.seen.last?.json["status"] == nil)203        let closed = try await a.closeConversation("c12d")204        #expect(StubServer.seen.last?.json["status"] as? String == "fermee" && StubServer.seen.last?.json["archived"] == nil && closed.isClosed && !closed.acceptsReplies)205        try await a.report("c12d", reason: "Pourriel ou sollicitation : essai", messageID: 9)206        #expect(StubServer.seen.last?.path == "/api/v3/messagerie/c12d/signalement" && StubServer.seen.last?.json["reason"] as? String == "Pourriel ou sollicitation : essai" && StubServer.seen.last?.json["message_id"] as? Int == 9)207        try await a.deleteConversation("c12d")208        #expect(StubServer.seen.last?.method == "DELETE" && StubServer.seen.last?.url == "https://compte.test/api/v3/messagerie/c12d")209        #expect(StubServer.seen.allSatisfy { $0.headers["Authorization"] == "Bearer jeton-1" })210    }211212    @Test("erreurs de la messagerie : message du serveur ; un 404 JSON est une vraie réponse, pas un serveur sans la route")213    func errors() async throws {214        func failure(_ r: StubResponse) async -> AccountError? {215            StubServer.install { _ in r }216            do { _ = try await api().thread("x"); return nil } catch { return error as? AccountError }217        }218        let unreachable = await failure(.error(409, "gestionnaire_non_joignable", "Ce gestionnaire ne reçoit pas de messages sur Lou-Ka."))219        #expect(unreachable?.code == "gestionnaire_non_joignable" && unreachable?.errorDescription == "Ce gestionnaire ne reçoit pas de messages sur Lou-Ka.")220        let closed = await failure(.error(403, "conversation_fermee", "Cette conversation est fermée."))221        #expect(closed?.code == "conversation_fermee" && closed?.isUnauthenticated == false)222        let gone = await failure(.error(404, "not_found", "Conversation introuvable"))223        #expect(gone?.isNotFound == true && gone?.errorDescription == "Conversation introuvable")224        #expect(await failure(StubResponse(status: 404, body: Data("<!doctype html>".utf8))) == .unavailable, "production sans la messagerie")225        let limited = await failure(.error(429, "trop_de_tentatives", "Trop de messages envoyés.", headers: ["Retry-After": "120"]))226        #expect(limited?.errorDescription == "Trop de messages envoyés. Délai d'attente : 2 min.")227    }228}229230@Suite("Messagerie : relève, non-lus, rôle, fil")231@MainActor232struct MessagingStateTests {233    private func messaging(_ user: AccountUser?) -> (Messaging, Counter) {234        let m = Messaging(api: api())235        let ended = Counter()236        m.user = { user }237        m.onUnauthenticated = { _ = ended.next() }238        return (m, ended)239    }240241    @Test("pastille : jamais sans session ni à l'arrière-plan, une fois par minute au plus, remise à zéro à la déconnexion")242    func unread() async throws {243        StubServer.install { _ in .json(#"{"unread":3}"#) }244        let (none, _) = messaging(nil)245        await none.refreshUnread(active: true)246        let (m, _) = messaging(tenant)247        await m.refreshUnread(active: false)248        #expect(StubServer.seen.isEmpty && m.unread == 0, "ni visiteur ni arrière-plan n'interrogent le serveur")249        let t0 = Date()250        await m.refreshUnread(active: true, now: t0)251        #expect(m.unread == 3 && StubServer.seen.count == 1)252        await m.refreshUnread(active: true, now: t0.addingTimeInterval(59))253        #expect(StubServer.seen.count == 1, "pas deux lectures en moins d'une minute")254        await m.refreshUnread(active: true, now: t0.addingTimeInterval(61))255        #expect(StubServer.seen.count == 2)256        m.reset()257        #expect(m.unread == 0 && m.lastUnreadCheck == nil)258    }259260    @Test("garde de rôle : un gestionnaire n'ouvre pas de conversation ; sans accès approuvé il n'interroge rien")261    func roles() async throws {262        StubServer.install { _ in .json(#"{"unread":1}"#) }263        #expect(tenant.canUseMessaging && tenant.canStartConversation && !tenant.isManager)264        #expect(!AccountUser(id: "u", email: "a@example.org", verified: false, role: "locataire").canUseMessaging, "adresse non confirmée")265        #expect(manager("approuve").canUseMessaging && !manager("approuve").canStartConversation)266        for s in ["en_attente", "refuse", "suspendu", "etat_inconnu"] { #expect(!manager(s).canUseMessaging, "\(s)") }267        #expect(manager("approuve", source: nil).manager?.state == .pending && !manager("approuve", source: "").canUseMessaging, "approuvé sans entreprise rattachée = attente")268        #expect(manager("suspendu", reason: "Compte signalé").manager?.state == .suspended)269        #expect(MessagingPolicy.canPoll(user: manager("approuve"), active: true) && !MessagingPolicy.canPoll(user: manager("en_attente"), active: true))270        let (pending, _) = messaging(manager("en_attente"))271        await pending.refreshUnread(active: true)272        #expect(StubServer.seen.isEmpty)273        let (approved, _) = messaging(manager("approuve"))274        let target = ComposeTarget(uid: nil, sourceID: "cogir", managerName: "Cogir", listing: nil)275        do { _ = try await approved.open(target, text: "Bonjour"); Issue.record("un gestionnaire ne doit pas pouvoir ouvrir une conversation") } catch let e as AccountError {276            #expect(e.code == "reserve_aux_locataires")277        }278        #expect(StubServer.seen.isEmpty, "le refus se fait sans appel au serveur")279        let (t, _) = messaging(tenant)280        do { _ = try await t.open(target, text: "  \n "); Issue.record("message vide") } catch let e as AccountError { #expect(e.code == "message_vide") }281        #expect(StubServer.seen.isEmpty)282        // décodage du compte : l'accès du gestionnaire et son motif283        let u = try JSONDecoder().decode(AccountUser.self, from: Data(#"{"id":"g","email":"g@cogir.net","name":"G","verified":true,"role":"gestionnaire","manager":{"source_id":"cogir","company":"Cogir Immobilier","website":"https://www.cogir.net","status":"refuse","reason":"Adresse non reconnue","requested_at":1,"decided_at":2}}"#.utf8))284        #expect(u.isManager && u.manager?.state == .refused && u.manager?.reason == "Adresse non reconnue" && u.manager?.company == "Cogir Immobilier")285        #expect(try JSONDecoder().decode(AccountUser.self, from: JSONEncoder().encode(u)) == u, "la fiche gardée au trousseau se relit avec l'accès")286    }287288    @Test("règles pures : fusion sans doublon, curseur, texte borné à 4 000, message proposé, brouillon gardé 30 minutes")289    func policy() {290        let a = ChatMessage(id: 7, role: "locataire", text: "a", mine: true), b = ChatMessage(id: 8, role: "systeme", text: "b"), c = ChatMessage(id: 9, role: "gestionnaire", text: "c")291        #expect(MessagingPolicy.merge([a, b], [c, b]).map(\.id) == [7, 8, 9] && MessagingPolicy.merge([c], [a]).map(\.id) == [7, 9])292        #expect(MessagingPolicy.cursor([a, c, b]) == 9 && MessagingPolicy.cursor([]) == nil)293        #expect(MessagingPolicy.clean("  \n") == nil && MessagingPolicy.clean(" Bonjour \n") == "Bonjour")294        #expect(MessagingPolicy.clean(String(repeating: "é", count: 4100))?.count == 4000)295        #expect(MessagingPolicy.prefill(listingTitle: "4½ lumineux").contains("4½ lumineux") && !MessagingPolicy.prefill(listingTitle: nil).isEmpty)296        #expect((15...20).contains(MessagingPolicy.threadInterval) && MessagingPolicy.unreadInterval == 60)297        #expect(!MessagingPolicy.shouldRefreshUnread(user: nil, active: true, last: nil) && MessagingPolicy.shouldRefreshUnread(user: tenant, active: true, last: nil))298        let m = Messaging(api: api())299        let target = ComposeTarget(uid: "cogir:1", sourceID: "cogir", managerName: "Cogir", listing: FavoriteSnapshot(title: "Studio"))300        #expect(target.listingTitle == "Studio" && m.takeDraft() == nil)301        let t0 = Date()302        m.keepDraft(target, text: "Mon message", now: t0)303        #expect(m.takeDraft(now: t0.addingTimeInterval(29 * 60))?.text == "Mon message")304        #expect(m.takeDraft(now: t0) == nil, "le brouillon n'est rendu qu'une fois")305        m.keepDraft(target, text: "Trop vieux", now: t0)306        #expect(m.takeDraft(now: t0.addingTimeInterval(31 * 60)) == nil, "au-delà de 30 minutes, le brouillon est oublié")307        m.keepDraft(target, text: "x", now: t0); m.reset()308        #expect(m.takeDraft(now: t0) == nil, "la déconnexion efface le brouillon")309    }310311    @Test("fil : chargement, relève des seuls nouveaux messages, pas de relève à l'arrière-plan, réponse, conversation fermée ou effacée")312    func thread() async throws {313        let step = Counter()314        StubServer.install { r in315            if r.path.hasSuffix("/non-lus") { return .json(#"{"unread":0}"#) }316            if r.method == "POST" { return step.next() == 1 ? .json(#"{"message":\#(messageJSON(10, "locataire", "Parfait", mine: true))}"#, status: 201) : .error(403, "conversation_fermee", "Cette conversation est fermée.") }317            if r.url.contains("apres=8") { return .json(threadJSON([messageJSON(9, "gestionnaire", "Oui, il est libre.")])) }318            if r.url.contains("apres=10") { return .error(404, "not_found", "Conversation introuvable") }319            return .json(threadJSON([messageJSON(7, "locataire", "Bonjour", mine: true), messageJSON(8, "systeme", "Merci de votre message.")]))320        }321        let (m, _) = messaging(tenant)322        let model = ThreadModel(id: "c12d", messaging: m)323        #expect(model.loading)324        await model.load()325        #expect(!model.loading && model.messages.map(\.id) == [7, 8] && model.conversation?.acceptsReplies == true && model.failure == nil)326        let before = StubServer.seen.count327        await model.poll(active: false)328        #expect(StubServer.seen.count == before, "pas de relève quand l'app n'est pas au premier plan")329        await model.poll(active: true)330        #expect(StubServer.seen.last?.url.hasSuffix("/messagerie/c12d?apres=8") == true && model.messages.map(\.id) == [7, 8, 9])331        #expect(await model.send("Parfait") == nil && model.messages.map(\.id) == [7, 8, 9, 10])332        #expect(await model.send("Encore") == "Cette conversation est fermée." && model.conversation?.acceptsReplies == false && model.conversation?.isClosed == true)333        await model.poll(active: true)334        #expect(model.gone, "la conversation a été effacée ailleurs")335        let n = StubServer.seen.count336        await model.poll(active: true)337        #expect(StubServer.seen.count == n, "plus de relève une fois la conversation disparue")338    }339340    @Test("401 non_authentifie dans la messagerie : la session se ferme ; un gestionnaire connecté ne synchronise pas de favoris")341    func session() async throws {342        StubServer.install { _ in .error(401, "non_authentifie", "Connectez-vous pour continuer.") }343        let (m, ended) = messaging(tenant)344        await #expect(throws: AccountError.self) { _ = try await m.conversations(archived: false) }345        #expect(ended.next() == 2, "la fermeture de session a été demandée une fois")346347        StubServer.install { r in348            if r.path.hasSuffix("/connexion") { return .json(#"{"user":{"id":"g1","email":"g@cogir.net","name":"Essai Gestion","verified":true,"role":"gestionnaire","manager":{"source_id":"cogir","company":"Cogir Immobilier","status":"approuve"}},"session":{"token":"jeton-g"}}"#) }349            if r.path.hasSuffix("/non-lus") { return .json(#"{"unread":4}"#) }350            return .json("{}")351        }352        let library = Library(inMemory: true)353        let account = Account(library: library, store: MemoryStore(), session: StubServer.session(), base: { base }, defaults: nil)354        try await account.signIn(email: "g@cogir.net", password: "x")355        #expect(account.user?.isManager == true && account.messaging.unread == 4)356        #expect(StubServer.seen("POST", "/favoris/synchronisation").isEmpty && StubServer.seen("POST", "/recherches/synchronisation").isEmpty,357                "les favoris d'un compte de gestionnaire ne partent pas")358        await account.signOut()359        #expect(account.messaging.unread == 0)360    }361}362}363364@Suite("Messagerie : liens")365struct MessagingLinkTests {366    @Test("lien des courriels d'avis : /compte/messages/{id} ouvre le fil")367    func links() {368        #expect(DeepLink(url: URL(string: "https://www.lou-ka.com/compte/messages/c12d6d162b07a7c0401fd37b")!) == .route(.conversation("c12d6d162b07a7c0401fd37b"), .favorites))369        #expect(DeepLink(url: URL(string: "https://www.lou-ka.com/pro/messages/abc")!) == .route(.conversation("abc"), .favorites))370        #expect(DeepLink(url: URL(string: "https://www.lou-ka.com/compte/messages")!) == .route(.messages, .favorites))371        #expect(DeepLink(url: URL(string: "louka://compte/messages/abc")!) == .route(.conversation("abc"), .favorites))372        #expect(DeepLink(url: URL(string: "https://www.lou-ka.com/compte")!) == .route(.account, .favorites))373        #expect(DeepLink(url: URL(string: "https://www.lou-ka.com/compte/messages/a/b")!) == nil && DeepLink(url: URL(string: "https://www.lou-ka.com/pro")!) == nil)374        #expect(DeepLink(url: URL(string: "https://ailleurs.test/compte/messages/abc")!) == nil)375    }376377    @Test("aperçu du logement joint à un message : mêmes champs que l'aperçu d'un favori")378    func snapshot() throws {379        let l = try JSONDecoder().decode(Listing.self, from: Data(#"{"uid":"cogir:1","source":"cogir","title":"Studio lumineux","address":"1, rue X","city":"Montréal","sector":"Rosemont","unit_type":"Studio","price":1200,"images":["https://img.example.org/a.jpg"],"lat":45.5,"lng":-73.6,"area_sqft":400}"#.utf8))380        #expect(l.snapshot == FavoriteItem(listing: l).snapshot)381    }382}383
Files main
Menu

Theme