Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : SP Mail8 * File : tests/e2e/next-prod/integration.part.ts9 * Module : tests10 * Repository : https://git.spboucher.ai/sp-mail11 * Project Website : https://mail.spboucher.ai12 * Created : 2026-11-2013 * Last Modified : 2026-11-2014 *15 * Author : Simon-Pierre Boucher16 * Position : Professor of Finance17 * Institution : Université du Québec en Outaouais (UQO)18 * Organization : SP Boucher19 * Website : https://spboucher.ai20 * Git : https://git.spboucher.ai21 *22 * Preferred Contact: support@spboucher.ai23 * Development : dev@spboucher.ai24 * Support : support@spboucher.ai25 * Security/Admin : admin@spboucher.ai26 *27 * Copyright (c) 202628 * Simon-Pierre Boucher29 * All rights reserved where applicable. This file is governed by the30 * applicable project license, copyright notices and relevant law.31 * Existing third-party rights and notices remain unaffected.32 *33 * License : None specified (no license file in this repository)34 *35 * Do not embed credentials, private keys, access tokens,36 * certificates or confidential personal information.37 *38 * =============================================================================39 * END OF SP BOUCHER SOURCE HEADER40 * =============================================================================41 */4243// SP Mail Next — essais d'intégration des zones : fil identifié par (boîte, fil), dossier « Snoozed » hors de l'arbre, centre de commande44// (sections indisponibles, réponses plafonnées, tuiles), « Toutes les boîtes » (menu contextuel, épingle), raccourcis uniques (aide et45// palette, FR et EN), palette au téléphone, ordre des boîtes (clavier et glisser), rédaction sans bouton d'envoi mort après un rechargement.46import { expect, test, type Page } from "@playwright/test"47import { toastText } from "../helpers"48import type { Part } from "./harness"4950const urow = (p: Page, subject: string) => p.locator("#message-list [role=option]").filter({ hasText: subject })5152export const integrationPart: Part = (h) => {53 const subj = (x: string) => `Intégration ${x} ${h().run}`54 const boxIndex = async (p: Page, address: string) => (await h().api<{ mailboxes: { address: string }[] }>(p, "GET", "/api/me")).mailboxes.findIndex((m) => m.address === address)55 const threads = async (p: Page, address: string) => {56 const r = await h().jmap(p, address, [["Email/query", { limit: 200 }, "q"], ["Email/get", { "#ids": { resultOf: "q", name: "Email/query", path: "/ids" }, properties: ["threadId", "subject", "mailboxIds"] }, "g"]])57 return r[1][1].list as { id: string; threadId: string; subject: string; mailboxIds: Record<string, boolean> }[]58 }59 const go = (p: Page, href: string) =>60 p.evaluate((href) => {61 history.pushState(null, "", href)62 dispatchEvent(new PopStateEvent("popstate"))63 }, href)6465 test("intégration : semis", async () => {66 const { page, P1, P2 } = h()67 await h().seed(page, P1, [68 { subject: subj("Un"), from: ["Prod Deux", P2], preview: "Premier message de la première boîte.", minutesAgo: 3 },69 { subject: subj("Épingle"), from: ["Prod Deux", P2], preview: "À épingler depuis « Toutes les boîtes ».", minutesAgo: 2 },70 ])71 await h().seed(page, P2, [{ subject: subj("Deux"), from: ["Prod Un", P1], preview: "Premier message de la seconde boîte.", minutesAgo: 1 }])72 })7374 test("intégration : deux boîtes, même identifiant de fil — le lecteur montre le fil de la boîte de l'adresse", async () => {75 const { page, P1, P2 } = h()76 const inboxOf = async (address: string) => {77 const r = await h().jmap(page, address, [["Mailbox/get", { properties: ["role"] }, "m"]])78 return (r[0][1].list as { id: string; role: string | null }[]).find((b) => b.role === "inbox")!.id79 }80 const [in1, in2] = [await inboxOf(P1), await inboxOf(P2)]81 const t1 = (await threads(page, P1)).filter((e) => e.mailboxIds[in1])82 const t2 = (await threads(page, P2)).filter((e) => e.mailboxIds[in2])83 const shared = t1.map((e) => e.threadId).find((id) => t2.some((e) => e.threadId === id && e.subject !== t1.find((x) => x.threadId === id)!.subject))84 test.skip(!shared, "aucun identifiant de fil commun aux deux boîtes dans ce parcours : le cas ne peut pas être construit")85 const a = t1.find((e) => e.threadId === shared)!86 const b = t2.find((e) => e.threadId === shared)!87 const [i1, i2] = [await boxIndex(page, P1), await boxIndex(page, P2)]88 await page.goto(`/m/${i1}/inbox/t/${shared}`)89 await expect(page.locator(".reader-subject")).toContainText(a.subject)90 // même identifiant de fil, autre boîte : sans rechargement de page91 await go(page, `/m/${i2}/inbox/t/${shared}`)92 await expect(page.getByRole("heading", { level: 2, name: P2 })).toBeVisible()93 await expect(page.locator(".reader-subject")).toContainText(b.subject)94 await expect(page.locator(".reader-subject")).not.toContainText(a.subject)95 await go(page, `/m/${i1}/inbox/t/${shared}`)96 await expect(page.locator(".reader-subject")).toContainText(a.subject)97 })9899 test("intégration : le dossier « Snoozed » du serveur n'est ni dans l'arbre « Dossiers » ni dans les menus de déplacement", async () => {100 const { page, P1 } = h()101 const boxes = (await h().jmap(page, P1, [["Mailbox/get", { properties: ["name", "role", "parentId"] }, "m"]]))[0][1].list as { name: string; role: string | null }[]102 if (!boxes.some((b) => b.name === "Snoozed" && !b.role)) await h().jmap(page, P1, [["Mailbox/set", { create: { n: { name: "Snoozed", parentId: null } } }, "c"]])103 await h().jmap(page, P1, [["Mailbox/set", { create: { n: { name: `Dossier ${h().run}`, parentId: null } } }, "c"]])104 await page.goto("/")105 await h().openBox(page, P1)106 const tree = page.locator("#sidebar .nav-tree")107 await expect(tree.getByRole("link", { name: new RegExp(`Dossier ${h().run}`) })).toBeVisible()108 await expect(tree.getByRole("link", { name: /Snoozed/ })).toHaveCount(0)109 await expect(page.locator("#sidebar").getByRole("link", { name: /^En veille/ })).toBeVisible()110 // menu « Déplacer vers » de la sélection111 await page.locator("#message-list [role=option]").filter({ hasText: subj("Un") }).locator(".mrow-check").click()112 await page.getByRole("toolbar", { name: "Actions sur la liste" }).getByRole("button", { name: "Déplacer vers…" }).click()113 const menu = page.getByRole("menu")114 await expect(menu.getByRole("menuitem", { name: new RegExp(`Dossier ${h().run}`) })).toBeVisible()115 await expect(menu.getByRole("menuitem", { name: /Snoozed/ })).toHaveCount(0)116 await page.keyboard.press("Escape")117 await page.keyboard.press("Escape")118 // palette : aucun dossier « Snoozed » proposé119 await page.keyboard.press("Control+k")120 const dlg = page.getByRole("dialog", { name: "Palette de commandes" })121 await dlg.getByRole("combobox").fill("Snoozed")122 await expect(dlg.getByRole("option", { name: /^Snoozed$/ })).toHaveCount(0)123 await page.keyboard.press("Escape")124 })125126 test("intégration : centre de commande — sections indisponibles dites, réponses attendues plafonnées, tuiles à leur hauteur", async () => {127 const { page } = h()128 const real = await h().api<Record<string, any>>(page, "GET", "/api/next/dashboard?fresh=1")129 expect(Array.isArray(real.partial), "le serveur rend `partial`").toBe(true)130 const row = (i: number) => ({ mailbox_id: real.inbox[0].mailbox_id, email_id: `e${i}`, thread_id: `t${i}`, subject: `Attente ${i}`, from: [{ name: `Personne ${i}`, email: `p${i}@example.com` }], to: [], preview: "", received_at: new Date(Date.now() - i * 3600_000).toISOString(), size: 1, unread: true, flagged: false, has_attachment: false, keywords: [], labels: [], folder_roles: ["inbox"] })131 const fake = { ...real, pending_replies: Array.from({ length: 10 }, (_, i) => row(i)), attention: { ...real.attention, unanswered: 23, flagged: 0 }, partial: ["storage", "attention", "attention.flagged"] }132 await page.route("**/api/next/dashboard*", (route) => route.fulfill({ json: fake }))133 await page.goto("/dashboard")134 await expect(page.locator(".nx-dash-grid")).toHaveAttribute("aria-busy", "false")135 // section en échec : « indisponible », pas « rien »136 const storage = page.locator('[data-widget="storage"]')137 await expect(storage.getByTestId("widget-unavailable")).toHaveText("Indisponible pour l'instant")138 await expect(storage.getByTestId("storage-row")).toHaveCount(0)139 // chiffre en échec : « — », jamais 0 ; les autres chiffres restent140 await expect(page.getByTestId("stat-flagged")).toHaveAttribute("data-unavailable", "")141 await expect(page.getByTestId("stat-flagged").locator(".nx-stat-n")).toHaveText("—")142 await expect(page.getByTestId("stat-unanswered").locator(".nx-stat-n")).toHaveText("23")143 await expect(page.getByTestId("attention-partial")).toBeVisible()144 // réponses attendues : cinq lignes, puis « Voir tout » vers la recherche correspondante145 const pending = page.locator('[data-widget="pending"]')146 await expect(pending.getByTestId("pending-row")).toHaveCount(5)147 const all = pending.getByTestId("pending-all")148 await expect(all).toHaveText("Voir tout (5 autres)")149 expect(decodeURIComponent((await all.getAttribute("href")) ?? "")).toContain("in:inbox is:unread")150 // tuiles : leur hauteur propre, pas celle de la rangée (le widget voisin, plus haut, ne les étire pas)151 const heights = await page.locator('[data-widget="attention"] .nx-stat').evaluateAll((els) => els.map((e) => Math.round(e.getBoundingClientRect().height)))152 const widgetH = await page.locator('[data-widget="attention"]').evaluate((e) => Math.round(e.getBoundingClientRect().height))153 expect(Math.max(...heights), `tuiles ${heights.join(",")} dans un widget de ${widgetH}px`).toBeLessThanOrEqual(120)154 await h().axe(page, "integration-dashboard-partial")155 await h().shot(page, "integration-dashboard-partial-light")156 await page.unroute("**/api/next/dashboard*")157 })158159 test("intégration : « Toutes les boîtes » — menu contextuel des lignes et épingle (menu, touche « p »)", async () => {160 const { page, P1 } = h()161 await page.goto("/u/inbox")162 const line = urow(page, subj("Épingle"))163 await expect(line).toBeVisible()164 const id = (await threads(page, P1)).find((e) => e.subject === subj("Épingle"))!.id165 const pinned = async () => !!((await h().jmap(page, P1, [["Email/get", { ids: [id], properties: ["keywords"] }, "g"]]))[0][1].list[0].keywords.$pinned)166 await line.click({ button: "right" })167 const menu = page.getByRole("menu")168 for (const name of [/^Marquer comme lu/, /^Ajouter aux favoris|^Marquer comme suivi/, /^Épingler/, /^Archiver/, /^Supprimer/, /^Libellés/, /^Mettre en veille/]) await expect(menu.getByRole("menuitem", { name })).toHaveCount(1)169 await menu.getByRole("menuitem", { name: /^Épingler/ }).click()170 await expect(line.locator(".icon.pin")).toBeVisible()171 await expect(toastText(page, "Épinglé")).toBeVisible()172 await expect.poll(pinned).toBe(true)173 // même menu : l'entrée devient « Désépingler »174 await line.click({ button: "right" })175 await expect(page.getByRole("menu").getByRole("menuitem", { name: /^Désépingler/ })).toBeVisible()176 await page.keyboard.press("Escape")177 // touche « p » sur la ligne sous le curseur178 await line.locator(".mrow-check").click()179 await page.keyboard.press("p")180 await expect(line.locator(".icon.pin")).toHaveCount(0)181 await expect.poll(pinned).toBe(false)182 await page.keyboard.press("Escape")183 })184185 test("intégration : raccourcis — chacun une seule fois dans l'aide et dans la palette, en français et en anglais", async () => {186 const { page, P1 } = h()187 const prefs = (await h().api<{ user: { prefs: Record<string, unknown> } }>(page, "GET", "/api/me")).user.prefs188 const check = async (lang: "fr" | "en") => {189 await h().api(page, "PUT", "/api/prefs", { ...prefs, lang })190 await page.goto("/")191 await page.getByRole("link", { name: P1 }).or(page.getByRole("heading", { level: 2, name: P1 })).first().waitFor()192 await expect(page.locator("html")).toHaveAttribute("lang", lang)193 // les modules inscrivent leurs raccourcis après lecture des capacités194 await expect(page.locator("#sidebar").getByRole("link", { name: lang === "fr" ? /^Centre de commande/ : /^Command Center/ })).toBeVisible()195 await page.locator("#message-list").focus()196 await page.keyboard.press("?")197 const help = page.getByRole("dialog", { name: lang === "fr" ? "Raccourcis clavier" : "Keyboard shortcuts" })198 await expect(help).toBeVisible()199 const section = help.locator("section").first()200 const keys = await section.locator("dt").evaluateAll((els) => els.map((e) => Array.from(e.querySelectorAll("kbd")).map((k) => k.textContent).join(" ")))201 const labels = await section.locator("dd").allTextContents()202 expect(keys.filter((k, i) => keys.indexOf(k) !== i), `${lang} : touches en double dans l'aide`).toEqual([])203 expect(labels.filter((l, i) => labels.indexOf(l) !== i), `${lang} : libellés en double dans l'aide`).toEqual([])204 for (const k of ["g h", "g c", "g f", "g z", "g u", "l", "p", "b"]) expect(keys, `${lang} : « ${k} » dans l'aide`).toContain(k)205 expect(labels.every((l) => l.trim().length > 0)).toBe(true)206 await page.keyboard.press("Escape")207 // palette : commandes (« > ») — une touche ne désigne qu'une commande, un titre n'apparaît qu'une fois208 await page.keyboard.press("Control+k")209 const dlg = page.locator(".palette")210 await dlg.getByRole("combobox").fill(">")211 await expect(dlg.locator(".palette-item").first()).toBeVisible()212 const items = await dlg.locator(".palette-item").evaluateAll((els) => els.map((e) => ({ id: e.getAttribute("data-command") ?? "", title: e.querySelector(".palette-title")?.textContent ?? "", keys: Array.from(e.querySelectorAll(".palette-keys kbd")).map((k) => k.textContent).join(" ") })))213 const withKeys = items.filter((x) => x.keys)214 const dupKeys = withKeys.filter((x, i) => withKeys.findIndex((y) => y.keys === x.keys) !== i)215 expect(dupKeys, `${lang} : touches en double dans la palette`).toEqual([])216 const dupTitles = items.filter((x, i) => items.findIndex((y) => y.title === x.title) !== i)217 expect(dupTitles, `${lang} : commandes en double dans la palette`).toEqual([])218 for (const k of ["g h", "g c", "g f", "g z", "g u", "l"]) expect(withKeys.map((x) => x.keys), `${lang} : « ${k} » dans la palette`).toContain(k)219 await page.keyboard.press("Escape")220 }221 try {222 await check("en")223 await check("fr")224 } finally {225 await h().api(page, "PUT", "/api/prefs", prefs)226 }227 })228229 test("intégration : téléphone — la palette a son bouton dans la barre du haut, à côté de la recherche", async () => {230 const { ctx, p } = await h().fromStorage({ width: 390, height: 844 }, true)231 try {232 await p.goto("/")233 await expect(p.locator(".bottom-nav").getByRole("link", { name: "Centre" })).toBeVisible()234 const btn = p.locator(".search-form .palette-btn")235 await expect(btn).toBeVisible()236 const [b, s] = [await btn.boundingBox(), await p.locator(".search-form .search-box").boundingBox()]237 expect(b!.width).toBeGreaterThanOrEqual(40)238 expect(b!.height).toBeGreaterThanOrEqual(40)239 expect(Math.abs(b!.y + b!.height / 2 - (s!.y + s!.height / 2))).toBeLessThan(12)240 await btn.tap()241 await expect(p.getByRole("dialog", { name: "Palette de commandes" })).toBeVisible()242 await h().shot(p, "integration-phone-palette-light")243 await p.keyboard.press("Escape")244 // « Toutes les boîtes » : même bouton245 await p.goto("/u/inbox")246 await expect(p.locator(".palette-btn").first()).toBeVisible()247 } finally {248 await ctx.close()249 }250 })251252 test("intégration : ordre des boîtes — clavier puis glisser ; l'adresse suit la boîte affichée", async () => {253 const { page, P1, P2 } = h()254 await page.goto("/")255 await h().openBox(page, P1)256 const order = async () => (await h().api<{ mailboxes: { address: string }[] }>(page, "GET", "/api/me")).mailboxes.map((m) => m.address)257 const before = await order()258 expect(before.slice(0, 2)).toEqual([P1, P2])259 const open = async () => {260 await page.locator("#sidebar").getByRole("button", { name: "Changer de boîte" }).click()261 await page.getByRole("menu").getByRole("menuitem", { name: "Réordonner les boîtes…" }).click()262 await expect(page.getByTestId("mailbox-order")).toBeVisible()263 }264 const rows = () => page.locator(".mb-order-row").evaluateAll((els) => els.map((e) => e.getAttribute("data-address")))265 await open()266 // clavier : bouton « Descendre », puis Alt+↑ pour revenir, puis Alt+↓267 await page.getByRole("button", { name: `Descendre ${P1}` }).click()268 expect((await rows()).slice(0, 2)).toEqual([P2, P1])269 // le focus suit la ligne déplacée (à l'image suivante) : les touches agissent sur elle270 const inRow = page.locator(`.mb-order-row[data-address="${P1}"] [data-ctl]:focus`)271 await expect(inRow).toHaveCount(1)272 await page.keyboard.press("Alt+ArrowUp")273 await expect.poll(async () => (await rows()).slice(0, 2)).toEqual([P1, P2])274 await expect(inRow).toHaveCount(1)275 await page.keyboard.press("Alt+ArrowDown")276 await expect.poll(async () => (await rows()).slice(0, 2)).toEqual([P2, P1])277 await page.getByRole("dialog", { name: "Ordre des boîtes" }).getByRole("button", { name: "Enregistrer" }).click()278 await expect(toastText(page, "Ordre des boîtes enregistré.")).toBeVisible()279 await expect.poll(order).toEqual([P2, P1, ...before.slice(2)])280 // la boîte affichée reste P1 ; son rang dans l'adresse a suivi281 await expect(page.getByRole("heading", { level: 2, name: P1 })).toBeVisible()282 await expect(page).toHaveURL(/\/m\/1\//)283 // l'ordre tient après un rechargement, dans la barre latérale284 await page.reload()285 await expect(page.getByRole("heading", { level: 2, name: P1 })).toBeVisible()286 // glisser : P1 déposée sur P2 revient en tête287 await open()288 await page.locator(`.mb-order-row[data-address="${P1}"]`).dragTo(page.locator(`.mb-order-row[data-address="${P2}"]`))289 expect((await rows()).slice(0, 2)).toEqual([P1, P2])290 await page.getByRole("dialog", { name: "Ordre des boîtes" }).getByRole("button", { name: "Enregistrer" }).click()291 await expect.poll(order).toEqual(before)292 await expect(page).toHaveURL(/\/m\/0\//)293 })294295 test("intégration : rédaction rouverte avant l'arrivée des identités — envoi désactivé avec sa raison, puis disponible", async () => {296 const { page, P1, P2 } = h()297 await page.goto("/")298 await h().openBox(page, P1)299 await expect(page.locator("#sidebar").getByRole("link", { name: /Brouillons/ })).toBeVisible()300 const composer = page.locator("section.composer")301 // rechargement : JMAP et la liste des adresses tardent — le message est ouvert AVANT l'arrivée des identités302 let release!: () => void303 const gate = new Promise<void>((r) => (release = r))304 const hold = async (route: import("@playwright/test").Route) => {305 await gate306 await route.continue()307 }308 await page.route("**/api/jmap/**", hold)309 await page.route("**/api/v1/addresses*", hold)310 // aucune copie locale des identités : c'est le cas d'un premier chargement (ou d'un cache vidé)311 await page.evaluate(() => new Promise<void>((resolve) => {312 const del = indexedDB.deleteDatabase("spmail-cache")313 del.onsuccess = del.onerror = del.onblocked = () => resolve()314 }))315 await page.reload()316 await page.getByRole("button", { name: "Nouveau message" }).first().click()317 await expect(composer).toBeVisible()318 await composer.getByRole("combobox", { name: "À :" }).fill(P2)319 await composer.getByRole("combobox", { name: "À :" }).press("Enter")320 await composer.getByLabel("Objet :").fill(subj("Identités tardives"))321 const send = composer.locator(".cmp-send-main")322 await expect(composer.locator('[data-cmp-blocked="sender"]')).toContainText("Chargement de votre adresse d'expéditeur")323 await expect(send).toBeDisabled()324 await expect(send).toHaveAttribute("title", "Chargement de l'adresse d'expéditeur…")325 await h().shot(page, "integration-composer-sender-loading-light")326 release()327 await page.unroute("**/api/jmap/**")328 await page.unroute("**/api/v1/addresses*")329 // les identités arrivent : le bouton s'active seul, sans rien retoucher, et l'envoi part vraiment330 await expect(send).toBeEnabled({ timeout: 30_000 })331 await expect(composer.locator("[data-cmp-blocked]")).toHaveCount(0)332 await composer.getByRole("textbox", { name: "Corps du message" }).click()333 await page.keyboard.type("Envoyé après un rechargement.")334 await send.click()335 await expect(composer).toHaveCount(0, { timeout: 30_000 })336 await expect(page.locator(".toast.error")).toHaveCount(0)337 })338}339