Repository Public
1// Courrier : identités d'envoi (boîtes ET alias), signature qui suit l'identité, réponse depuis l'alias visé,2// boîte de réception unifiée (ordre, pastilles d'adresse, ouverture, archivage, arrivée en direct, sous-ensemble), programmés.3import type { Page } from "@playwright/test"4import { list, row } from "../helpers"5import { api, axeBoth, createAlias, expect, noOverflow, sendMail, st, test, toastText, waitForMessage } from "./fixtures"67test.describe.configure({ mode: "serial" })89const SIG_A = `Signature A ${st.run}`10const SIG_ALIAS = `Service de la facturation ${st.run}`11let alias = ""12let mbA = ""13let mbB = ""1415/** Message brut lu par la passerelle JMAP (session du lanceur) : expéditeur réel du message reçu. */16async function receivedFrom(mb: string, subject: string): Promise<{ email: string; name: string | null }[]> {17 const accountId = Object.keys((await api("GET", `/api/jmap/${mb}/session`)).body.accounts)[0]18 for (let i = 0; i < 60; i++) {19 const r = await api("POST", `/api/jmap/${mb}/api`, {20 using: ["urn:ietf:params:jmap:core", "urn:ietf:params:jmap:mail"],21 methodCalls: [["Email/query", { accountId, filter: { subject } }, "q"], ["Email/get", { accountId, "#ids": { resultOf: "q", name: "Email/query", path: "/ids" }, properties: ["from", "subject"] }, "g"]],22 })23 const hit = (r.body.methodResponses?.[1]?.[1]?.list ?? []).find((e: { subject: string }) => e.subject === subject)24 if (hit) return hit.from25 await new Promise((res) => setTimeout(res, 700))26 }27 throw new Error(`« ${subject} » not received`)28}29const composer = (page: Page) => page.locator("section.composer")30const fromSelect = (page: Page) => composer(page).getByLabel("De :")31const body = (page: Page) => composer(page).getByRole("textbox", { name: "Corps du message" })32async function pickSender(page: Page, address: string) {33 const label = (await fromSelect(page).locator("option").allTextContents()).find((o) => o.includes(address))34 expect(label, `expéditeur ${address} proposé`).toBeTruthy()35 await fromSelect(page).selectOption({ label: label! })36}3738test.beforeAll(async () => {39 const me = (await api("GET", "/api/me")).body40 mbA = me.mailboxes.find((m: { address: string }) => m.address === st.addrA).id41 mbB = me.mailboxes.find((m: { address: string }) => m.address === st.addrB).id42 alias = (await createAlias("billing", st.addrA, { display_name: "Facturation", signature_text: SIG_ALIAS })).address43 const r = await api("PATCH", `/api/v1/addresses/${encodeURIComponent(st.addrA)}`, { signature_text: SIG_A })44 expect(r.ok, JSON.stringify(r.body)).toBe(true)45})4647test("rédaction : l'alias est proposé sous sa boîte, la signature suit l'identité, l'envoi part vraiment de l'alias", async ({ page }) => {48 const subject = `Depuis alias ${st.run}`49 await page.goto("/")50 await page.getByRole("link", { name: st.addrA }).or(page.getByRole("heading", { level: 2, name: st.addrA })).first().waitFor()51 await page.getByRole("button", { name: "Nouveau message" }).first().click()52 await expect(composer(page)).toBeVisible()53 // l'alias est groupé avec sa boîte, l'adresse principale en tête (d'autres essais ont pu y ajouter leurs alias)54 const group = fromSelect(page).locator(`optgroup[label="${st.addrA}"]`)55 await expect(group.locator("option").first()).toContainText(st.addrA)56 await expect(group.locator("option").filter({ hasText: alias })).toHaveCount(1)57 // texte tapé + signature de A58 await pickSender(page, st.addrA)59 await expect(body(page)).toContainText(SIG_A)60 // curseur au tout début du corps (au-dessus de la signature), puis frappe61 await body(page).evaluate((el) => {62 el.focus()63 getSelection()?.collapse(el.firstChild ?? el, 0)64 })65 await page.keyboard.type("Bonjour, voici la facture.")66 // → alias : la signature est remplacée (jamais doublée), le texte tapé reste67 await pickSender(page, alias)68 await expect(body(page)).toContainText(SIG_ALIAS)69 await expect(body(page)).not.toContainText(SIG_A)70 await expect(body(page)).toContainText("Bonjour, voici la facture.")71 // aller-retour : toujours une seule signature72 await pickSender(page, st.addrA)73 await expect(body(page)).toContainText(SIG_A)74 await expect(body(page)).not.toContainText(SIG_ALIAS)75 await pickSender(page, alias)76 expect(await body(page).locator(".spm-signature").count()).toBe(1)77 // du texte tapé dans le bloc de signature lui-même (le curseur s'y pose en cliquant sous le texte) n'est pas perdu78 await body(page).evaluate((el) => {79 const sig = el.querySelector(".spm-signature")!80 el.focus()81 getSelection()?.selectAllChildren(sig)82 getSelection()?.collapseToEnd()83 })84 await page.keyboard.type(" PS tapé dans la signature")85 await pickSender(page, st.addrA)86 await expect(body(page)).toContainText("PS tapé dans la signature")87 await expect(body(page).locator(".spm-signature")).toHaveText(SIG_A)88 await pickSender(page, alias)89 await expect(body(page)).toContainText("PS tapé dans la signature")90 await expect(body(page).locator(".spm-signature")).toHaveText(SIG_ALIAS)91 await expect(fromSelect(page)).toHaveAttribute("data-via", "api")92 await axeBoth(page, "composer-alias")9394 await composer(page).getByRole("combobox", { name: "À :" }).fill(st.addrB)95 await composer(page).getByRole("combobox", { name: "À :" }).press("Enter")96 await composer(page).getByLabel("Objet :").fill(subject)97 const sent = page.waitForResponse((r) => r.url().endsWith("/api/v1/messages/send") && r.request().method() === "POST")98 await composer(page).getByRole("button", { name: "Envoyer" }).click()99 const res = await sent100 // 200 : remis au serveur de courrier ; 202 : retenu le temps de « Annuler l'envoi » (réglage par défaut de la rédaction Next)101 expect([200, 202]).toContain(res.status())102 expect((await res.json()).from).toBe(alias)103 await expect(composer(page)).toBeHidden()104 // suivi honnête : accepté, puis l'état observé par destinataire105 const card = page.getByTestId("delivery").filter({ hasText: subject })106 await expect(card).toBeVisible()107 await expect(card.locator(`[data-recipient="${st.addrB}"]`)).toHaveAttribute("data-delivered", "yes", { timeout: 45_000 })108109 // le message REÇU porte bien l'alias en expéditeur (lu dans la boîte B par la passerelle JMAP)110 const from = await receivedFrom(mbB, subject)111 expect(from).toHaveLength(1)112 expect(from[0].email).toBe(alias)113 expect(from[0].name).toBe("Facturation")114})115116test("réponse : l'identité par défaut est l'alias auquel le message a été envoyé", async ({ page }) => {117 const subject = `Pour l'alias ${st.run}`118 await sendMail(st.addrB, alias, subject, "Question sur une facture.")119 await waitForMessage(st.addrA, subject)120 await page.goto("/")121 await page.getByRole("link", { name: st.addrA }).or(page.getByRole("heading", { level: 2, name: st.addrA })).first().waitFor()122 if (await page.getByRole("link", { name: st.addrA, exact: true }).count()) await page.getByRole("link", { name: st.addrA, exact: true }).click()123 await row(page, new RegExp(subject)).click()124 await page.getByRole("button", { name: "Répondre", exact: true }).first().click()125 await expect(composer(page)).toBeVisible()126 await expect(fromSelect(page).locator("option:checked")).toContainText(alias)127 await expect(body(page)).toContainText(SIG_ALIAS)128 await expect(composer(page).locator(".rcpt-chip")).toContainText(["Essai B"])129 // rien n'est envoyé : la rédaction est abandonnée130 await composer(page).getByRole("button", { name: "Supprimer le brouillon" }).click()131 await page.getByRole("alertdialog").getByRole("button", { name: "Supprimer le brouillon" }).click()132 await expect(composer(page)).toBeHidden()133})134135test("boîte unifiée : deux boîtes fusionnées par date, pastilles d'adresse, ouverture, archivage, arrivée en direct", async ({ page }) => {136 const s1 = `Unifié un ${st.run}`137 const s2 = `Unifié deux ${st.run}`138 const s3 = `Unifié direct ${st.run}`139 await sendMail(st.addrA, st.addrB, s1)140 await waitForMessage(st.addrB, s1)141 await sendMail(st.addrB, st.addrA, s2)142 await waitForMessage(st.addrA, s2)143144 await page.goto("/")145 await page.getByRole("link", { name: "Toutes les boîtes" }).click()146 await expect(page).toHaveURL(/\/u\/inbox$/)147 await expect(list(page)).toBeVisible()148 const r1 = row(page, new RegExp(s1))149 const r2 = row(page, new RegExp(s2))150 await expect(r1).toBeVisible()151 await expect(r2).toBeVisible()152 // chaque ligne dit quelle adresse a reçu le message ; l'alias a sa propre pastille153 await expect(r1.locator(".addr-chip")).toHaveAttribute("data-address", st.addrB)154 await expect(r2.locator(".addr-chip")).toHaveAttribute("data-address", st.addrA)155 await expect(row(page, new RegExp(`Pour l'alias ${st.run}`)).locator(".addr-chip")).toHaveAttribute("data-address", alias)156 // une seule liste, du plus récent au plus ancien157 const order = await list(page).getByRole("option").evaluateAll((els) => els.map((e) => Number(e.getAttribute("aria-posinset"))))158 expect(order).toEqual([...order].sort((a, b) => a - b))159 expect(Number(await r2.getAttribute("aria-posinset"))).toBeLessThan(Number(await r1.getAttribute("aria-posinset")))160 // couleur stable : la même adresse a la même teinte sur toutes ses lignes161 const hues = await page.locator(`.addr-chip[data-address="${st.addrA}"]`).evaluateAll((els) => els.map((e) => (e as HTMLElement).style.getPropertyValue("--h")))162 expect(new Set(hues).size).toBe(1)163 await axeBoth(page, "unified-inbox")164 await noOverflow(page)165166 // arrivée en direct : aucun rechargement167 await sendMail(st.addrA, st.addrB, s3)168 await expect(row(page, new RegExp(s3))).toBeVisible({ timeout: 45_000 })169170 // ouverture dans le lecteur habituel, depuis la bonne boîte171 await r1.click()172 await expect(page).toHaveURL(/\/u\/inbox\/t\/\d+\//)173 await expect(page.locator("main#main").getByRole("heading", { name: s1 })).toBeVisible()174 // archiver depuis le lecteur : l'action vise la boîte du message, la ligne quitte la vue unifiée175 await page.locator("main#main").getByRole("button", { name: "Archiver" }).first().click()176 await expect(toastText(page, /archivé/i)).toBeVisible()177 await expect(row(page, new RegExp(s1))).toHaveCount(0)178 const archived = (await api("GET", `/api/v1/messages?address=${encodeURIComponent(st.addrB)}&folder=archive&subject=${encodeURIComponent(s1)}`)).body.data179 expect(archived.map((m: { subject: string }) => m.subject)).toEqual([s1])180 await expect(r2).toBeVisible()181182 // actions de liste (API, par message) : favori puis vue « Favoris » de toutes les boîtes183 await r2.locator(".mrow-star").click()184 await page.getByRole("link", { name: "Favoris", exact: true }).click()185 await expect(page).toHaveURL(/\/u\/starred$/)186 await expect(row(page, new RegExp(s2))).toBeVisible()187 await expect(row(page, new RegExp(s3))).toHaveCount(0)188 // clavier : g a ramène à la boîte unifiée189 await page.getByRole("link", { name: "Non lus", exact: true }).click()190 await expect(page).toHaveURL(/\/u\/unread$/)191 await list(page).or(page.locator(".list-pane .empty")).first().waitFor()192 await page.locator(".list-title").click()193 await page.keyboard.press("g")194 await page.keyboard.press("a")195 await expect(page).toHaveURL(/\/u\/inbox$/)196})197198test("boîte unifiée : sous-ensemble de boîtes, enregistré dans les préférences (PATCH)", async ({ page }) => {199 await page.goto("/u/inbox")200 await expect(row(page, new RegExp(`Unifié deux ${st.run}`))).toBeVisible()201 await expect(row(page, new RegExp(`Unifié direct ${st.run}`))).toBeVisible()202 await page.getByTestId("subset-button").click()203 const dlg = page.getByRole("dialog", { name: "Boîtes à afficher" })204 // ne garder que la boîte A (d'autres essais ont pu créer des boîtes supplémentaires)205 const total = (await api("GET", "/api/me")).body.mailboxes.length206 for (const box of await dlg.getByRole("checkbox").all()) if (!((await box.evaluate((el) => el.closest("label")?.textContent ?? "")).includes(st.addrA))) await box.uncheck()207 const saved = page.waitForResponse((r) => r.url().endsWith("/api/prefs") && r.request().method() === "PATCH")208 await dlg.getByRole("button", { name: "Appliquer" }).click()209 expect((await saved).status()).toBe(200)210 await expect(row(page, new RegExp(`Unifié direct ${st.run}`))).toHaveCount(0)211 await expect(row(page, new RegExp(`Unifié deux ${st.run}`))).toBeVisible()212 await expect(page.getByTestId("subset-button")).toContainText(`1 boîte sur ${total}`)213 // les autres préférences n'ont pas été écrasées, et le choix survit au rechargement214 const prefs = (await api("GET", "/api/me")).body.user.prefs215 expect(prefs.unifiedMailboxes).toEqual([mbA])216 await page.reload()217 await expect(row(page, new RegExp(`Unifié deux ${st.run}`))).toBeVisible()218 await expect(row(page, new RegExp(`Unifié direct ${st.run}`))).toHaveCount(0)219 await axeBoth(page, "unified-subset")220 // retrait par la pastille : retour à toutes les boîtes221 await page.getByRole("button", { name: `Ne plus afficher ${st.addrA}` }).click()222 await expect(row(page, new RegExp(`Unifié direct ${st.run}`))).toBeVisible()223 expect((await api("GET", "/api/me")).body.user.prefs.unifiedMailboxes).toEqual([])224})225226test("programmés : un envoi différé apparaît dans « Programmés » et peut être annulé", async ({ page }) => {227 const subject = `Programmé ${st.run}`228 const sendAt = new Date(Date.now() + 26 * 3600_000).toISOString()229 const r = await api("POST", "/api/v1/messages/send", { from: st.addrA, to: [{ email: st.addrB }], subject, text: "Plus tard.", send_at: sendAt })230 expect(r.status).toBe(202)231 expect(r.body.status).toBe("scheduled")232 await page.goto("/u/inbox")233 await page.getByRole("link", { name: "Programmés", exact: true }).click()234 const item = page.getByTestId("scheduled-item").filter({ hasText: subject })235 await expect(item).toBeVisible()236 await expect(item).toContainText(st.addrB)237 await axeBoth(page, "unified-scheduled")238 await item.getByRole("button", { name: /Annuler l'envoi/ }).click()239 await page.getByRole("alertdialog").getByRole("button", { name: "Annuler l'envoi" }).click()240 await expect(toastText(page, /Envoi programmé annulé/)).toBeVisible()241 await expect(item).toHaveCount(0)242 expect((await api("GET", `/api/v1/messages/outbound/${r.body.id}`)).body.status).toBe("cancelled")243})244