SPB Git

Repository Public

templates.spec.ts 56.3 KB 885 lines typescript

1/**2 * =============================================================================3 *                  SP BOUCHER | SOFTWARE & RESEARCH4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : SP Mail8 * File             : tests/e2e/studio/templates.spec.ts9 * Module           : tests10 * Repository       : https://git.spboucher.ai/sp-mail11 * Project Website  : https://mail.spboucher.ai12 * Created          : 2026-11-1913 * Last Modified    : 2026-11-1914 *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// Studio de modèles sur ordinateur (1440 × 900). Génération par IA rejouée depuis fixtures/generate-welcome.sse ;44// un seul essai réel, à la demande : E2E_AI=1.45import fs from "node:fs"46import { API_HEADERS, OUT } from "./env"47import { axe, card, expect, noOverflow, pretendAiConfigured, previewFrame, test, toastText } from "./fixtures"48import { errorScenario, recordedScenario, startReplay, stubGeneration, truncatedScenario, type Replay } from "./replay"49import { MALICIOUS_HTML, clearTemplates, listTemplates, recordedTemplate, seedSimple, seedTemplate } from "./seed"5051const REAL_AI = process.env.E2E_AI === "1"52let replay: Replay5354test.describe.configure({ mode: "serial" })55test.beforeAll(async () => {56  fs.rmSync(`${OUT}/axe.log`, { force: true })57  replay = await startReplay()58})59test.afterAll(async () => {60  await replay.close()61})6263const BRIEF = "Courriel de bienvenue pour les nouveaux abonnés d'un atelier de céramique, avec un code promo et un bouton vers la boutique."6465/** Crée dans la base le modèle que le flux rejoué « génère », et rend l'objet complet tel que l'API le présente. */66async function seedRecorded(request: Parameters<typeof seedTemplate>[0]) {67  const t = recordedTemplate()68  return seedTemplate(request, { name: t.name, category: "transactional", subject: t.subject, preheader: t.preheader, html: t.html, text: t.text, variables: t.variables, brand: t.brand })69}7071// ================================================================ bibliothèque72test("bibliothèque vide : l'état vide présente le studio et mène à la création", async ({ page, request }) => {73  await clearTemplates(request)74  await page.goto("/")75  await page.getByRole("link", { name: "Modèles" }).click()76  await expect(page).toHaveURL(/\/templates$/)77  await expect(page.getByRole("heading", { level: 1, name: "Modèles" })).toBeVisible()78  const empty = page.getByTestId("templates-empty")79  await expect(empty.getByRole("heading", { name: "Vos courriels, dessinés une fois pour toutes" })).toBeVisible()80  await expect(empty.getByText("{{first_name}}")).toBeVisible()81  await axe(page, "library-empty")82  await page.screenshot({ path: `${OUT}/shots/library-empty.png` })83  await empty.getByRole("link", { name: "Créer avec l'IA" }).click()84  await expect(page).toHaveURL(/\/templates\/new$/)85  await expect(page.getByRole("heading", { name: "Décrivez le courriel" })).toBeVisible()86  await page.getByRole("link", { name: "Modèles" }).click()87  await expect(empty).toBeVisible()88})8990test("bibliothèque : cartes avec miniature vivante, pastille IA, recherche, filtre, tri", async ({ page, request }) => {91  await seedSimple(request, "Confirmation de commande")92  await seedSimple(request, "Alerte de connexion", { category: "security", subject: "Nouvelle connexion à votre compte" })93  const ai = await seedRecorded(request)94  // la pastille « IA » dépend de `source`, que seule une vraie génération pose : la liste est retouchée pour cet essai95  await pretendAiConfigured(page, (list) => {96    for (const t of list) if (t.id === ai.id) Object.assign(t, { source: "ai", ai_model: "claude-opus-5-5" })97  })98  await page.goto("/templates")99  await expect(page.getByTestId("template-card")).toHaveCount(3)100  await expect(page.getByText("3 modèles")).toBeVisible()101102  // miniature : cadre isolé, inerte, contenu rendu avec les valeurs d'exemple103  const c = card(page, "Confirmation de commande")104  const frame = c.locator("iframe")105  await expect(frame).toHaveAttribute("sandbox", "")106  await expect(frame).toHaveAttribute("aria-hidden", "true")107  await expect(c.frameLocator("iframe").locator("body")).toContainText("Bonjour Camille, votre commande A-1042 est confirmée.")108  await expect(c.getByText("3 variables")).toBeVisible()109  await expect(c.getByText("Transactionnel")).toBeVisible()110  await expect(c.getByText("à l'instant")).toBeVisible()111  await expect(card(page, ai.name).getByText("IA", { exact: true })).toBeVisible()112  await expect(c.getByText("IA", { exact: true })).toHaveCount(0)113  // pas de saut de mise en page : la miniature occupe sa place avant d'être rendue (rapport hauteur/largeur fixe)114  const box = await c.locator(".tpl-thumb").boundingBox()115  expect(Math.abs(box!.height / box!.width - 5.4 / 5)).toBeLessThan(0.02)116117  await page.getByRole("searchbox", { name: "Rechercher un modèle" }).fill("connexion")118  await expect(page.getByTestId("template-card")).toHaveCount(1)119  await expect(card(page, "Alerte de connexion")).toBeVisible()120  await page.getByRole("searchbox", { name: "Rechercher un modèle" }).fill("introuvable")121  await expect(page.getByRole("heading", { name: "Aucun modèle ne correspond" })).toBeVisible()122  await page.getByRole("button", { name: "Effacer les filtres" }).click()123  await page.getByLabel("Catégorie").selectOption({ label: "Sécurité" })124  await expect(page.getByTestId("template-card")).toHaveCount(1)125  await page.getByLabel("Catégorie").selectOption({ label: "Toutes les catégories" })126  await page.getByLabel("Tri").selectOption({ label: "Nom (A → Z)" })127  await expect(page.getByTestId("template-card").locator("h3")).toHaveText(["Alerte de connexion", ai.name, "Confirmation de commande"])128  // raccourci « / » : la recherche prend le focus129  await page.locator("#main").click({ position: { x: 5, y: 5 } })130  await page.keyboard.press("/")131  await expect(page.getByRole("searchbox", { name: "Rechercher un modèle" })).toBeFocused()132  await noOverflow(page)133  await axe(page, "library")134  await page.screenshot({ path: `${OUT}/shots/library.png` })135})136137test("bibliothèque : cent modèles restent fluides, seules les miniatures proches de l'écran sont rendues", async ({ page, request }) => {138  for (let i = 0; i < 100; i += 10) await Promise.all(Array.from({ length: 10 }, (_, k) => seedSimple(request, `Série ${String(i + k).padStart(3, "0")}`)))139  let renders = 0140  page.on("request", (r) => {141    if (/\/api\/templates\/[0-9a-f-]+\/render$/.test(r.url())) renders++142  })143  await page.goto("/templates")144  await expect(page.getByTestId("template-card")).toHaveCount(103)145  await expect(page.locator(".tpl-thumb[data-state='ready']").first()).toBeVisible()146  await page.waitForTimeout(1500)147  const before = await page.locator(".tpl-thumb iframe").count()148  expect(before).toBeGreaterThan(0)149  expect(before).toBeLessThan(40)150  expect(renders).toBeLessThan(40)151  // le défilement fait apparaître les suivantes152  await page.locator("#main").evaluate((el) => el.scrollTo(0, el.scrollHeight))153  await expect(page.getByTestId("template-card").last().locator("iframe")).toBeVisible()154  expect(await page.locator(".tpl-thumb iframe").count()).toBeGreaterThan(before)155  for (const t of await listTemplates(request)) if (/^Série /.test(t.name)) await request.delete(`/api/templates/${t.id}`, { headers: API_HEADERS })156})157158test("bibliothèque : dupliquer, supprimer puis annuler, supprimer pour de bon", async ({ page, request }) => {159  await page.goto("/templates")160  const c = card(page, "Alerte de connexion")161  await c.getByRole("button", { name: "Actions pour Alerte de connexion" }).click()162  await page.getByRole("menuitem", { name: "Dupliquer" }).click()163  await expect(toastText(page, "Copie créée : Alerte de connexion (copie)")).toBeVisible()164  await expect(card(page, "Alerte de connexion (copie)")).toBeVisible()165  await expect(page.getByTestId("template-card")).toHaveCount(4)166167  // suppression annulable : le modèle est archivé tout de suite (DELETE), « Annuler » le désarchive (POST …/unarchive)168  const copy = card(page, "Alerte de connexion (copie)")169  const copyId = (await listTemplates(request)).find((t) => t.name === "Alerte de connexion (copie)")!.id170  await copy.getByRole("button", { name: /^Actions pour/ }).click()171  const archived = page.waitForResponse((r) => r.request().method() === "DELETE" && r.url().endsWith(`/api/templates/${copyId}`))172  await page.getByRole("menuitem", { name: "Supprimer" }).click()173  await expect(copy).toHaveCount(0)174  expect((await archived).ok()).toBe(true)175  expect((await listTemplates(request)).some((t) => t.id === copyId)).toBe(false)176  const restored = page.waitForResponse((r) => r.request().method() === "POST" && r.url().endsWith(`/api/templates/${copyId}/unarchive`))177  await toastText(page, "Modèle supprimé : Alerte de connexion (copie)").getByRole("button", { name: "Annuler" }).click()178  expect((await restored).ok()).toBe(true)179  await expect(copy).toBeVisible()180  expect((await listTemplates(request)).some((t) => t.id === copyId)).toBe(true)181182  // sans annulation, le modèle reste archivé183  await copy.getByRole("button", { name: /^Actions pour/ }).click()184  await page.getByRole("menuitem", { name: "Supprimer" }).click()185  await expect(copy).toHaveCount(0)186  await expect.poll(async () => (await listTemplates(request)).some((t) => t.id === copyId), { timeout: 15_000 }).toBe(false)187  await page.reload()188  await expect(page.getByTestId("template-card")).toHaveCount(3)189})190191// ================================================================ modèle hostile192test("un modèle piégé reste inerte dans la miniature comme dans l'éditeur ; son image distante passe par /api/img", async ({ page, request, watch }) => {193  const evil = await seedTemplate(request, { name: "Modèle piégé", html: MALICIOUS_HTML, subject: "Piège" })194  await page.goto("/templates")195  const c = card(page, "Modèle piégé")196  const thumb = c.frameLocator("iframe")197  await expect(thumb.locator("body")).toContainText("Contenu du modèle piégé")198  await expect(thumb.locator("script")).toHaveCount(0)199  await expect(thumb.locator("[onerror]")).toHaveCount(0)200  await expect.poll(() => watch.proxied).toContain("https://example.org/t.gif")201  // l'image récupérée par la page est injectée en data: — le cadre ne contient aucune URL distante202  await expect(thumb.locator('img[src^="data:image/png"]')).toHaveCount(1)203  expect(await page.evaluate(() => (window as unknown as { pwned?: unknown }).pwned)).toBeUndefined()204205  await c.getByRole("link", { name: "Ouvrir le modèle Modèle piégé" }).click()206  await expect(page).toHaveURL(new RegExp(`/templates/${evil.id}$`))207  const frame = previewFrame(page)208  await expect(frame.locator("body")).toContainText("Contenu du modèle piégé")209  await expect(frame.locator("script")).toHaveCount(0)210  await expect(frame.locator("[onerror]")).toHaveCount(0)211  await expect(frame.locator("img")).toHaveCount(2)212  for (const src of await frame.locator("img").evaluateAll((els) => els.map((e) => e.getAttribute("src") ?? ""))) expect(src).toMatch(/^data:image\/(png|gif);base64,/)213  const iframe = page.locator('[data-testid="preview-stage"] iframe')214  expect(await iframe.getAttribute("sandbox")).not.toMatch(/allow-scripts|allow-same-origin/)215  expect(await iframe.getAttribute("srcdoc")).toContain("default-src 'none'; img-src data:")216  expect(await page.evaluate(() => (window as unknown as { pwned?: unknown }).pwned)).toBeUndefined()217  // même chose avec la source brute affichée218  await page.getByRole("button", { name: "Afficher les variables brutes" }).click()219  await expect(frame.locator("body")).toContainText("Contenu du modèle piégé")220  expect(await page.evaluate(() => (window as unknown as { pwned?: unknown }).pwned)).toBeUndefined()221  // aucune requête vers example.org autrement que par le mandataire (vérifié aussi, pour toute origine tierce, en fin d'essai)222  expect(watch.requests.filter((u) => u.includes("example.org") && !u.includes("/api/img?u="))).toEqual([])223  expect(watch.requests.some((u) => u.includes("/api/img?u=https%3A%2F%2Fexample.org%2Ft.gif"))).toBe(true)224  // aucun contenu du modèle dans le document de l'application225  expect(await page.locator("body").innerHTML()).not.toContain("Contenu du modèle piégé<")226  await request.delete(`/api/templates/${evil.id}`, { headers: API_HEADERS })227})228229// ================================================================ création par IA (flux rejoué)230test("création par IA : progression honnête, puis ouverture du modèle dans l'éditeur", async ({ page, request }) => {231  const made = await seedRecorded(request)232  await pretendAiConfigured(page)233  await stubGeneration(page, replay, recordedScenario(made, { delay: 60, firstDelay: 600 }))234  const sent = replay.requests.length235  await page.goto("/templates")236  await expect(page.getByTestId("template-card").first()).toBeVisible()237  await page.keyboard.press("n")238  await expect(page).toHaveURL(/\/templates\/new$/)239  await axe(page, "generator")240241  // briefs de départ : un clic remplit le brief et la catégorie ; changer de langue traduit un brief non retouché242  await page.getByRole("button", { name: "Bienvenue", exact: true }).click()243  const brief = page.getByLabel("Brief")244  await expect(brief).toHaveValue(/^Courriel de bienvenue envoyé juste après l'inscription/)245  await expect(page.getByLabel("Catégorie")).toHaveValue("transactional")246  await page.getByRole("radio", { name: "English" }).click()247  await expect(brief).toHaveValue(/^Welcome email sent right after sign-up/)248  await page.getByRole("radio", { name: "Français" }).click()249  await brief.fill("court")250  await expect(page.getByRole("button", { name: "Générer le modèle" })).toBeDisabled()251  await brief.fill(BRIEF)252  await page.screenshot({ path: `${OUT}/shots/generator.png` })253  await page.getByRole("button", { name: "Générer le modèle" }).click()254255  const gen = page.getByTestId("generation")256  await expect(gen).toHaveAttribute("data-phase", "running")257  await expect(gen.getByRole("heading", { name: "L'IA rédige votre modèle" })).toBeVisible()258  await expect(gen.getByText("Connexion au service…")).toBeVisible()259  await expect(gen.getByTestId("gen-elapsed")).toHaveText(/^0:0\d$/)260  await expect(gen.getByTestId("gen-chars")).toHaveText("—")261  await expect(gen.locator(".tpl-skel.active")).toBeVisible()262  await expect(gen.getByText(/%/)).toHaveCount(0) // aucun pourcentage inventé263  await expect(page.getByLabel("Brief")).toBeDisabled()264  // les caractères écrits viennent des événements `progress`265  await expect.poll(async () => Number((await gen.getByTestId("gen-chars").textContent())?.replace(/\D/g, "") || 0)).toBeGreaterThan(2000)266  await expect(gen.getByRole("status")).toContainText("Génération lancée")267  await page.screenshot({ path: `${OUT}/shots/generating.png` })268269  await expect(page).toHaveURL(new RegExp(`/templates/${made.id}$`), { timeout: 20_000 })270  await expect(page.getByRole("heading", { level: 1, name: made.name })).toBeVisible()271  await expect(toastText(page, /Modèle créé en 92 s/)).toBeVisible()272  await expect(previewFrame(page).locator("body")).toContainText("Bienvenue,")273  expect(replay.requests.length).toBe(sent + 1)274  expect(replay.requests.at(-1)).toMatchObject({ brief: BRIEF, language: "fr", category: "transactional" })275})276277test("création par IA : annuler interrompt la requête, relancer repart de la même demande", async ({ page, request }) => {278  const made = (await listTemplates(request)).find((t) => t.name === recordedTemplate().name)!279  await pretendAiConfigured(page)280  await stubGeneration(page, replay, recordedScenario(made, { delay: 400 }))281  await page.goto("/templates/new")282  await page.getByLabel("Brief").fill(BRIEF)283  await page.getByLabel("Brief").press("ControlOrMeta+Enter")284  const gen = page.getByTestId("generation")285  await expect(gen.getByTestId("gen-chars")).not.toHaveText("—")286  const aborted = replay.aborted287  await gen.getByRole("button", { name: "Annuler la génération" }).click()288  await expect(gen).toHaveAttribute("data-phase", "cancelled")289  await expect(gen.getByText("Vous avez annulé la génération. Rien n'a été enregistré.")).toBeVisible()290  await expect.poll(() => replay.aborted).toBe(aborted + 1) // la connexion a bien été fermée : le serveur arrête la génération291  await expect(page).toHaveURL(/\/templates\/new$/)292  await expect(page.getByLabel("Brief")).toHaveValue(BRIEF)293  // relancer294  await stubGeneration(page, replay, recordedScenario(made, { delay: 5 }))295  await gen.getByRole("button", { name: "Relancer" }).click()296  await expect(page).toHaveURL(new RegExp(`/templates/${made.id}$`))297  expect(replay.requests.at(-1)).toMatchObject({ brief: BRIEF })298})299300test("création par IA : chaque code d'erreur a son message et permet de réessayer", async ({ page, request, watch }) => {301  watch.allow.push(/status of (429|400)/) // réponses hors flux voulues plus bas302  const made = (await listTemplates(request)).find((t) => t.name === recordedTemplate().name)!303  await pretendAiConfigured(page)304  await page.goto("/templates/new")305  await page.getByLabel("Brief").fill(BRIEF)306  const gen = page.getByTestId("generation")307  const cases: [string, RegExp, boolean][] = [308    ["ai_refused", /a refusé cette demande/, true],309    ["ai_rate_limited", /momentanément saturé/, true],310    ["ai_output_truncated", /trop long : l'écriture a été coupée/, true],311    ["ai_invalid_output", /résultat inexploitable/, true],312    ["ai_unreachable", /injoignable pour le moment/, true],313    ["ai_error", /raison inattendue/, true],314    ["ai_not_configured", /Aucune clé d'IA n'est configurée/, false],315    ["code_inconnu", /raison inattendue/, true],316  ]317  for (const [code, message, retry] of cases) {318    await stubGeneration(page, replay, errorScenario(code))319    await page.getByRole("button", { name: "Générer le modèle" }).click()320    await expect(gen).toHaveAttribute("data-phase", "error")321    await expect(gen.getByRole("alert")).toContainText(message)322    await expect(gen.getByRole("alert")).toHaveAttribute("data-error", code === "code_inconnu" ? "ai_error" : code)323    await expect(gen.getByRole("button", { name: "Réessayer" })).toHaveCount(retry ? 1 : 0)324    await expect(page).toHaveURL(/\/templates\/new$/)325    await gen.getByRole("button", { name: "Masquer" }).click()326    await expect(gen).toHaveCount(0)327  }328  // flux coupé sans `done` ni `error`329  await stubGeneration(page, replay, truncatedScenario())330  await page.getByRole("button", { name: "Générer le modèle" }).click()331  await expect(gen.getByRole("alert")).toContainText("La connexion a été coupée pendant la génération")332  await expect(gen.getByRole("alert")).toContainText("caractères avaient été écrits")333  // limite horaire (429 JSON) et brief refusé (400 JSON) : réponses hors flux334  for (const [status, error, message] of [[429, "rate_limited", /30 générations par heure/], [400, "invalid_request", /Le brief a été refusé/]] as const) {335    await page.unroute("**/api/templates/generate")336    await page.route("**/api/templates/generate", (route) => route.fulfill({ status, json: { error, message: "x" } }))337    await gen.getByRole("button", { name: "Réessayer" }).click()338    await expect(gen.getByRole("alert")).toContainText(message)339  }340  // réessayer après une erreur : même demande, cette fois menée au bout341  await stubGeneration(page, replay, recordedScenario(made, { delay: 5 }))342  await gen.getByRole("button", { name: "Réessayer" }).click()343  await expect(page).toHaveURL(new RegExp(`/templates/${made.id}$`))344})345346test("création par IA : sans clé configurée, le serveur répond 503 et la page l'explique", async ({ page, watch }) => {347  test.skip(REAL_AI, "le backend a une clé d'IA dans ce mode")348  watch.allow.push(/status of 503/)349  await page.goto("/templates/new")350  // la page le sait dès le chargement de la bibliothèque…351  await expect(page.getByTestId("ai-not-configured")).toContainText("Aucune clé d'IA n'est configurée sur ce serveur")352  // …et l'explique encore si l'on tente la génération (vraie réponse 503 JSON du backend, hors flux)353  await page.getByLabel("Brief").fill(BRIEF)354  const response = page.waitForResponse("**/api/templates/generate")355  await page.getByRole("button", { name: "Générer le modèle" }).click()356  const r = await response357  expect(r.status()).toBe(503)358  expect(((await r.json()) as { error: string }).error).toBe("ai_not_configured")359  const gen = page.getByTestId("generation")360  await expect(gen.getByRole("alert")).toContainText("Aucune clé d'IA n'est configurée sur ce serveur")361  await expect(gen.getByRole("alert")).toHaveAttribute("data-error", "ai_not_configured")362  await expect(gen.getByRole("button", { name: "Réessayer" })).toHaveCount(0)363  await expect(page.getByTestId("ai-usage")).toContainText("IA non configurée sur ce serveur")364})365366test("création par IA : quitter pendant une génération demande confirmation", async ({ page, request }) => {367  const made = (await listTemplates(request)).find((t) => t.name === recordedTemplate().name)!368  await pretendAiConfigured(page)369  await stubGeneration(page, replay, recordedScenario(made, { delay: 500 }))370  await page.goto("/templates")371  await page.getByRole("link", { name: "Créer avec l'IA" }).click()372  await page.getByLabel("Brief").fill(BRIEF)373  await page.getByRole("button", { name: "Générer le modèle" }).click()374  const gen = page.getByTestId("generation")375  await expect(gen).toHaveAttribute("data-phase", "running")376  // lien interne377  await page.getByRole("link", { name: "Modèles" }).click()378  const dialog = page.getByRole("alertdialog", { name: "Interrompre la génération ?" })379  await expect(dialog).toBeVisible()380  await dialog.getByRole("button", { name: "Annuler", exact: true }).click()381  await expect(page).toHaveURL(/\/templates\/new$/)382  await expect(gen).toHaveAttribute("data-phase", "running")383  // bouton Précédent du navigateur384  await page.goBack()385  await expect(dialog).toBeVisible()386  await expect(page).toHaveURL(/\/templates\/new$/)387  await page.keyboard.press("Escape")388  await expect(dialog).toHaveCount(0)389  await expect(gen).toHaveAttribute("data-phase", "running")390  // fermeture de l'onglet : le navigateur est prévenu (beforeunload)391  expect(await page.evaluate(() => !window.dispatchEvent(new Event("beforeunload", { cancelable: true })))).toBe(true)392  // confirmation : la génération est annulée et la navigation a lieu393  const aborted = replay.aborted394  await page.getByRole("link", { name: "Modèles" }).click()395  await dialog.getByRole("button", { name: "Annuler la génération et quitter" }).click()396  await expect(page).toHaveURL(/\/templates$/)397  await expect.poll(() => replay.aborted).toBe(aborted + 1)398})399400test("identité de marque : enregistrée dans les préférences, conservée au rechargement, transmise à la génération", async ({ page, request }) => {401  // d'autres préférences existent déjà : elles doivent survivre402  await request.put("/api/prefs", { headers: API_HEADERS, data: { theme: "light", density: "comfortable", lang: "fr", remoteImages: "block", trustedSenders: ["amie@example.org"] } })403  const made = (await listTemplates(request)).find((t) => t.name === recordedTemplate().name)!404  await pretendAiConfigured(page)405  await stubGeneration(page, replay, recordedScenario(made, { delay: 5 }))406  await page.goto("/templates/new")407  await page.locator("summary", { hasText: "Identité de marque" }).click()408  await page.getByLabel("Nom", { exact: true }).fill("Atelier Boréal")409  const accent = page.getByLabel("Couleur d'accent", { exact: true })410  await accent.fill("#zz")411  await expect(page.getByText("Format attendu : # suivi de six chiffres hexadécimaux")).toBeVisible()412  await accent.fill("#AA3355")413  await expect(page.getByLabel("Choisir la couleur d'accent")).toHaveValue("#aa3355")414  await page.getByLabel("Logo (adresse https)").fill("https://atelier-boreal.example/logo.png")415  await page.getByLabel("Ton", { exact: true }).fill("chaleureux, sobre")416  const saved = page.waitForResponse((r) => r.url().endsWith("/api/prefs") && r.request().method() === "PUT" && (r.request().postData() ?? "").includes("chaleureux, sobre"))417  await page.getByLabel("Ligne de pied de page").fill("12 rue du Four, Québec")418  await page.getByLabel("Ligne de pied de page").blur()419  await saved420  await expect.poll(async () => ((await (await request.get("/api/me")).json()) as { user: { prefs: Record<string, unknown> } }).user.prefs.templateBrand).toEqual({ name: "Atelier Boréal", accent: "#aa3355", logo_url: "https://atelier-boreal.example/logo.png", tone: "chaleureux, sobre", footer: "12 rue du Four, Québec" })421  const prefs = ((await (await request.get("/api/me")).json()) as { user: { prefs: Record<string, unknown> } }).user.prefs422  expect(prefs).toMatchObject({ theme: "light", lang: "fr", remoteImages: "block", trustedSenders: ["amie@example.org"] })423424  await page.reload()425  await expect(page.getByText("5 champs remplis")).toBeVisible()426  await expect(page.getByLabel("Nom", { exact: true })).toHaveValue("Atelier Boréal") // le bloc se rouvre seul quand il est rempli427  await expect(page.getByLabel("Couleur d'accent", { exact: true })).toHaveValue("#aa3355")428  await expect(page.getByLabel("Ligne de pied de page")).toHaveValue("12 rue du Four, Québec")429  await page.getByLabel("Brief").fill(BRIEF)430  await page.getByRole("button", { name: "Générer le modèle" }).click()431  await expect(page).toHaveURL(new RegExp(`/templates/${made.id}$`))432  expect(replay.requests.at(-1)).toMatchObject({ brand: { name: "Atelier Boréal", accent: "#aa3355", logo_url: "https://atelier-boreal.example/logo.png", tone: "chaleureux, sobre", footer: "12 rue du Four, Québec" } })433  await request.put("/api/prefs", { headers: API_HEADERS, data: { theme: "system", lang: "fr" } })434})435436// ================================================================ éditeur437test("éditeur : variables en direct, variables brutes, retour aux exemples, variable obligatoire manquante", async ({ page, request }) => {438  const tpl = await seedSimple(request, "Éditeur — variables", {439    html: `<!DOCTYPE html><html><body><p>Bonjour {{first_name}}, commande {{order_id}}, code {{promo_code}}.</p></body></html>`,440    variables: [441      { name: "first_name", description: "Prénom de la personne", example: "Camille", required: true },442      { name: "order_id", description: "Numéro de commande", example: "A-1042", required: true },443      { name: "promo_code", description: "Code promo", example: "", required: true },444    ],445  })446  await page.goto(`/templates/${tpl.id}`)447  const frame = previewFrame(page)448  await expect(frame.locator("body")).toContainText("Bonjour Camille, commande A-1042, code .")449  // ligne de boîte de réception : expéditeur, objet et texte d'aperçu rendus450  const inbox = page.getByTestId("inbox-line")451  await expect(inbox).toContainText("Studio Essai")452  await expect(inbox.getByTestId("inbox-subject")).toHaveText("Commande A-1042 confirmée")453  await expect(inbox.getByTestId("inbox-preheader")).toContainText("Merci Camille, tout est en ordre")454  // variable obligatoire sans exemple ni valeur455  await expect(page.getByTestId("missing-variables")).toContainText("{{promo_code}}")456  const first = page.locator('[data-variable="first_name"]')457  await expect(first).toHaveAttribute("placeholder", "Camille")458  await expect(first).toHaveAttribute("aria-required", "true")459  await expect(page.getByText("Prénom de la personne")).toBeVisible()460461  await first.fill("Zoé <b>&")462  await expect(frame.locator("body")).toContainText("Bonjour Zoé <b>&, commande") // valeur échappée, jamais interprétée463  await expect(frame.locator("b")).toHaveCount(0)464  await expect(inbox.getByTestId("inbox-preheader")).toContainText("Merci Zoé <b>&")465  await page.locator('[data-variable="order_id"]').fill("Z-9")466  await expect(inbox.getByTestId("inbox-subject")).toHaveText("Commande Z-9 confirmée")467  await page.locator('[data-variable="promo_code"]').fill("ÉTÉ10")468  await expect(page.getByTestId("missing-variables")).toHaveCount(0)469  await expect(frame.locator("body")).toContainText("code ÉTÉ10.")470471  await page.getByRole("checkbox", { name: "Afficher les {{variables}} brutes" }).check()472  await expect(frame.locator("body")).toContainText("Bonjour {{first_name}}, commande {{order_id}}, code {{promo_code}}.")473  await expect(inbox.getByTestId("inbox-subject")).toHaveText("Commande {{order_id}} confirmée")474  await page.getByRole("checkbox", { name: "Afficher les {{variables}} brutes" }).uncheck()475  await page.getByRole("button", { name: "Revenir aux exemples" }).click()476  await expect(first).toHaveValue("")477  await expect(frame.locator("body")).toContainText("Bonjour Camille, commande A-1042")478  await expect(page.getByTestId("missing-variables")).toBeVisible()479  // les valeurs d'aperçu ne salissent pas le modèle480  await expect(page.getByTestId("save-state")).toContainText("Enregistré · version 1")481  await expect(page.getByTestId("save")).toBeDisabled()482})483484test("éditeur : rendu sombre forcé, cadre de téléphone, ajustement", async ({ page, request }) => {485  const tpl = (await listTemplates(request)).find((t) => t.name === "Confirmation de commande")!486  await page.goto(`/templates/${tpl.id}`)487  const frame = previewFrame(page)488  const stage = page.getByTestId("preview-stage")489  const cardEl = frame.locator("table.card")490  await expect(cardEl).toHaveCSS("background-color", "rgb(255, 255, 255)")491  await expect(frame.locator("h1")).toHaveCSS("font-size", "28px")492  await page.getByRole("button", { name: "Sombre" }).click()493  await expect(stage).toHaveAttribute("data-scheme", "dark")494  await expect(cardEl).toHaveCSS("background-color", "rgb(32, 32, 32)")495  await expect(frame.locator("body")).toHaveCSS("background-color", "rgb(16, 16, 16)")496  await page.screenshot({ path: `${OUT}/shots/editor-dark.png` })497  // le rendu ne dépend pas du thème du système : système sombre + « Clair » reste clair498  await page.emulateMedia({ colorScheme: "dark" })499  await expect(cardEl).toHaveCSS("background-color", "rgb(32, 32, 32)")500  await page.getByRole("button", { name: "Clair" }).click()501  await expect(cardEl).toHaveCSS("background-color", "rgb(255, 255, 255)")502  await page.emulateMedia({ colorScheme: "light" })503504  // téléphone : cadre de 390 px dans un appareil, les requêtes média du modèle s'appliquent505  await page.getByRole("button", { name: "Téléphone" }).click()506  await expect(stage).toHaveAttribute("data-device", "mobile")507  await expect(stage.locator(".tpl-device.mobile")).toBeVisible()508  const iframe = stage.locator("iframe")509  expect(await iframe.evaluate((el) => (el as HTMLIFrameElement).style.width)).toBe("390px")510  await expect(frame.locator("h1")).toHaveCSS("font-size", "22px")511  await page.screenshot({ path: `${OUT}/shots/editor-mobile-frame.png` })512  await page.getByRole("button", { name: "Ordinateur" }).click()513  await expect(frame.locator("h1")).toHaveCSS("font-size", "28px")514  expect(await iframe.evaluate((el) => (el as HTMLIFrameElement).style.width)).toBe("680px")515  // ajustement : dans une fenêtre étroite le cadre est réduit ; sans ajustement il garde sa taille réelle516  await page.setViewportSize({ width: 1200, height: 800 })517  await expect(page.locator(".tpl-zoom")).not.toHaveText(/^100/)518  const fitted = (await stage.locator(".tpl-frame").boundingBox())!.width519  expect(fitted).toBeLessThan(680)520  await page.getByRole("button", { name: "Ajuster à la largeur" }).click()521  await expect(page.locator(".tpl-zoom")).toHaveText(/^100/)522  expect((await stage.locator(".tpl-frame").boundingBox())!.width).toBe(680)523  await noOverflow(page)524})525526test("éditeur : modifier le HTML et enregistrer crée la version 2 ; un <script> saisi est signalé puis retiré", async ({ page, request }) => {527  const tpl = await seedSimple(request, "Éditeur — source")528  await page.goto(`/templates/${tpl.id}`)529  await expect(page.getByTestId("save-state")).toContainText("Enregistré · version 1")530  await page.getByRole("tab", { name: "HTML" }).click()531  const source = page.getByRole("textbox", { name: "Source HTML du modèle" })532  await expect(source).toHaveValue(/^<!DOCTYPE html>/)533  await expect(page.locator(".tpl-code-gutter pre")).toContainText("12")534535  // recherche dans la source (Ctrl/⌘+F), résultat sélectionné536  await source.focus()537  await page.keyboard.press("ControlOrMeta+f")538  const find = page.getByRole("searchbox", { name: "Rechercher", exact: true })539  await expect(find).toBeFocused()540  await find.fill("padding")541  await expect(page.locator(".tpl-find-count")).toHaveText(/^1 sur \d+$/)542  await find.press("Enter")543  await expect(page.locator(".tpl-find-count")).toHaveText(/^2 sur \d+$/)544  expect(await source.evaluate((el) => (el as HTMLTextAreaElement).value.slice((el as HTMLTextAreaElement).selectionStart, (el as HTMLTextAreaElement).selectionEnd))).toBe("padding")545  await find.press("Escape")546  await expect(source).toBeFocused()547  // tabulation : indente au lieu de quitter le champ ; Échap puis Tab quitte548  await source.evaluate((el) => (el as HTMLTextAreaElement).setSelectionRange(0, 0))549  await page.keyboard.press("Tab")550  await expect(source).toHaveValue(/^ {2}<!DOCTYPE html>/)551  await expect(source).toBeFocused()552  await page.keyboard.press("ControlOrMeta+z")553  await page.keyboard.press("Escape")554  await page.keyboard.press("Tab")555  await expect(source).not.toBeFocused()556  // retour automatique à la ligne557  await page.getByRole("button", { name: "Retour automatique à la ligne" }).click()558  await expect(page.locator(".tpl-code.wrap")).toBeVisible()559  await page.getByRole("button", { name: "Retour automatique à la ligne" }).click()560561  const html = (await source.inputValue()).replace("Voir la commande", "Suivre mon colis").replace("</body>", `<script>window.pwned=1</script><p onclick="window.pwned=1">Merci {{first_name}} !</p></body>`)562  await source.fill(html)563  await expect(page.getByTestId("save-state")).toContainText("Modifications non enregistrées")564  // aperçu de la saisie non enregistrée (POST /api/templates/preview)565  await expect(previewFrame(page).locator("body")).toContainText("Suivre mon colis")566  await expect(previewFrame(page).locator("body")).toContainText("Merci Camille !")567  const notice = page.getByTestId("sanitize-notice")568  await expect(notice).toContainText("Du contenu actif sera retiré à l'enregistrement")569  await expect(notice).toContainText("Scripts (balises <script>)")570  await expect(notice).toContainText("Gestionnaires d'événements")571  await expect(notice).toHaveAttribute("role", "status")572573  await page.keyboard.press("ControlOrMeta+s")574  await expect(page.getByTestId("save-state")).toContainText("Enregistré · version 2")575  await expect(toastText(page, "Enregistré — version 2")).toBeVisible()576  await expect(notice).toContainText("Le serveur a retiré du contenu actif")577  await expect(notice).toContainText("Scripts (balises <script>)")578  await expect(source).not.toHaveValue(/<script|onclick/)579  await expect(source).toHaveValue(/Suivre mon colis/)580  expect(await page.evaluate(() => (window as unknown as { pwned?: unknown }).pwned)).toBeUndefined()581  const stored = (await (await request.get(`/api/templates/${tpl.id}`)).json()) as { version: number; html: string }582  expect(stored.version).toBe(2)583  expect(stored.html).not.toMatch(/<script|onclick/)584  await notice.getByRole("button", { name: "Masquer" }).click()585  await expect(notice).toHaveCount(0)586587  // champs : objet avec insertion de variable et compteur, texte brut, renommage seul = pas de nouvelle version588  await page.getByRole("tab", { name: "Contenu" }).click()589  const subject = page.getByLabel("Objet", { exact: true })590  await subject.fill("Votre commande est en route, ")591  await page.getByRole("button", { name: "Insérer une variable dans : Objet" }).click()592  await page.getByRole("menuitem", { name: "{{first_name}}" }).click()593  await expect(subject).toHaveValue("Votre commande est en route, {{first_name}}")594  await expect(page.getByTestId("inbox-subject")).toHaveText("Votre commande est en route, Camille")595  await expect(page.locator('[data-testid$="-subject-count"]')).toHaveText("36 / 60")596  await subject.fill("Un objet volontairement beaucoup trop long pour tenir sur l'écran d'un téléphone")597  await expect(page.getByText("Au-delà de 60 caractères, l'objet est souvent tronqué sur téléphone.")).toBeVisible()598  await subject.fill("Votre commande est en route, {{first_name}}")599  await page.getByRole("tab", { name: "Texte brut" }).click()600  await page.getByRole("textbox", { name: "Version texte brut du modèle" }).fill("Bonjour {{first_name}}, votre colis est en route.")601  await page.getByTestId("save").click()602  await expect(page.getByTestId("save-state")).toContainText("Enregistré · version 3")603  await page.getByRole("tab", { name: "Contenu" }).click()604  await page.getByLabel("Nom du modèle").fill("Éditeur — source (renommé)")605  await page.getByTestId("save").click()606  await expect(toastText(page, /^Enregistré$/)).toBeVisible()607  await expect(page.getByTestId("save-state")).toContainText("Enregistré · version 3")608  await expect(page.getByRole("heading", { level: 1, name: "Éditeur — source (renommé)" })).toBeVisible()609})610611test("éditeur : tiroir des versions, aperçu d'une version, restauration en un clic", async ({ page, request }) => {612  const tpl = (await listTemplates(request)).find((t) => t.name === "Éditeur — source (renommé)")!613  await page.goto(`/templates/${tpl.id}`)614  await page.getByRole("button", { name: /^Versions?( \d+)?$/ }).click()615  const drawer = page.getByTestId("versions-drawer")616  await expect(drawer).toBeVisible()617  await expect(drawer).toHaveAttribute("aria-modal", "true")618  await expect(drawer.getByText("Version 3")).toBeVisible()619  await expect(drawer.getByText("actuelle")).toBeVisible()620  await expect(drawer.locator(".tpl-version")).toHaveCount(2)621  await expect(drawer.locator('.tpl-version[data-version="2"]')).toContainText("Remplacée par : modification manuelle")622  await expect(drawer.locator('.tpl-version[data-version="1"]')).toContainText(/\d+ o|Ko/)623  await axe(page, "versions-drawer")624  // Échap ferme le tiroir et rend le focus au bouton625  await page.keyboard.press("Escape")626  await expect(drawer).toHaveCount(0)627  await expect(page.getByRole("button", { name: /^Versions?( \d+)?$/ })).toBeFocused()628629  await page.getByRole("button", { name: /^Versions?( \d+)?$/ }).click()630  await drawer.locator('.tpl-version[data-version="1"]').click()631  const old = drawer.frameLocator("iframe")632  await expect(old.locator("body")).toContainText("Voir la commande")633  await expect(old.locator("body")).not.toContainText("Suivre mon colis")634  await page.screenshot({ path: `${OUT}/shots/versions.png` })635  await drawer.getByRole("button", { name: "Restaurer cette version" }).click()636  await expect(toastText(page, "Version 1 restaurée — c'est maintenant la version 4")).toBeVisible()637  await expect(drawer.locator(".tpl-version")).toHaveCount(3)638  await expect(drawer.locator('.tpl-version[data-version="3"]')).toContainText("restauration de la version 1")639  await drawer.getByRole("button", { name: "Fermer" }).click()640  await expect(page.getByTestId("save-state")).toContainText("Enregistré · version 4")641  await expect(previewFrame(page).locator("body")).toContainText("Voir la commande")642  await expect(page.getByLabel("Objet", { exact: true })).toHaveValue("Commande {{order_id}} confirmée")643})644645test("éditeur : retouche par IA (flux rejoué) → nouvelle version ; indisponible tant que des modifications ne sont pas enregistrées", async ({ page, request }) => {646  const tpl = await seedSimple(request, "Éditeur — retouche")647  await pretendAiConfigured(page)648  await page.goto(`/templates/${tpl.id}`)649  const instruction = page.getByLabel("Instruction de retouche")650  await page.getByRole("button", { name: "Rends le bouton plus sobre" }).click()651  await expect(instruction).toHaveValue("Rends le bouton plus sobre")652  // modifications non enregistrées : la retouche partirait de la version enregistrée, elle est donc retenue653  await page.getByLabel("Nom du modèle").fill("Éditeur — retouche !")654  await expect(page.getByTestId("revise")).toBeDisabled()655  await expect(page.getByText("Enregistrez d'abord vos modifications")).toBeVisible()656  await page.getByLabel("Nom du modèle").fill("Éditeur — retouche")657  await expect(page.getByTestId("revise")).toBeEnabled()658659  // le serveur de rejeu « retouche » : la version 2 est créée par l'API, puis annoncée par l'événement `done`660  const revised = (await (await request.put(`/api/templates/${tpl.id}`, { headers: API_HEADERS, data: { html: tpl.html.replace("background:#2c5b4d;color:#ffffff", "background:#ffffff;color:#2c5b4d;border:1px solid #2c5b4d"), note: "retouche par IA : Rends le bouton plus sobre" } })).json()) as { version: number }661  expect(revised.version).toBe(2)662  await stubGeneration(page, replay, recordedScenario(revised, { delay: 40, revising: true }))663  await page.getByTestId("revise").click()664  const gen = page.getByTestId("generation")665  await expect(gen.getByRole("heading", { name: "L'IA retouche votre modèle" })).toBeVisible()666  await expect(page.getByText("Le contenu est verrouillé pendant la retouche.")).toBeVisible()667  await expect(page.getByTestId("save")).toBeDisabled()668  await expect(toastText(page, "Retouche terminée — version 2")).toBeVisible({ timeout: 20_000 })669  expect(replay.requests.at(-1)).toMatchObject({ brief: "Rends le bouton plus sobre", base_template_id: tpl.id, language: "fr" })670  await expect(page.getByTestId("save-state")).toContainText("Enregistré · version 2")671  await expect(previewFrame(page).locator("a")).toHaveCSS("background-color", "rgb(255, 255, 255)")672  await expect(instruction).toHaveValue("")673  await page.getByRole("button", { name: /^Versions?( \d+)?$/ }).click()674  await expect(page.getByTestId("versions-drawer").locator('.tpl-version[data-version="1"]')).toContainText("retouche par IA : Rends le bouton plus sobre")675  await page.keyboard.press("Escape")676677  // erreur pendant une retouche : message précis, le modèle reste intact et modifiable678  await instruction.fill("Ajoute une section FAQ de trois questions")679  await stubGeneration(page, replay, errorScenario("ai_output_truncated"))680  await page.getByTestId("revise").click()681  await expect(gen.getByRole("alert")).toContainText("trop long : l'écriture a été coupée")682  await expect(page.getByLabel("Nom du modèle")).toBeEditable()683  await gen.getByRole("button", { name: "Masquer" }).click()684  await expect(page.getByTestId("save-state")).toContainText("Enregistré · version 2")685})686687test("éditeur : export (téléchargement rendu et source, copie HTML et texte), poids et alerte de troncature", async ({ page, request }) => {688  const tpl = (await listTemplates(request)).find((t) => t.name === "Confirmation de commande")!689  await page.goto(`/templates/${tpl.id}`)690  await expect(previewFrame(page).locator("body")).toContainText("Bonjour Camille")691  await page.locator('[data-variable="first_name"]').fill("Noémie")692  await expect(previewFrame(page).locator("body")).toContainText("Bonjour Noémie")693  await expect(page.getByTestId("size")).toHaveText(/^1[,.]\d\sKo$/)694695  await page.getByRole("button", { name: "Exporter" }).click()696  await expect(page.getByRole("menu", { name: "Exporter" })).toContainText(/Poids du HTML : 1[,.]\d\sKo/)697  const [rendered] = await Promise.all([page.waitForEvent("download"), page.getByRole("menuitem", { name: "Télécharger le HTML rendu" }).click()])698  expect(rendered.suggestedFilename()).toBe("confirmation-de-commande.html")699  const renderedHtml = fs.readFileSync(await rendered.path(), "utf8")700  expect(renderedHtml).toContain("Bonjour Noémie, votre commande A-1042 est confirmée.")701  expect(renderedHtml).not.toContain("{{")702  expect(renderedHtml).toContain("@media (prefers-color-scheme:dark)") // l'export est le vrai modèle, pas le document d'aperçu703  expect(renderedHtml).not.toContain("Content-Security-Policy")704705  await page.getByRole("button", { name: "Exporter" }).click()706  const [raw] = await Promise.all([page.waitForEvent("download"), page.getByRole("menuitem", { name: "Télécharger la source (avec variables)" }).click()])707  expect(raw.suggestedFilename()).toBe("confirmation-de-commande-source.html")708  expect(fs.readFileSync(await raw.path(), "utf8")).toContain("Bonjour {{first_name}}, votre commande {{order_id}} est confirmée.")709710  await page.getByRole("button", { name: "Exporter" }).click()711  await page.getByRole("menuitem", { name: "Copier le HTML rendu" }).click()712  await expect(toastText(page, "HTML copié")).toBeVisible()713  expect(await page.evaluate(() => navigator.clipboard.readText())).toContain("Bonjour Noémie, votre commande A-1042")714  await page.getByRole("button", { name: "Exporter" }).click()715  await page.getByRole("menuitem", { name: "Copier le texte brut" }).click()716  expect(await page.evaluate(() => navigator.clipboard.readText())).toBe("Bonjour Noémie, votre commande A-1042 est confirmée.")717718  // au-delà d'environ 100 Ko : alerte de troncature par Gmail, sans bloquer719  await page.getByRole("tab", { name: "HTML" }).click()720  const source = page.getByRole("textbox", { name: "Source HTML du modèle" })721  const big = (await source.inputValue()).replace("</body>", `${"<p>Paragraphe de remplissage pour dépasser la limite de Gmail.</p>\n".repeat(1700)}</body>`)722  await source.fill(big)723  await expect(page.getByTestId("size")).toHaveAttribute("data-level", "clipped")724  await expect(page.getByTestId("size")).toContainText("Gmail tronquera ce message")725  await expect(page.getByTestId("size-warning")).toContainText("Gmail tronque les messages de plus de 102 Ko")726  // l'éditeur reste réactif sur ce document (> 100 Ko) : une frappe est prise en compte sans délai sensible727  await source.evaluate((el) => (el as HTMLTextAreaElement).setSelectionRange(0, 0))728  await source.focus()729  const t0 = Date.now()730  await page.keyboard.type("<!-- x -->")731  await expect(source).toHaveValue(/^<!-- x -->/)732  expect(Date.now() - t0).toBeLessThan(3000)733  await expect(page.locator(".tpl-code-gutter pre")).toContainText("1700")734})735736test("éditeur : garde des modifications non enregistrées (lien, bouton Précédent, fermeture)", async ({ page, request }) => {737  const tpl = (await listTemplates(request)).find((t) => t.name === "Confirmation de commande")!738  await page.goto("/templates")739  await card(page, "Confirmation de commande").getByRole("link").click()740  await expect(page).toHaveURL(new RegExp(`/templates/${tpl.id}$`))741  // sans modification : aucune garde742  expect(await page.evaluate(() => !window.dispatchEvent(new Event("beforeunload", { cancelable: true })))).toBe(false)743  await page.getByRole("textbox", { name: "Texte d'aperçu" }).fill("Un nouveau texte d'aperçu, pas encore enregistré, assez long pour être correct.")744  await expect(page.getByTestId("save-state")).toContainText("Modifications non enregistrées")745  expect(await page.evaluate(() => !window.dispatchEvent(new Event("beforeunload", { cancelable: true })))).toBe(true)746747  await page.getByRole("link", { name: "Modèles" }).click()748  const dialog = page.getByRole("alertdialog", { name: "Quitter sans enregistrer ?" })749  await expect(dialog).toBeVisible()750  await dialog.getByRole("button", { name: "Annuler", exact: true }).click()751  await expect(page).toHaveURL(new RegExp(`/templates/${tpl.id}$`))752  await expect(page.getByRole("textbox", { name: "Texte d'aperçu" })).toHaveValue(/pas encore enregistré/)753  await page.goBack()754  await expect(dialog).toBeVisible()755  await expect(page).toHaveURL(new RegExp(`/templates/${tpl.id}$`))756  await dialog.getByRole("button", { name: "Quitter sans enregistrer" }).click()757  await expect(page).toHaveURL(/\/templates$/)758  await expect(page.getByTestId("template-card").first()).toBeVisible()759  const stored = (await (await request.get(`/api/templates/${tpl.id}`)).json()) as { preheader: string; version: number }760  expect(stored.preheader).not.toContain("pas encore enregistré")761  // une fois enregistré : plus de garde762  await card(page, "Confirmation de commande").getByRole("link").click()763  await page.getByRole("textbox", { name: "Texte d'aperçu" }).fill("Merci {{first_name}}, tout est en ordre : voici le récapitulatif complet.")764  await page.getByTestId("save").click()765  await expect(page.getByTestId("save-state")).toContainText("Enregistré · version 2")766  await page.getByRole("link", { name: "Modèles" }).click()767  await expect(page).toHaveURL(/\/templates$/)768})769770test("éditeur : « Utiliser dans un message » copie le HTML rendu et dit honnêtement ce que la rédaction ne garde pas", async ({ page, request }) => {771  const tpl = (await listTemplates(request)).find((t) => t.name === "Confirmation de commande")!772  await page.goto(`/templates/${tpl.id}`)773  await expect(previewFrame(page).locator("body")).toContainText("Bonjour Camille")774  await page.getByRole("button", { name: "Utiliser dans un message" }).click()775  const dialog = page.getByRole("dialog", { name: "Utiliser ce modèle" })776  await expect(dialog.getByText("La rédaction de SP Mail ne conserve pas la mise en page d'un modèle")).toBeVisible()777  await expect(dialog.getByText(/la feuille de style .* les images et les attributs de mise en page des tableaux y sont retirés/)).toBeVisible()778  // ce compte d'essai n'a aucune boîte : seul le HTML est copié (avec une boîte, un message s'ouvre avec l'objet prérempli)779  await expect(dialog.getByText("Aucune boîte de courrier n'est rattachée à ce compte")).toBeVisible()780  await dialog.getByRole("button", { name: "Copier le HTML rendu" }).click()781  await expect(toastText(page, "HTML rendu copié dans le presse-papiers")).toBeVisible()782  const copied = await page.evaluate(() => navigator.clipboard.readText())783  expect(copied).toContain("Bonjour Camille, votre commande A-1042 est confirmée.")784  expect(copied).toContain("<style>")785  // envoi par l'API : en service — commande cURL et corps JSON de ce modèle, clé lue dans $SPMAIL_API_KEY (jamais de jeton)786  await expect(dialog.getByText("Bientôt disponible")).toHaveCount(0)787  const curl = (await dialog.getByTestId("api-curl").textContent()) ?? ""788  expect(curl).toContain("/api/v1/messages/send")789  expect(curl).toContain('-H "Authorization: Bearer $SPMAIL_API_KEY"')790  expect(curl).toContain(`"template_id": "${tpl.id}"`)791  expect(curl).not.toMatch(/spm_[A-Za-z0-9]/)792  const example = JSON.parse((await dialog.locator(".tpl-api-example").textContent()) ?? "{}") as { template_id: string; variables: Record<string, string> }793  expect(example.template_id).toBe(tpl.id)794  expect(example.variables).toEqual({ first_name: "Camille", order_id: "A-1042", order_url: "https://boutique.example/commandes/A-1042" })795  await axe(page, "use-dialog")796  await page.keyboard.press("Escape")797  await expect(dialog).toHaveCount(0)798})799800test("éditeur : dupliquer et supprimer depuis l'éditeur ; modèle introuvable", async ({ page, request, watch }) => {801  watch.allow.push(/status of 404/)802  const tpl = await seedSimple(request, "Éditeur — à dupliquer")803  await page.goto(`/templates/${tpl.id}`)804  await page.getByRole("button", { name: "Autres actions" }).click()805  await page.getByRole("menuitem", { name: "Dupliquer" }).click()806  await expect(page.getByRole("heading", { level: 1, name: "Éditeur — à dupliquer (copie)" })).toBeVisible()807  expect(page.url()).not.toContain(tpl.id)808  await page.getByRole("button", { name: "Autres actions" }).click()809  await page.getByRole("menuitem", { name: "Supprimer" }).click()810  await expect(page).toHaveURL(/\/templates$/)811  await expect(card(page, "Éditeur — à dupliquer (copie)")).toHaveCount(0)812  await toastText(page, "Modèle supprimé").getByRole("button", { name: "Annuler" }).click()813  await expect(card(page, "Éditeur — à dupliquer (copie)")).toBeVisible()814  await page.goto("/templates/00000000-0000-4000-8000-000000000000")815  await expect(page.getByRole("heading", { name: "Ce modèle est introuvable" })).toBeVisible()816  await page.getByRole("button", { name: "Retour à la bibliothèque" }).click()817  await expect(page).toHaveURL(/\/templates$/)818})819820test("éditeur : accessibilité (axe, onglets au clavier, aide des raccourcis), thèmes clair et sombre", async ({ page, request }) => {821  const tpl = (await listTemplates(request)).find((t) => t.name === recordedTemplate().name)!822  await page.goto(`/templates/${tpl.id}`)823  await expect(previewFrame(page).locator("body")).toContainText("Bienvenue,")824  await axe(page, "editor")825  await page.screenshot({ path: `${OUT}/shots/editor.png` })826  // onglets : flèches, un seul onglet dans l'ordre de tabulation827  const tabs = page.getByRole("tablist", { name: "Parties du modèle" })828  await tabs.getByRole("tab", { name: "Contenu" }).focus()829  await page.keyboard.press("ArrowRight")830  await expect(tabs.getByRole("tab", { name: "HTML" })).toBeFocused()831  await expect(tabs.getByRole("tab", { name: "HTML" })).toHaveAttribute("aria-selected", "true")832  await expect(page.getByRole("tabpanel", { name: "HTML" })).toBeVisible()833  await axe(page, "editor-html")834  await page.keyboard.press("End")835  await expect(tabs.getByRole("tab", { name: "Texte brut" })).toBeFocused()836  await page.keyboard.press("Home")837  await expect(tabs.getByRole("tab", { name: "Contenu" })).toHaveAttribute("tabindex", "0")838  await expect(tabs.getByRole("tab", { name: "HTML" })).toHaveAttribute("tabindex", "-1")839  // aide « ? » : les raccourcis du studio y figurent840  await page.locator(".tpl-status").click()841  await page.keyboard.press("?")842  const help = page.getByRole("dialog", { name: "Raccourcis clavier" })843  await expect(help.getByRole("heading", { name: "Modèles" })).toBeVisible()844  await expect(help.getByText("Enregistrer le modèle")).toBeVisible()845  await expect(help.getByText("Rechercher dans la source")).toBeVisible()846  await expect(help.getByText("Conversation suivante")).toBeVisible()847  await page.keyboard.press("Escape")848  await expect(help).toHaveCount(0)849  // thème sombre de l'application : contraste AA vérifié par axe850  await page.emulateMedia({ colorScheme: "dark" })851  await page.waitForTimeout(400) // fin des transitions de couleur des boutons852  await axe(page, "editor-dark-theme")853  await page.screenshot({ path: `${OUT}/shots/editor-dark-theme.png` })854  await page.goto("/templates")855  await expect(page.getByTestId("template-card").first()).toBeVisible()856  await axe(page, "library-dark-theme")857  await page.goto("/templates/new")858  await page.locator("summary", { hasText: "Identité de marque" }).click()859  await axe(page, "generator-dark-theme")860  await page.emulateMedia({ colorScheme: "light", reducedMotion: "reduce" })861  await axe(page, "generator-brand")862  // mouvement réduit : aucune animation en boucle863  await page.goto("/templates")864  expect(await page.locator(".tpl-card").first().evaluate((el) => getComputedStyle(el).transitionDuration)).toMatch(/^0\.001ms|^1e-06s|^0s/)865})866867// ================================================================ un seul essai réel (coûte de l'argent) : E2E_AI=1868test("IA réelle : un brief devient un modèle ouvert dans l'éditeur", async ({ page }) => {869  test.skip(!REAL_AI, "essai réel sur demande seulement : E2E_AI=1")870  test.setTimeout(360_000)871  await page.goto("/templates/new")872  await expect(page.getByTestId("ai-not-configured")).toHaveCount(0)873  await page.getByRole("button", { name: "Lien de connexion" }).click()874  await page.getByRole("button", { name: "Générer le modèle" }).click()875  const gen = page.getByTestId("generation")876  await expect(gen).toHaveAttribute("data-phase", "running")877  await expect.poll(async () => Number((await gen.getByTestId("gen-chars").textContent())?.replace(/\D/g, "") || 0), { timeout: 120_000 }).toBeGreaterThan(400)878  await expect(page).toHaveURL(/\/templates\/[0-9a-f-]{36}$/, { timeout: 300_000 })879  await expect(page.getByTestId("save-state")).toContainText("Enregistré · version 1")880  await expect(previewFrame(page).locator("body")).not.toBeEmpty()881  await expect(page.getByRole("heading", { name: "Notes de conception" })).toBeVisible()882  await expect(page.getByTestId("ai-usage")).toContainText(/1 génération/)883  await page.screenshot({ path: `${OUT}/shots/real-ai.png` })884})885
Files main
Menu

Theme