SPB Git

Repository Public

templates-send.spec.ts 14.2 KB 233 lines typescript

1// Studio de modèles — « Envoyer ce modèle » de bout en bout sur la pile de la console (vraies boîtes de recette, port 8811) :2// variables modifiables, envoi par modèle (un seul vrai envoi), suivi jusqu'à « remis », programmation puis annulation,3// panneau d'API, suppression annulable par désarchivage.4import crypto from "node:crypto"5import type { Page } from "@playwright/test"6import { api, axeBoth, expect, noOverflow, st, test, toastText, waitForMessage } from "./fixtures"78const rand = () => crypto.randomBytes(3).toString("hex")910/** Modèle à mise en page complète : feuille de style avec requête média, deux variables. Aucune image distante. */11const HTML = (title: string) => `<!DOCTYPE html>12<html lang="fr"><head><meta charset="utf-8"><title>${title}</title>13<style>14body{margin:0;background:#f4f3ef;}15.card{background:#ffffff;color:#1c1b19;}16h1{font-size:28px;}17@media (max-width:600px){.card{width:100% !important;} h1{font-size:22px !important;}}18</style></head>19<body><table role="presentation" width="100%" cellpadding="0" cellspacing="0"><tr><td align="center" style="padding:24px 12px;">20<table role="presentation" class="card" width="600" cellpadding="0" cellspacing="0" style="width:600px;max-width:100%;border-radius:12px;"><tr><td style="padding:32px;font-family:Arial,sans-serif;">21<h1 style="margin:0 0 12px;">${title}</h1>22<p style="margin:0 0 16px;">Bonjour {{first_name}}, voici votre code : {{code}}</p>23</td></tr></table></td></tr></table></body></html>`2425interface Seeded {26  id: string27  name: string28  version: number29  variables: { name: string; description: string; example: string; required: boolean }[]30}31async function seed(label: string): Promise<Seeded> {32  const name = `Envoi ${label} ${st.run}-${rand()}`33  const r = await api<Seeded>("POST", "/api/templates", {34    name, category: "transactional", subject: "Bienvenue {{first_name}}", preheader: "Votre code de vérification est prêt à être utilisé dès maintenant.",35    html: HTML(name), text: "Bonjour {{first_name}}, voici votre code : {{code}}",36    variables: [{ name: "first_name", description: "", example: "", required: false }, { name: "code", description: "Code à usage unique", example: "424242", required: false }],37  })38  if (!r.ok) throw new Error(`seed template: ${r.status} ${JSON.stringify(r.body)}`)39  return r.body40}41const sendDialog = (page: Page) => page.getByRole("dialog", { name: "Envoyer ce modèle" })42const isSend = (url: string, method: string) => method === "POST" && new URL(url).pathname === "/api/v1/messages/send"4344/** Corps HTML brut du message reçu (passerelle JMAP) : la lecture par /api/v1 assainit le HTML et retirerait <style>. */45async function receivedHtml(address: string, subject: string): Promise<string> {46  const me = await api<{ mailboxes: { id: string; address: string }[] }>("GET", "/api/me")47  const mb = me.body.mailboxes.find((m) => m.address === address)48  if (!mb) throw new Error(`no mailbox ${address} in /api/me`)49  const session = await api<{ primaryAccounts?: Record<string, string>; accounts?: Record<string, unknown> }>("GET", `/api/jmap/${mb.id}/session`)50  const accountId = session.body.primaryAccounts?.["urn:ietf:params:jmap:mail"] ?? Object.keys(session.body.accounts ?? {})[0]51  if (!accountId) throw new Error(`no JMAP account for ${address}: ${session.status}`)52  const r = await api<{ methodResponses: [string, { list?: { htmlBody: { partId: string }[]; bodyValues: Record<string, { value: string }> }[] }, string][] }>("POST", `/api/jmap/${mb.id}/api`, {53    using: ["urn:ietf:params:jmap:core", "urn:ietf:params:jmap:mail"],54    methodCalls: [55      ["Email/query", { accountId, filter: { subject } }, "q"],56      ["Email/get", { accountId, "#ids": { resultOf: "q", name: "Email/query", path: "/ids" }, properties: ["htmlBody", "bodyValues", "subject", "from"], fetchHTMLBodyValues: true }, "g"],57    ],58  })59  if (!r.ok) throw new Error(`jmap: ${r.status} ${JSON.stringify(r.body)}`)60  const email = r.body.methodResponses.find((m) => m[0] === "Email/get")?.[1].list?.[0]61  if (!email) throw new Error(`message « ${subject} » not found through JMAP: ${JSON.stringify(r.body)}`)62  return email.htmlBody.map((p) => email.bodyValues[p.partId]?.value ?? "").join("\n")63}6465test("modèle : variables modifiables, envoi réel suivi jusqu'à « remis », mise en page conservée, envoi programmé", async ({ page }) => {66  test.setTimeout(180_000)67  const tpl = await seed("réel")68  const value = `Maelle-${st.run}-${rand()}`69  const subject = `Modèle ${st.run} ${rand()}`70  const sends: { headers: Record<string, string>; body: Record<string, unknown> }[] = []71  page.on("request", (r) => {72    if (isSend(r.url(), r.method())) sends.push({ headers: r.headers(), body: r.postDataJSON() as Record<string, unknown> })73  })7475  // états rapportés par l'API, dans l'ordre (réponse de l'envoi puis relectures du suivi) : consignés dans le rapport de l'essai76  const flow: string[] = []77  page.on("response", (r) => {78    const path = new URL(r.url()).pathname79    if (!isSend(r.url(), r.request().method()) && !path.startsWith("/api/v1/messages/outbound/")) return80    void r.json().then((o: { status?: string; recipients?: { status: string }[] }) => flow.push(`${o.status}[${(o.recipients ?? []).map((x) => x.status).join(",")}]`), () => {})81  })8283  await page.goto(`/templates/${tpl.id}`)84  await expect(page.getByRole("heading", { level: 1, name: tpl.name })).toBeVisible()85  await expect(page.getByTestId("save-state")).toContainText("Enregistré · version 1")8687  // ---- variables : description, exemple et caractère obligatoire se modifient dans le studio88  const def = page.locator('[data-variable-definition="first_name"]')89  await def.locator("summary").click()90  await page.locator('[data-variable-description="first_name"]').fill("Prénom de la personne")91  await page.locator('[data-variable-example="first_name"]').fill("Camille")92  await page.locator('[data-variable-required="first_name"]').check()93  await expect(page.getByTestId("save")).toBeEnabled()94  await expect(def).toHaveAttribute("data-changed", "true")9596  // modifications non enregistrées : le dialogue le dit, et propose d'enregistrer avant d'envoyer97  await page.getByTestId("send-open").click()98  const dialog = sendDialog(page)99  await expect(dialog.getByTestId("send-unsaved")).toContainText("SP Mail envoie toujours la version enregistrée")100  await expect(dialog.getByTestId("send-submit")).toHaveText("Enregistrer et envoyer")101  await dialog.getByRole("button", { name: "Annuler", exact: true }).click()102  await expect(dialog).toHaveCount(0)103104  await page.getByTestId("save").click()105  await expect(toastText(page, "Enregistré")).toBeVisible()106  await expect(page.getByTestId("save")).toBeDisabled()107  const saved = await api<Seeded>("GET", `/api/templates/${tpl.id}`)108  expect(saved.body.variables).toEqual([109    { name: "code", description: "Code à usage unique", example: "424242", required: false },110    { name: "first_name", description: "Prénom de la personne", example: "Camille", required: true },111  ])112113  // ---- envoyer ce modèle114  await page.getByTestId("send-open").click()115  await expect(dialog.getByTestId("send-unsaved")).toHaveCount(0)116  await dialog.getByTestId("send-from").selectOption(st.addrA)117  const toInput = dialog.getByRole("combobox", { name: "À", exact: true })118  await toInput.fill(st.addrB)119  await toInput.press("Enter")120  await expect(dialog.locator(".rcpt-chip")).toHaveCount(1)121122  // variable obligatoire vide : l'envoi est retenu, avec un message, et rien ne part123  await dialog.getByTestId("send-submit").click()124  await expect(dialog.getByTestId("send-problems")).toContainText("Variable obligatoire sans valeur : {{first_name}}")125  await expect(dialog.locator('[data-send-variable="first_name"]')).toHaveAttribute("aria-invalid", "true")126  expect(sends).toHaveLength(0)127128  await dialog.locator('[data-send-variable="first_name"]').fill(value)129  await expect(dialog.getByTestId("send-problems")).toHaveCount(0)130  await dialog.getByTestId("send-subject").fill(subject)131132  // aperçu rendu avec les valeurs saisies (cadre isolé) ; la variable facultative laissée vide reste vide, sans exemple133  const preview = dialog.getByTestId("send-preview")134  await expect(preview.frameLocator("iframe").locator("body")).toContainText(`Bonjour ${value}, voici votre code :`)135  await expect(preview.frameLocator("iframe").locator("body")).not.toContainText("424242")136  await expect(dialog.getByTestId("send-preview-subject")).toHaveText(subject)137138  // panneau d'API : identifiant réel, expéditeur choisi, clé lue dans $SPMAIL_API_KEY ; lien vers les clés (administrateur)139  await dialog.locator('[data-testid="send-api"] > summary').click()140  const curl = (await dialog.getByTestId("api-curl").textContent()) ?? ""141  expect(curl).toContain("/api/v1/messages/send")142  expect(curl).toContain('-H "Authorization: Bearer $SPMAIL_API_KEY"')143  expect(curl).toContain(`"template_id": "${tpl.id}"`)144  expect(curl).toContain(`"from": "${st.addrA}"`)145  expect(curl).not.toMatch(/spm_[A-Za-z0-9]/)146  const example = JSON.parse((await dialog.getByTestId("api-json").textContent()) ?? "{}") as { template_id: string; from: string; variables: Record<string, string> }147  expect(example).toMatchObject({ template_id: tpl.id, from: st.addrA, variables: { first_name: value, code: "424242" } })148  await expect(dialog.getByTestId("api-keys-link")).toHaveAttribute("href", "/admin/keys")149150  await axeBoth(page, "templates-send-dialog")151  await noOverflow(page)152153  // ---- envoi : un double clic ne produit qu'une demande, porteuse d'une clé d'idempotence154  const answered = page.waitForResponse((r) => isSend(r.url(), r.request().method()))155  await dialog.getByTestId("send-submit").dblclick()156  expect((await answered).status()).toBeLessThan(300)157  const status = dialog.getByTestId("send-status")158  await expect(status).toBeVisible()159  // « accepté » n'est pas « remis » : l'état affiché est celui que l'API rapporte, jamais une remise supposée160  expect(["queued", "sent", "delivered"]).toContain(await status.getAttribute("data-status"))161  const recipient = status.locator(`[data-recipient="${st.addrB}"]`)162  await expect(recipient).toHaveAttribute("data-status", "delivered", { timeout: 90_000 })163  await expect(recipient).toContainText("Remis")164  await expect(status).toHaveAttribute("data-status", "delivered")165  await expect(dialog.getByTestId("send-status-label")).toHaveText("Remis")166167  test.info().annotations.push({ type: "status-flow", description: flow.join(" → ") })168  console.log(`[templates-send] états observés : ${flow.join(" → ")}`)169  expect(flow.at(-1)).toBe("delivered[delivered]")170  expect(sends).toHaveLength(1)171  expect(sends[0].headers["idempotency-key"]).toMatch(/^studio-[0-9a-f-]{36}$/)172  expect(sends[0].body).toEqual({ from: st.addrA, to: [{ email: st.addrB }], template_id: tpl.id, variables: { first_name: value }, subject })173174  // ---- le message reçu : objet de remplacement, valeur de la variable, feuille de style conservée175  const hit = await waitForMessage(st.addrB, subject)176  const got = await api("GET", `/api/v1/messages/${encodeURIComponent(hit.id)}`)177  expect(got.ok).toBe(true)178  expect(got.body.subject).toBe(subject)179  const html = await receivedHtml(st.addrB, subject)180  expect(html).toContain("<style")181  expect(html).toContain("@media (max-width:600px)")182  expect(html).toContain(`Bonjour ${value}, voici votre code :`)183  expect(html).not.toContain("{{")184185  // ---- programmation (aucun second envoi réel) : demain 9 h par défaut → « Programmé », puis annulation par l'API186  await dialog.getByTestId("send-again").click()187  await expect(dialog.locator('[data-send-variable="first_name"]')).toHaveValue(value)188  await dialog.getByTestId("send-schedule").check()189  await expect(dialog.getByTestId("send-at")).toHaveValue(/^\d{4}-\d{2}-\d{2}T09:00$/)190  await expect(dialog.getByTestId("send-submit")).toHaveText("Programmer l'envoi")191  const scheduledResponse = page.waitForResponse((r) => isSend(r.url(), r.request().method()))192  await dialog.getByTestId("send-submit").click()193  const scheduled = (await (await scheduledResponse).json()) as { id: string; status: string; send_at: string }194  expect(scheduled.status).toBe("scheduled")195  expect(new Date(scheduled.send_at).getTime()).toBeGreaterThan(Date.now() + 3600_000)196  await expect(status).toHaveAttribute("data-status", "scheduled")197  await expect(dialog.getByTestId("send-status-label")).toHaveText("Programmé")198  await expect(status).toContainText("Rien n'est parti")199  expect(sends).toHaveLength(2)200  expect(sends[1].headers["idempotency-key"]).not.toBe(sends[0].headers["idempotency-key"])201  expect(typeof sends[1].body.send_at).toBe("string")202  await axeBoth(page, "templates-send-status")203  const cancelled = await api("DELETE", `/api/v1/messages/scheduled/${scheduled.id}`)204  expect(cancelled.ok).toBe(true)205  expect(cancelled.body.status).toBe("cancelled")206207  await dialog.getByRole("button", { name: "Fermer", exact: true }).last().click()208  await expect(dialog).toHaveCount(0)209  await api("DELETE", `/api/templates/${tpl.id}`)210})211212test("modèle : la suppression archive tout de suite, « Annuler » désarchive (POST …/unarchive)", async ({ page }) => {213  const tpl = await seed("corbeille")214  await page.goto("/templates")215  const card = page.getByTestId("template-card").filter({ has: page.getByRole("heading", { name: tpl.name }) })216  await expect(card).toBeVisible()217  await card.getByRole("button", { name: `Actions pour ${tpl.name}` }).click()218  const archived = page.waitForResponse((r) => r.request().method() === "DELETE" && new URL(r.url()).pathname === `/api/templates/${tpl.id}`)219  await page.getByRole("menuitem", { name: "Supprimer" }).click()220  expect((await archived).ok()).toBe(true)221  await expect(card).toHaveCount(0)222  // archivé côté serveur dès maintenant (plus de délai, plus de requête à la fermeture de la page)223  expect((await api("GET", `/api/templates/${tpl.id}`)).status).toBe(404)224225  const restored = page.waitForResponse((r) => r.request().method() === "POST" && new URL(r.url()).pathname === `/api/templates/${tpl.id}/unarchive`)226  await toastText(page, `Modèle supprimé : ${tpl.name}`).getByRole("button", { name: "Annuler" }).click()227  expect((await restored).ok()).toBe(true)228  await expect(card).toBeVisible()229  expect((await api("GET", `/api/templates/${tpl.id}`)).status).toBe(200)230  await noOverflow(page)231  await api("DELETE", `/api/templates/${tpl.id}`)232})233
Files main
Menu

Theme