SPB Git

Repository Public

NextFixtures.swift 20.0 KB 265 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Sources/Shared/Next/NextFixtures.swift3// Description: DEBUG-only fixtures for design captures of the SP Mail Next screens, against the LOCAL dev backend and its staging mailboxes:4// `-spmScene next.seed` creates real content once (messages with attachments, labels, a pin, a snooze, a reminder, contacts, a saved5// search); `-spmScene next.<screen>` then opens one screen. Compiled out of Release.6#if DEBUG7import SPMailCore8import SwiftUI9#if os(macOS)10import AppKit11#else12import UIKit13#endif1415@MainActor16enum NextFixtures {17    private static var done = false18    static let marker = "nxfix"1920    static func runIfRequested(_ app: AppModel) async -> Bool {21        guard let wanted = AppConfig.screenshotScene, wanted.hasPrefix("next."), !done else { return false }22        done = true23        guard await SelfTest.wait(30, { app.phase == .ready && app.main.mailbox(.inbox) != nil }), app.accounts.count >= 2,24              app.accounts.allSatisfy({ $0.address.hasPrefix("apple-") && $0.address.hasSuffix("@stg.spboucher.ai") }) else { return true }25        _ = await SelfTest.wait(15) { app.next.isAvailable }26        await app.next.refresh(force: true)27        let scene = app.main, next = app.next28        let a = app.accounts[0], b = app.accounts[1]29        let name = String(wanted.dropFirst(5))30        if name == "seed" { await seed(app, a: a, b: b); try? "seeded".write(to: SelfTest.progressURL, atomically: true, encoding: .utf8); return true }31        // drafts left by earlier captures of the composer (a composer closed with the app keeps its draft, as it should) would fill the32        // outbox, the gallery and the Command Center of the next capture: they are discarded, with their copy in Drafts33        var seenNotes = false34        for item in (try? await app.store?.outbox()) ?? [] where item.state == .draft {35            let duplicateNotes = item.message.subject == "Notes pour la revue de mardi" && seenNotes36            if item.message.subject == "Notes pour la revue de mardi" { seenNotes = true }37            if item.message.subject.hasPrefix("Compte rendu — suite") || duplicateNotes { await app.engines[item.account]?.discardDraft(id: item.id) }38        }39        await scene.switchAccount(b.id)40        try? await app.engines[b.id]?.syncNowAndWait()41        await scene.reloadThreads()42        func inboxRow(_ subject: String) -> ThreadSummary? { scene.list.threads.first { $0.email.subject.hasPrefix(subject) } }43        func openFirst(_ subject: String) async {44            guard let row = inboxRow(subject) else { return }45            scene.list.selectedIds = [row.id]46            await scene.open(emailId: row.id)47            scene.detailRequest += 148        }49        switch name {50        case "inbox":51            await next.loadInsights(account: b.id)52            await openFirst("Compte rendu")53        case "inbox-list": await next.loadInsights(account: b.id)54        case "search-list":55            scene.openSearch()56            scene.next.search.allMailboxes = true57            scene.next.search.draft = "subject:devis OR subject:facture has:attachment "58            await scene.runRemoteSearch()59        case "dashboard": scene.selection = .dashboard60        case "contacts":61            scene.selection = .contacts62            try? await Task.sleep(for: .seconds(2))63            if let c = scene.next.contacts.contacts.first(where: { $0.name.hasPrefix("Camille") }) ?? scene.next.contacts.contacts.first { await scene.selectContact(c); scene.detailRequest += 1 }64        case "attachments": scene.selection = .attachments65        case "attachments-select":66            scene.selection = .attachments67            try? await Task.sleep(for: .seconds(3))68            scene.next.gallery.selection = Set(scene.next.gallery.items.prefix(2).map(\.id))69        case "snoozed": scene.selection = .snoozed70        case "followups": scene.selection = .followUps71        case "search":72            scene.openSearch()73            scene.next.search.allMailboxes = true74            scene.next.search.draft = "subject:devis OR subject:facture has:attachment "75            await scene.runRemoteSearch()76            if let row = scene.next.search.rows.first { scene.next.selection = [row.id]; await scene.openRemote(row) }77        case "search-error":78            scene.openSearch()79            scene.next.search.draft = "from:camille before:demain-matin larger:beaucoup "80            await scene.runRemoteSearch()81        case "search-suggest":82            scene.openSearch()83            scene.next.search.draft = "is:unread la"84        case "label":85            if let label = next.labels.first(where: { $0.name == "Clients" }) ?? next.labels.first { scene.selection = .label(label.id) }86        case "saved":87            if let saved = next.savedSearches.first { scene.selection = .savedSearch(saved.id) }88        case "unified":89            scene.selection = .unified(.inbox)90            _ = await SelfTest.wait(20) { !scene.unified.rows.isEmpty }91            scene.next.selection = Set(scene.unified.rows.prefix(3).map(\.id))92        case "reader", "summary", "replies":93            try? await next.setAI(AISettingsUpdate(provider: .local, features: ["summary": true, "reply": true, "triage": true, "semantic": false]))94            await openFirst("Compte rendu")95            if name == "summary" { await scene.summarize() }96            if name == "replies" { await scene.suggestReplies() }97        case "triage":98            try? await next.setAI(AISettingsUpdate(provider: .local, features: ["summary": true, "reply": true, "triage": true]))99            await next.loadInsights(account: b.id)100            await next.loadTriage(account: b.id, emailIds: scene.list.threads.prefix(25).map(\.id))101        case "ai-off": try? await next.setAI(AISettingsUpdate(provider: .off))102        case "snooze":103            if let row = inboxRow("Souper") ?? scene.list.threads.first { scene.list.selectedIds = [row.id]; await scene.snooze(ids: [row.id]) }104        case "remind":105            await openFirst("Devis")106            scene.remindSelection()107        case "label-edit": scene.next.labelEdit = LabelEditRequest(label: next.labels.first)108        case "label-pick":109            if let row = scene.list.threads.first { scene.next.labelPick = LabelPickRequest(keywords: row.email.keywords) { _ in } }110        case "palette":111            await openFirst("Compte rendu")112            scene.showPalette = true113        case "outbox":114            await outbox(app, a: a, b: b)115            await scene.switchAccount(a.id)116            scene.selection = .outbox117        case "compose", "assistant":118            // the composer filled by ComposeDemo (`-spmComposeDemo rich`); « assistant » then asks the scripted provider for a rewrite of119            // the selection, which presents the preview sheet — nothing is sent120            if name == "assistant" { try? await next.setAI(AISettingsUpdate(provider: .local, features: ["summary": true, "reply": true, "write": true])) }121            let before = Set(app.composers.keys)122            await scene.compose(.new)123            if name == "assistant" {124                try? await Task.sleep(for: .seconds(4))125                if let composer = app.composers.first(where: { !before.contains($0.key) })?.value { await composer.assist(.improve) }126            }127        case "customize": scene.selection = .dashboard; scene.next.debugPane = "customize"128        case let pane where pane.hasPrefix("settings."):129            if pane == "settings.ai" { try? await next.setAI(AISettingsUpdate(provider: .local, features: ["summary": true, "reply": true, "triage": true])) }130            scene.next.debugPane = String(pane.dropFirst(9))131        default: break132        }133        return true134    }135136    // MARK: outbox137138    /// The outbox with one row of each kind that can be produced between the two staging mailboxes: a local draft, an unsent item of a139    /// mailbox that is gone (local only), a send the server delivered, a scheduled send, and a message held by undo send (its countdown140    /// runs for 45 s — long enough for a capture; it is then delivered to the other test mailbox).141    private static func outbox(_ app: AppModel, a: MeResponse.Box, b: MeResponse.Box) async {142        guard let ea = app.engines[a.id], let store = app.store else { return }143        let center = app.compose144        await center.load(force: true)145        let undoBefore = center.prefs.undoSeconds146        func prefs(_ undo: Int) async { var p = center.prefs; p.undoSeconds = undo; await center.setPrefs(p) }147        func composer(_ subject: String, _ text: String) async -> ComposeModel? {148            guard let id = await app.makeComposer(.new, account: a.id), let c = app.composers[id] else { return nil }149            c.to = [EmailAddress(name: "Camille Tremblay", email: b.address)]150            c.subject = subject151            c.insertText(text + "\n\n" + marker)152            return c153        }154        for old in ((try? await app.api.scheduledSends()) ?? []).dropFirst() { _ = try? await app.api.cancelScheduled(id: old.id) } // one is enough155        await prefs(0)156        await app.outbound.reload(force: true)157        let already = Set(app.outbound.items.compactMap { app.outbound.title(for: $0) })158        if !already.contains("Contrat signé — exemplaire final"), let c = await composer("Contrat signé — exemplaire final", "Bonjour Camille, voici l’exemplaire final du contrat signé par les deux parties.") { _ = await c.deliver(.now); app.composerClosed(c.id) }159        if ((try? await app.api.scheduledSends()) ?? []).isEmpty, let c = await composer("Invitation — lancement du 4 décembre", "Vous êtes invitée au lancement, jeudi à 17 h.") { _ = await c.deliver(.later(Date().addingTimeInterval(2 * 86_400))); app.composerClosed(c.id) }160        if ((try? await store.outbox()) ?? []).allSatisfy({ $0.message.subject != "Notes pour la revue de mardi" }) {161            _ = try? await ea.saveDraft(OutboxItem(account: a.id, message: OutgoingMessage(from: EmailAddress(name: a.display_name, email: a.address), to: [EmailAddress(name: "Olivier Gagnon", email: b.address)],162                                                                                        subject: "Notes pour la revue de mardi", text: "À compléter : points ouverts, budget, calendrier.")))163        }164        if ((try? await store.outbox()) ?? []).allSatisfy({ $0.account != "demo-removed-mailbox" }) {165            try? await store.saveOutbox(OutboxItem(account: "demo-removed-mailbox", message: OutgoingMessage(from: EmailAddress(name: "Projets", email: "apple-projets@stg.spboucher.ai"), to: [EmailAddress(name: "Camille Tremblay", email: b.address)],166                                                                                                       subject: "Réponse au fournisseur — délais", text: "Brouillon écrit avant le retrait de la boîte.")))167        }168        try? await Task.sleep(for: .seconds(6)) // the first send reaches « remis »169        await prefs(45)170        if let c = await composer("Budget révisé — version 3", "Voici la version 3 du budget, avec les postes revus ce matin.") { _ = await c.deliver(.now); app.composerClosed(c.id) }171        await prefs(undoBefore)172        await app.reloadOutbox()173        await app.outbound.reload(force: true)174    }175176    // MARK: seed177178    private static func image(_ hue: Double, _ title: String) -> Data {179        let size = CGSize(width: 640, height: 420)180        #if os(macOS)181        let img = NSImage(size: size)182        img.lockFocus()183        NSColor(hue: hue, saturation: 0.35, brightness: 0.86, alpha: 1).setFill()184        NSRect(origin: .zero, size: size).fill()185        NSColor(hue: hue, saturation: 0.6, brightness: 0.5, alpha: 1).setFill()186        NSBezierPath(ovalIn: NSRect(x: 60, y: 80, width: 220, height: 220)).fill()187        (title as NSString).draw(at: NSPoint(x: 310, y: 190), withAttributes: [.font: NSFont.boldSystemFont(ofSize: 34), .foregroundColor: NSColor.white])188        img.unlockFocus()189        guard let tiff = img.tiffRepresentation, let rep = NSBitmapImageRep(data: tiff) else { return Data() }190        return rep.representation(using: .png, properties: [:]) ?? Data()191        #else192        return UIGraphicsImageRenderer(size: size).pngData { ctx in193            UIColor(hue: hue, saturation: 0.35, brightness: 0.86, alpha: 1).setFill(); ctx.fill(CGRect(origin: .zero, size: size))194            UIColor(hue: hue, saturation: 0.6, brightness: 0.5, alpha: 1).setFill(); ctx.cgContext.fillEllipse(in: CGRect(x: 60, y: 100, width: 220, height: 220))195            (title as NSString).draw(at: CGPoint(x: 310, y: 190), withAttributes: [.font: UIFont.boldSystemFont(ofSize: 34), .foregroundColor: UIColor.white])196        }197        #endif198    }199    /// A minimal one-page PDF (text only).200    private static func pdf(_ title: String) -> Data {201        let stream = "BT /F1 26 Tf 60 720 Td (\(title)) Tj ET"202        let objects = ["<< /Type /Catalog /Pages 2 0 R >>", "<< /Type /Pages /Kids [3 0 R] /Count 1 >>",203                       "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents 4 0 R /Resources << /Font << /F1 5 0 R >> >> >>",204                       "<< /Length \(stream.count) >>\nstream\n\(stream)\nendstream", "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>"]205        var out = "%PDF-1.4\n", offsets: [Int] = []206        for (n, o) in objects.enumerated() { offsets.append(out.utf8.count); out += "\(n + 1) 0 obj\n\(o)\nendobj\n" }207        let xref = out.utf8.count208        out += "xref\n0 \(objects.count + 1)\n0000000000 65535 f \n" + offsets.map { String(format: "%010d 00000 n \n", $0) }.joined()209        out += "trailer\n<< /Size \(objects.count + 1) /Root 1 0 R >>\nstartxref\n\(xref)\n%%EOF\n"210        return Data(out.utf8)211    }212213    private static func seed(_ app: AppModel, a: MeResponse.Box, b: MeResponse.Box) async {214        let scene = app.main, next = app.next215        struct Mail { var fromA: Bool; var subject: String; var text: String; var files: [(String, String, Data)] = [] }216        let mails = [217            Mail(fromA: true, subject: "Souper vendredi ?", text: "On pensait au petit resto de la rue Principale vers 19 h. Tu es partant ?"),218            Mail(fromA: true, subject: "Photos de la séance de samedi", text: "Les photos retouchées sont en pièce jointe. La série complète est sur le disque partagé.", files: [("Portrait 01.png", "image/png", image(0.08, "Portrait")), ("Atelier 02.png", "image/png", image(0.55, "Atelier"))]),219            Mail(fromA: true, subject: "Facture 2026-114 — novembre", text: "Bonjour, veuillez trouver la facture de novembre en pièce jointe. Paiement à 30 jours.", files: [("Facture 2026-114.pdf", "application/pdf", pdf("Facture 2026-114"))]),220            Mail(fromA: true, subject: "Devis révisé — rénovation de la cuisine", text: "Comme convenu, le devis tient compte du plan de travail en quartz et du délai de livraison de trois semaines. Pouvez-vous confirmer d’ici vendredi ?", files: [("Devis cuisine v2.pdf", "application/pdf", pdf("Devis cuisine v2")), ("Budget.csv", "text/csv", Data("poste;montant\nquartz;4200\npose;1800\n".utf8))]),221            Mail(fromA: true, subject: "Compte rendu de la réunion de jeudi", text: "Bonjour, voici le compte rendu et les prochaines étapes : valider la palette d’ici lundi, préparer les gabarits des trois thèmes, planifier la revue d’accessibilité. La version finale suivra demain.", files: [("Compte rendu.pdf", "application/pdf", pdf("Compte rendu"))]),222            Mail(fromA: false, subject: "Proposition de calendrier pour le séminaire", text: "Le mardi me convient mieux que le jeudi ; je peux présenter la deuxième partie si cela aide."),223            Mail(fromA: false, subject: "Maquettes de la nouvelle page d’accueil", text: "J’ai intégré tes commentaires sur la hiérarchie et les couleurs. Dis-moi si la version sombre te convient.", files: [("Maquette accueil.png", "image/png", image(0.38, "Accueil"))]),224        ]225        for m in mails {226            let from = m.fromA ? a : b, to = m.fromA ? b : a227            await app.switchAccount(from.id)228            await app.compose(.new)229            guard let composer = app.composeRequest.flatMap({ app.composers[$0] }) else { continue }230            composer.to = [EmailAddress(name: m.fromA ? "Simon-Pierre" : "Camille Tremblay", email: to.address)]231            composer.subject = m.subject232            composer.body = AttributedString(m.text + "\n\n" + marker)233            for f in m.files { composer.addAttachment(name: f.0, type: f.1, data: f.2) }234            composer.edited()235            _ = await composer.send()236            app.composerClosed(composer.id); app.composeRequest = nil237            try? await Task.sleep(for: .seconds(1.5))238        }239        await app.switchAccount(b.id)240        _ = await SelfTest.wait(60) { await scene.reloadThreads(); return scene.list.threads.filter { $0.email.preview.contains(marker) }.count >= 5 }241        func row(_ prefix: String) -> ThreadSummary? { scene.list.threads.first { $0.email.subject.hasPrefix(prefix) } }242        var labels: [String: MailLabel] = [:]243        for (n, name) in [(5, "Clients"), (1, "Factures"), (7, "Personnel")] { if let l = next.labels.first(where: { $0.name == name }) { labels[name] = l } else if let l = await next.createLabel(name: name, color: LabelPalette.hex(n)) { labels[name] = l } }244        func tag(_ prefix: String, _ names: [String]) async { if let r = row(prefix) { for n in names { if let l = labels[n] { await scene.perform(.keyword(l.keyword, true), on: [r.id]) } } } }245        await tag("Devis", ["Clients"]); await tag("Facture", ["Clients", "Factures"]); await tag("Souper", ["Personnel"]); await tag("Compte rendu", ["Clients"])246        if let r = row("Compte rendu") { await scene.perform(.pin(true), on: [r.id]); await scene.perform(.markRead(false), on: [r.id]) }247        if let r = row("Devis") { await scene.perform(.flag(true), on: [r.id]); _ = await next.remind(account: b.id, emailId: r.id, dueAt: Date().addingTimeInterval(2 * 86_400), onlyIfNoReply: true, note: "Relancer si le devis n’est pas confirmé") }248        if let r = row("Facture") { _ = await next.remind(account: b.id, emailId: r.id, dueAt: Date().addingTimeInterval(5 * 86_400), onlyIfNoReply: false, note: "Payer avant l’échéance") }249        if let r = row("Photos") { _ = await next.snooze(account: b.id, emailIds: [r.id], until: SnoozePresets().date(.tomorrowMorning) ?? Date().addingTimeInterval(86_400)); scene.didSnooze(account: b.id, ids: [r.id]) }250        let people: [(String, String, String, String?, Bool, Bool)] = [("Camille Tremblay", "camille.tremblay@example.org", "Atelier Nord", "Directrice artistique", true, true), ("Olivier Gagnon", "olivier@atelier-nord.example", "Atelier Nord", nil, true, false),251                                                                    ("Maya Okafor", "maya.okafor@example.com", "Studio Lumen", "Photographe", false, false), ("Jean-François Roy", "jf.roy@example.net", "Rénovations Roy", "Entrepreneur", false, true),252                                                                    ("Sofia Martinez", "sofia@studio-lumen.example", "Studio Lumen", nil, false, false)]253        var group = ((try? await next.api.contactGroups()) ?? []).first { $0.name == "Atelier" }254        if group == nil { group = try? await next.api.createContactGroup(name: "Atelier", color: LabelPalette.hex(4)) }255        let existing = ((try? await next.api.contacts(ContactQuery(kind: .saved, limit: 100)))?.contacts ?? []).map(\.name)256        for p in people where !existing.contains(p.0) {257            _ = try? await next.api.createContact(ContactContent(kind: .saved, name: p.0, emails: [ContactEmail(email: p.1, label: "travail")], organization: p.2, title: p.3, phones: p.4 ? [ContactPhone(number: "+1 819 555 0142", label: "mobile")] : [],258                                                                 notes: p.4 ? "Préfère être jointe le matin. Projet « page d’accueil »." : nil, favorite: p.4, vip: p.5, groups: p.2 == "Atelier Nord" ? [group?.id].compactMap { $0 } : []))259        }260        if !next.savedSearches.contains(where: { $0.name == "Factures et devis" }) { _ = await next.saveSearch(name: "Factures et devis", query: "subject:facture OR subject:devis has:attachment", scope: .all) }261        await next.refresh(force: true)262    }263}264#endif265
Files main
Menu

Theme