SPB Git

Repository Public

settings.part.ts 35.8 KB 597 lines typescript

1/**2 * =============================================================================3 *                  SP BOUCHER | SOFTWARE & RESEARCH4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : SP Mail8 * File             : tests/e2e/next-prod/settings.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 de la zone « settings » : Réglages › Notifications (préférences des appareils, état de l'envoi, appareils),44// notifications du navigateur (niveau d'aperçu, onglet caché, rafale), Réglages › Règles (constructeur, essai à blanc, exécution réelle,45// journal, ordre, activation, suppression) et renvois Sieve ⇄ règles.46import { expect, test, type Page } from "@playwright/test"47import { toastText } from "../helpers"48import { THEMES, type Harness, type Part } from "./harness"4950interface PushPrefs {51  enabled: boolean52  preview: string53  quiet_hours: { start: string; end: string; tz: string } | null54  priority_senders: string[]55  priority_only: boolean56  mailboxes: Record<string, boolean>57  badge: string58}59interface RuleOut {60  id: string61  name: string62  enabled: boolean63  position: number64  match: string65  conditions: unknown[]66  actions: unknown[]67  mailbox_ids: string[] | null68  stop: boolean69}70interface Note {71  title: string72  body: string73  tag: string74}75const pushPrefs = (h: Harness, p: Page = h.page) => h.api<PushPrefs>(p, "GET", "/api/next/push/prefs")76const rules = async (h: Harness) => (await h.api<{ data: RuleOut[] }>(h.page, "GET", "/api/next/rules")).data77const saved = (p: Page) => expect(p.getByTestId("push-saved")).toHaveText("Enregistré.")78/** Un dialogue passé à axe dans les trois thèmes et capturé (la palette ne s'ouvre pas par-dessus un dialogue : il est rouvert à chaque thème). */79async function themedDialog(h: Harness, p: Page, name: string, open: () => Promise<void>, close: () => Promise<void>) {80  for (const [theme, label] of THEMES) {81    await h.setTheme(p, label, theme)82    await open()83    await h.axe(p, `${name}-${theme}`)84    if (theme !== "dark") await h.shot(p, `${name}-${theme}`)85    await close()86  }87  await h.setTheme(p, "Clair", "light")88}89/** Remplace `window.Notification` avant tout script de la page : les notifications créées sont consignées dans `window.__notes`. */90const stubNotification = (p: Page, permission: "granted" | "denied" | "default") =>91  p.addInitScript((permission) => {92    const w = window as unknown as { __notes: unknown[]; __asked: number; Notification: unknown }93    w.__notes = []94    w.__asked = 095    class FakeNotification {96      static permission = permission97      static requestPermission = async () => {98        w.__asked++99        return FakeNotification.permission100      }101      onclick: (() => void) | null = null102      constructor(public title: string, opts: { body?: string; tag?: string } = {}) {103        w.__notes.push({ title, body: opts.body ?? "", tag: opts.tag ?? "", self: this })104      }105      close() {}106    }107    w.Notification = FakeNotification108  }, permission)109const notes = (p: Page) => p.evaluate(() => (window as unknown as { __notes: Note[] }).__notes.map(({ title, body, tag }) => ({ title, body, tag })))110const setHidden = (p: Page, hidden: boolean) =>111  p.evaluate((hidden) => {112    Object.defineProperty(document, "hidden", { configurable: true, get: () => hidden })113    Object.defineProperty(document, "visibilityState", { configurable: true, get: () => (hidden ? "hidden" : "visible") })114  }, hidden)115116export const settingsPart: Part = (h) => {117  const subj = (x: string) => `Réglage ${x} ${h().run}`118119  test("settings : notifications — préférences des appareils enregistrées et relues, état de l'envoi, appareils", async () => {120    const { page, P1, P2 } = h()121    const before = await pushPrefs(h())122    expect(before).toMatchObject({ enabled: true, preview: "sender", quiet_hours: null, priority_senders: [], priority_only: false, badge: "inbox" })123    await page.goto("/settings/profile")124    await page.getByRole("navigation", { name: "Réglages" }).getByRole("link", { name: "Notifications" }).click()125    await expect(page).toHaveURL(/\/settings\/notifications$/)126    await expect(page.getByRole("heading", { level: 2, name: "Notifications" })).toBeVisible()127    // ---- ce qui vaut pour les appareils natifs est dit clairement ; l'absence d'APNs aussi128    await expect(page.getByTestId("push-native-note")).toContainText("s'appliquent à vos appareils")129    await expect(page.getByTestId("push-native-note")).toContainText("Le web est simplement un endroit commode pour les gérer")130    const status = await h().api<{ configured: boolean; last_error: string | null }>(page, "GET", "/api/next/push/status")131    await expect(page.getByTestId("push-status")).toHaveAttribute("data-configured", String(status.configured))132    if (!status.configured) {133      await expect(page.getByTestId("push-status")).toContainText("Les notifications push ne sont pas configurées sur ce serveur")134      await expect(page.getByTestId("push-test")).toBeDisabled()135    }136    // aucun appareil natif dans ce parcours : seul l'état vide est vérifiable137    await expect(page.getByTestId("push-devices-empty")).toContainText("Aucun appareil enregistré.")138    expect((await h().api<{ data: unknown[] }>(page, "GET", "/api/next/push/devices")).data).toEqual([])139140    // ---- aperçu141    await page.getByTestId("push-preview-full").click()142    await expect(page.getByTestId("push-preview-full")).toHaveAttribute("aria-checked", "true")143    await expect(page.getByTestId("push-prefs")).toContainText("La notification montre l'expéditeur, l'objet et le début du message.")144    await saved(page)145    // ---- heures calmes : plage par défaut à cheval sur minuit, dans le fuseau du navigateur ; début modifié146    await page.getByTestId("push-quiet").check()147    await expect(page.getByTestId("push-quiet-start")).toHaveValue("22:00")148    await expect(page.getByTestId("push-quiet-tz")).toHaveValue("America/Toronto")149    await expect.poll(async () => (await pushPrefs(h())).quiet_hours).toEqual({ start: "22:00", end: "07:00", tz: "America/Toronto" })150    await page.getByTestId("push-quiet-start").fill("21:30")151    await expect(page.getByTestId("push-prefs")).toContainText("De 21:30 à 07:00 le lendemain")152    await expect.poll(async () => (await pushPrefs(h())).quiet_hours?.start).toBe("21:30")153    // plage vide : refusée ici, rien n'est envoyé au serveur154    await page.getByTestId("push-quiet-end").fill("21:30")155    await expect(page.getByTestId("push-prefs").getByRole("alert")).toHaveText("Le début et la fin sont identiques : la plage ne couvre aucun moment.")156    await page.waitForTimeout(400)157    expect((await pushPrefs(h())).quiet_hours).toEqual({ start: "21:30", end: "07:00", tz: "America/Toronto" })158    await page.getByTestId("push-quiet-end").fill("06:45")159    await expect.poll(async () => (await pushPrefs(h())).quiet_hours?.end).toBe("06:45")160    // ---- expéditeurs prioritaires : syntaxe validée, doublon refusé161    const input = page.getByTestId("push-sender-input")162    await input.fill("pas une adresse")163    await input.press("Enter")164    await expect(page.getByTestId("push-prefs").getByRole("alert")).toContainText("Indiquez une adresse complète")165    await input.fill("@Example.org")166    await input.press("Enter")167    await expect(page.getByTestId("push-senders")).toContainText("@example.org")168    await input.fill(P2.toUpperCase())169    await page.getByRole("button", { name: "Ajouter", exact: true }).click()170    await expect(page.getByTestId("push-senders").locator("li")).toHaveCount(2)171    await input.fill("@example.org")172    await input.press("Enter")173    await expect(page.getByTestId("push-prefs").getByRole("alert")).toHaveText("Cet expéditeur est déjà dans la liste.")174    await input.fill("")175    await page.getByTestId("push-priority-only").check()176    // ---- par boîte : la seconde est coupée177    await page.locator(`[data-testid="push-mailbox"][data-address="${P2}"]`).uncheck()178    await page.getByTestId("push-badge").uncheck()179    const mb2 = await h().mailboxId(page, P2)180    const expected = { enabled: true, preview: "full", quiet_hours: { start: "21:30", end: "06:45", tz: "America/Toronto" }, priority_senders: ["@example.org", P2], priority_only: true, mailboxes: { [mb2]: false }, badge: "none" }181    await expect.poll(() => pushPrefs(h())).toEqual(expected)182183    // ---- relues après rechargement184    await page.reload()185    await expect(page.getByTestId("push-preview-full")).toHaveAttribute("aria-checked", "true")186    await expect(page.getByTestId("push-quiet")).toBeChecked()187    await expect(page.getByTestId("push-quiet-start")).toHaveValue("21:30")188    await expect(page.getByTestId("push-quiet-end")).toHaveValue("06:45")189    await expect(page.getByTestId("push-senders").locator("li")).toHaveText(["@example.org", P2])190    await expect(page.getByTestId("push-priority-only")).toBeChecked()191    await expect(page.locator(`[data-testid="push-mailbox"][data-address="${P1}"]`)).toBeChecked()192    await expect(page.locator(`[data-testid="push-mailbox"][data-address="${P2}"]`)).not.toBeChecked()193    await expect(page.getByTestId("push-badge")).not.toBeChecked()194195    await h().axeThemes(page, "settings-notifications")196    await h().shotThemes(page, "settings-notifications")197198    // ---- retrait d'un expéditeur, tout couper : le reste est figé ; remise en état pour la suite199    await page.getByRole("button", { name: "Retirer @example.org" }).click()200    await expect(page.getByTestId("push-senders").locator("li")).toHaveCount(1)201    await page.getByTestId("push-enabled").uncheck()202    await expect.poll(async () => (await pushPrefs(h())).enabled).toBe(false)203    await expect(page.getByTestId("push-preview-none")).toBeDisabled()204    await h().api(page, "PUT", "/api/next/push/prefs", { enabled: true, preview: "sender", quiet_hours: null, priority_senders: [], priority_only: false, mailboxes: {}, badge: "inbox" })205206    // ---- palette207    await page.goto("/")208    await h().openBox(page, P1)209    await h().palette(page, ">réglages notifications", "Réglages : Notifications")210    await expect(page).toHaveURL(/\/settings\/notifications$/)211  })212213  test("settings : notifications du navigateur — permission, aperçu « none / sender / full », rafale, onglet visible, clic", async () => {214    const { P1 } = h()215    const { ctx, p } = await h().fromStorage({ width: 1280, height: 800 })216    try {217      await ctx.grantPermissions(["notifications"])218      await stubNotification(p, "granted")219      const mb1 = await (async () => {220        await p.goto("/settings/notifications")221        return h().mailboxId(p, P1)222      })()223      // ---- option propre à ce navigateur, coupée par défaut224      const sw = p.getByTestId("web-notify-switch")225      await expect(sw).not.toBeChecked()226      await expect(p.getByTestId("web-notify-state")).toContainText("Désactivées.")227      await sw.check()228      await expect(sw).toBeChecked()229      await expect(p.getByTestId("web-notify-state")).toContainText("Activées. Aperçu affiché : expéditeur.")230      expect(await p.evaluate(() => localStorage.getItem("spmail.webNotify"))).toBe("1")231232      const arm = async (preview: "none" | "sender" | "full") => {233        await h().api(p, "PUT", "/api/next/push/prefs", { preview })234        await p.goto("/")235        await h().openBox(p, P1)236        await expect(p.locator("#sidebar").getByRole("link", { name: "Centre de commande" })).toBeVisible()237        // le premier relevé (chargement) ne notifie jamais, même onglet caché et messages non lus présents238        await setHidden(p, true)239        await p.waitForTimeout(2500)240        expect(await notes(p)).toEqual([])241      }242      const from: [string, string] = ["Expéditrice Web", "expeditrice@example.org"]243      const arrived = async (n: number) => {244        await expect.poll(() => notes(p), { timeout: 30_000 }).toHaveLength(n)245        return (await notes(p))[n - 1]246      }247248      // ---- « none » : rien du message ; deux messages arrivés ensemble = une seule notification249      await arm("none")250      await h().seed(p, P1, [251        { subject: subj("notif A"), from, preview: "Premier.", minutesAgo: 0 },252        { subject: subj("notif B"), from, preview: "Second.", minutesAgo: 0 },253      ])254      expect(await arrived(1)).toEqual({ title: "SP Mail", body: "2 nouveaux messages", tag: `spmail-${mb1}` })255      await p.waitForTimeout(2500)256      expect(await notes(p)).toHaveLength(1)257      // onglet visible : aucune notification, et rien n'est rejoué quand il est caché de nouveau258      await setHidden(p, false)259      await h().seed(p, P1, [{ subject: subj("notif visible"), from, preview: "Vu à l'écran.", minutesAgo: 0 }])260      await expect(p.getByRole("option", { name: new RegExp(subj("notif visible")) })).toBeVisible({ timeout: 30_000 })261      await setHidden(p, true)262      await p.waitForTimeout(2500)263      expect(await notes(p)).toHaveLength(1)264265      // ---- « sender » : le nom de l'expéditeur, pas l'objet266      await arm("sender")267      await h().seed(p, P1, [{ subject: subj("notif C"), from, preview: "Troisième.", minutesAgo: 0 }])268      expect(await arrived(1)).toEqual({ title: "Expéditrice Web", body: "Nouveau message", tag: `spmail-${mb1}` })269270      // ---- « full » : expéditeur et objet271      await arm("full")272      await h().seed(p, P1, [{ subject: subj("notif D"), from, preview: "Quatrième.", minutesAgo: 0 }])273      expect(await arrived(1)).toEqual({ title: "Expéditrice Web", body: subj("notif D"), tag: `spmail-${mb1}` })274275      // ---- clic : l'onglet revient sur la boîte de réception de la boîte concernée276      await setHidden(p, false)277      await p.locator("#sidebar").getByRole("link", { name: "Centre de commande" }).click()278      await expect(p).toHaveURL(/\/dashboard$/)279      await p.evaluate(() => (window as unknown as { __notes: { self: { onclick: () => void } }[] }).__notes[0].self.onclick())280      await expect(p).toHaveURL(/\/m\/\d+\/inbox$/)281      await expect(p.getByRole("heading", { level: 2, name: P1 })).toBeVisible()282      // la pastille de non lus du titre de l'onglet est toujours là283      await expect.poll(() => p.title()).toMatch(/^\(\d+\) SP Mail$/)284285      // ---- option coupée : plus rien286      await p.goto("/settings/notifications")287      await p.getByTestId("web-notify-switch").uncheck()288      expect(await p.evaluate(() => localStorage.getItem("spmail.webNotify"))).toBeNull()289      await h().api(p, "PUT", "/api/next/push/prefs", { preview: "sender" })290    } finally {291      await ctx.close()292    }293294    // ---- permission refusée par le navigateur : dite clairement, interrupteur figé295    const denied = await h().fromStorage({ width: 1280, height: 800 })296    try {297      await stubNotification(denied.p, "denied")298      await denied.p.goto("/settings/notifications")299      await expect(denied.p.getByTestId("web-notify-switch")).toBeDisabled()300      await expect(denied.p.getByTestId("web-notify-state")).toContainText("Les notifications sont bloquées pour ce site dans les réglages du navigateur.")301    } finally {302      await denied.ctx.close()303    }304    // ---- permission jamais demandée puis refusée au moment du geste : l'option reste coupée305    const asked = await h().fromStorage({ width: 1280, height: 800 })306    try {307      await stubNotification(asked.p, "default")308      await asked.p.goto("/settings/notifications")309      await asked.p.getByTestId("web-notify-switch").click()310      expect(await asked.p.evaluate(() => (window as unknown as { __asked: number }).__asked)).toBe(1)311      await expect(asked.p.getByTestId("web-notify-switch")).not.toBeChecked()312      expect(await asked.p.evaluate(() => localStorage.getItem("spmail.webNotify"))).toBeNull()313    } finally {314      await asked.ctx.close()315    }316    // ---- navigateur sans notifications317    const none = await h().fromStorage({ width: 1280, height: 800 })318    try {319      await none.p.addInitScript(() => {320        delete (window as unknown as { Notification?: unknown }).Notification321      })322      await none.p.goto("/settings/notifications")323      await expect(none.p.getByTestId("web-notify-state")).toHaveText("Ce navigateur ne propose pas les notifications.")324      await expect(none.p.getByTestId("web-notify-switch")).toBeDisabled()325    } finally {326      await none.ctx.close()327    }328  })329330  test("settings : règles — constructeur, essai à blanc, exécution sur un vrai message, journal, ordre, activation, suppression", async () => {331    test.setTimeout(240_000)332    const { page, P1, P2 } = h()333    const labelName = `Règle ${h().run}`334    const label = await h().api<{ id: string; keyword: string }>(page, "POST", "/api/next/labels", { name: labelName })335    await h().seed(page, P1, [336      { subject: subj("règle hors sujet"), from: ["Autre", "autre@example.org"], preview: "Ne correspond pas.", minutesAgo: 6 },337      { subject: subj("règle correspond"), from: ["Prod Deux", P2], preview: "Correspond à la règle.", minutesAgo: 3 },338    ])339    const ai = (await h().api<{ provider: string }>(page, "GET", "/api/next/ai/settings")).provider !== "off"340    const name = `De P2 ${h().run}`341342    await page.goto("/settings/rules")343    await expect(page.getByRole("heading", { level: 2, name: "Règles" })).toBeVisible()344    // ---- la différence avec les filtres Sieve est expliquée345    await expect(page.getByTestId("rules-explain")).toContainText("Les règles s'exécutent après la livraison")346    await expect(page.getByTestId("rules-explain")).toContainText("Une règle n'envoie jamais de courrier.")347    await expect(page.getByTestId("rules-explain")).toContainText("Les filtres de livraison (Sieve) s'exécutent avant, dans le serveur de courrier")348    await expect(page.getByTestId("rules-empty")).toBeVisible()349350    // ---- nouvelle règle : rien de valide tant que le formulaire est vide351    await page.getByTestId("rule-add").click()352    const dlg = page.getByRole("dialog", { name: "Nouvelle règle" })353    await dlg.getByTestId("rule-save").click()354    await expect(dlg.locator(".nx-set-issues li")).toHaveText(["Donnez un nom à la règle (80 caractères au plus).", "Condition 1 : indiquez une valeur (300 caractères au plus).", "Action 1 : choisissez un libellé."])355    expect(await rules(h())).toEqual([])356    // ---- le constructeur propose chaque champ et chaque action du serveur, avec le bon champ de saisie357    const cond = dlg.getByTestId("rule-condition").first()358    expect(await cond.getByLabel("Champ").locator("option").evaluateAll((os) => os.map((o) => (o as HTMLOptionElement).value))).toEqual(["from", "to", "subject", "list", "has_attachment", "is_newsletter", "ai_category", "size"])359    await cond.getByLabel("Champ").selectOption("has_attachment")360    await expect(cond.getByLabel("Valeur")).toHaveValue("1")361    await cond.getByLabel("Champ").selectOption("size")362    await expect(cond.getByLabel("Taille", { exact: true })).toBeVisible()363    await expect(cond.getByLabel("Unité")).toHaveValue("mb")364    await cond.getByLabel("Champ").selectOption("ai_category")365    await expect(cond.getByLabel("Valeur").locator("option")).toHaveCount(7)366    await expect(cond).toContainText("Requiert Intelligence.")367    if (!ai) await expect(cond).toContainText("Elle est désactivée : activez-la dans Réglages › Intelligence.")368    await cond.getByLabel("Champ").selectOption("to")369    expect(await cond.getByLabel("Opérateur").locator("option").evaluateAll((os) => os.map((o) => (o as HTMLOptionElement).value))).toEqual(["contains", "equals", "matches_domain"])370    const act = dlg.getByTestId("rule-action").first()371    expect(await act.getByLabel("Type d'action").locator("option").evaluateAll((os) => os.map((o) => (o as HTMLOptionElement).value))).toEqual(["label", "star", "mark_read", "pin", "snooze", "remind", "event", "notify_app", "draft_reply", "extract"])372    await act.getByLabel("Type d'action").selectOption("snooze")373    await act.getByLabel("Jusqu'à").selectOption("hours")374    await expect(act.getByLabel("Nombre")).toHaveValue("3")375    await act.getByLabel("Type d'action").selectOption("remind")376    await expect(act.getByLabel("Délai du rappel")).toHaveValue("2")377    await act.getByLabel("Type d'action").selectOption("event")378    await expect(act.getByLabel("Nom de l'événement")).toBeVisible()379    await act.getByLabel("Type d'action").selectOption("notify_app")380    await expect(act.getByLabel("Nom de l'application")).toBeVisible()381    await act.getByLabel("Type d'action").selectOption("draft_reply")382    await expect(act).toContainText("Il n'est jamais envoyé")383    await expect(act.getByLabel("Extrait", { exact: true })).toBeVisible()384    await act.getByLabel("Origine du texte").selectOption("ai")385    await expect(act.getByLabel("Ton")).toHaveValue("concise")386    await expect(act).toContainText("Requiert Intelligence.")387    await act.getByLabel("Type d'action").selectOption("extract")388    await expect(act.getByLabel("Nom du champ")).toBeVisible()389    await expect(act).toContainText("Requiert Intelligence.")390    await act.getByLabel("Type d'action").selectOption("label")391392    // ---- « De contient <P2> → libellé + suivi »393    await dlg.getByLabel("Nom", { exact: true }).fill(name)394    await cond.getByLabel("Champ").selectOption("from")395    await cond.getByLabel("Valeur").fill(P2)396    await act.getByLabel("Libellé", { exact: true }).selectOption({ label: labelName })397    await dlg.getByRole("button", { name: "Ajouter une action" }).click()398    await expect(dlg.getByTestId("rule-action")).toHaveCount(2)399    await expect(dlg.getByTestId("rule-action").nth(1).getByLabel("Type d'action")).toHaveValue("star")400401    // ---- essai à blanc sur un message de la boîte : correspond, puis ne correspond pas ; rien n'est exécuté402    const dry = dlg.getByTestId("rule-test")403    await dry.getByLabel("Boîte").selectOption({ label: P1 })404    const msg = dry.getByLabel("Message")405    await expect(msg.locator("option").filter({ hasText: subj("règle correspond") })).toHaveCount(1)406    await msg.selectOption({ label: await msg.locator("option").filter({ hasText: subj("règle correspond") }).innerText() })407    await dry.getByRole("button", { name: "Tester" }).click()408    const result = dry.getByTestId("rule-test-result")409    await expect(result).toHaveAttribute("data-matched", "true")410    await expect(result).toContainText("La règle s'appliquerait à ce message.")411    await expect(result.locator('li[data-result="true"]')).toContainText(`Expéditeur contient « ${P2} »`)412    await expect(result.getByRole("list", { name: "Actions qui seraient exécutées" }).locator("li")).toHaveText([`libellé « ${labelName} »`, "marquer comme suivi"])413    await msg.selectOption({ label: await msg.locator("option").filter({ hasText: subj("règle hors sujet") }).innerText() })414    await dry.getByRole("button", { name: "Tester" }).click()415    await expect(result).toHaveAttribute("data-matched", "false")416    await expect(result.locator('li[data-result="false"]')).toHaveCount(1)417    expect(await rules(h())).toEqual([])418419    await dlg.getByTestId("rule-save").click()420    await expect(toastText(page, "Règle créée.")).toBeVisible()421    await expect(dlg).toHaveCount(0)422    const rowOf = (n: string) => page.getByTestId("rule-row").filter({ hasText: n })423    await expect(rowOf(name).getByTestId("rule-summary")).toHaveText(`Expéditeur contient « ${P2} » → libellé « ${labelName} », marquer comme suivi`)424    await expect(rowOf(name)).toContainText("Boîtes : Toutes mes boîtes")425    let api = await rules(h())426    expect(api).toHaveLength(1)427    expect(api[0]).toMatchObject({ name, enabled: true, match: "all", stop: false, mailbox_ids: null, conditions: [{ field: "from", op: "contains", value: P2 }], actions: [{ type: "label", label_id: label.id }, { type: "star" }] })428    // l'essai n'a rien touché : le message d'essai n'a ni libellé ni marque429    const keywordsOf = async (subject: string) => {430      const r = await h().jmap(page, P1, [["Email/query", { filter: { subject }, limit: 5 }, "q"], ["Email/get", { "#ids": { resultOf: "q", name: "Email/query", path: "/ids" }, properties: ["keywords", "from"] }, "g"]])431      const list = r[1][1].list as { keywords: Record<string, boolean> }[]432      return list.length ? Object.keys(list[0].keywords) : null433    }434    expect(await keywordsOf(subj("règle correspond"))).not.toContain("$flagged")435436    // ---- un vrai message P2 → P1 (le seul envoi réel de la zone) : la règle le libelle et le marque437    const sent = await h().api<{ status: string }>(page, "POST", "/api/v1/messages/send", { from: P2, to: [{ email: P1 }], subject: subj("règle réelle"), text: "Message réel pour la règle." })438    expect(["queued", "sent", "delivered"]).toContain(sent.status)439    await expect.poll(() => keywordsOf(subj("règle réelle")), { timeout: 120_000, intervals: [1500] }).toEqual(expect.arrayContaining([label.keyword, "$flagged"]))440    // ---- journal d'exécution441    await rowOf(name).getByRole("button", { name: `Journal de « ${name} »` }).click()442    const runs = page.getByRole("dialog", { name: `Journal de « ${name} »` })443    // une exécution par message : le message réel, et parfois le message d'essai déposé plus tôt si le veilleur ne l'a traité qu'après la création de la règle444    const realId = (await h().jmap(page, P1, [["Email/query", { filter: { subject: subj("règle réelle") }, limit: 1 }, "q"]]))[0][1].ids[0] as string445    const apiRuns = (await h().api<{ data: { email_id: string; mailbox_id: string; status: string; actions: { type: string; status: string }[] }[] }>(page, "GET", `/api/next/rules/${api[0].id}/runs`)).data446    const real = apiRuns.find((r) => r.email_id === realId)447    expect(real).toMatchObject({ mailbox_id: await h().mailboxId(page, P1), status: "ok", actions: [{ type: "label", status: "ok" }, { type: "star", status: "ok" }] })448    await expect(runs.getByTestId("run-row")).toHaveCount(apiRuns.length)449    const first = runs.getByTestId("run-row").first()450    await expect(first).toHaveAttribute("data-status", "ok")451    await expect(first).toContainText("Exécutée")452    await expect(first).toContainText(P1)453    await expect(first.locator('li[data-status="ok"]')).toHaveText(["Ajouter un libellé", "Marquer comme suivi"])454    await page.keyboard.press("Escape")455    await expect(runs).toHaveCount(0)456457    // ---- seconde règle (toutes les formes restantes passent par le serveur) : ordre, au clavier458    const other = `Gros fichiers ${h().run}`459    await page.getByTestId("rule-add").click()460    const dlg2 = page.getByRole("dialog", { name: "Nouvelle règle" })461    await dlg2.getByLabel("Nom", { exact: true }).fill(other)462    const c2 = dlg2.getByTestId("rule-condition").first()463    await c2.getByLabel("Champ").selectOption("size")464    await c2.getByLabel("Taille", { exact: true }).fill("2,5")465    await dlg2.getByRole("button", { name: "Ajouter une condition" }).click()466    await dlg2.getByTestId("rule-condition").nth(1).getByLabel("Champ").selectOption("has_attachment")467    await dlg2.getByRole("radio", { name: "Au moins une condition" }).check()468    const a2 = dlg2.getByTestId("rule-action").first()469    await a2.getByLabel("Type d'action").selectOption("snooze")470    await a2.getByLabel("Jusqu'à").selectOption("days")471    await a2.getByLabel("Nombre").fill("2")472    await dlg2.getByRole("button", { name: "Ajouter une action" }).click()473    const a3 = dlg2.getByTestId("rule-action").nth(1)474    await a3.getByLabel("Type d'action").selectOption("remind")475    await a3.getByLabel("Délai du rappel").fill("36")476    await a3.getByLabel("Unité du délai").selectOption("hours")477    await dlg2.getByRole("button", { name: "Ajouter une action" }).click()478    const a4 = dlg2.getByTestId("rule-action").nth(2)479    await a4.getByLabel("Type d'action").selectOption("event")480    await a4.getByLabel("Nom de l'événement").fill("Gros Fichier")481    await dlg2.getByTestId("rule-save").click()482    await expect(dlg2.locator(".nx-set-issues li")).toHaveText([/^Action 3 : nom d'événement invalide/])483    await a4.getByLabel("Nom de l'événement").fill("gros.fichier")484    await dlg2.getByLabel("Arrêter ici").check()485    await dlg2.getByRole("radio", { name: "Certaines boîtes seulement" }).check()486    await dlg2.getByRole("checkbox", { name: P1 }).check()487    await dlg2.getByTestId("rule-save").click()488    await expect(toastText(page, "Règle créée.")).toBeVisible()489    await expect(rowOf(other).getByTestId("rule-summary")).toHaveText("dépasse 2,5 Mo ou avec pièce jointe → mettre en veille (2 jours), rappel après 36 heures, événement « gros.fichier » · puis arrêter")490    await expect(rowOf(other)).toContainText(`Boîtes : ${P1}`)491    api = await rules(h())492    const mb1 = await h().mailboxId(page, P1)493    expect(api[1]).toMatchObject({494      name: other, match: "any", stop: true, mailbox_ids: [mb1], conditions: [{ field: "size", op: "gt", value: 2621440 }, { field: "has_attachment", op: "is", value: true }],495      actions: [{ type: "snooze", until_rule: "2d" }, { type: "remind", after_hours: 36 }, { type: "event", name: "gros.fichier" }],496    })497    const names = () => page.getByTestId("rule-row").evaluateAll((els) => els.map((e) => e.getAttribute("data-rule-name")))498    expect(await names()).toEqual([name, other])499    await expect(rowOf(name).getByRole("button", { name: `Monter « ${name} »` })).toBeDisabled()500    await rowOf(other).getByRole("button", { name: `Monter « ${other} »` }).focus()501    await page.keyboard.press("Enter")502    await expect.poll(names).toEqual([other, name])503    await expect.poll(async () => (await rules(h())).map((r) => [r.name, r.position])).toEqual([[other, 0], [name, 1]])504    await rowOf(other).getByRole("button", { name: `Descendre « ${other} »` }).click()505    await expect.poll(async () => (await rules(h())).map((r) => r.name)).toEqual([name, other])506    await page.reload()507    await expect.poll(names).toEqual([name, other])508509    await h().axeThemes(page, "settings-rules")510    await h().shotThemes(page, "settings-rules")511512    // ---- activer / désactiver513    const sw = rowOf(other).getByRole("switch", { name: `Activer la règle « ${other} »` })514    await expect(sw).toBeChecked()515    await sw.uncheck()516    await expect.poll(async () => (await rules(h())).find((r) => r.name === other)?.enabled).toBe(false)517    await sw.check()518    await expect.poll(async () => (await rules(h())).find((r) => r.name === other)?.enabled).toBe(true)519520    // ---- modifier : le formulaire relit la règle telle qu'enregistrée ; éditeur dans les trois thèmes521    const openEditor = async () => {522      await rowOf(other).getByRole("button", { name: `Modifier « ${other} »` }).click()523      await expect(page.getByRole("dialog", { name: "Modifier la règle" })).toBeVisible()524    }525    const closeEditor = async () => {526      await page.keyboard.press("Escape")527      await expect(page.getByRole("dialog", { name: "Modifier la règle" })).toHaveCount(0)528    }529    await themedDialog(h(), page, "rule-editor", openEditor, closeEditor)530    await openEditor()531    const edit = page.getByRole("dialog", { name: "Modifier la règle" })532    await expect(edit.getByTestId("rule-condition").first().getByLabel("Taille", { exact: true })).toHaveValue("2.5")533    await expect(edit.getByTestId("rule-action").nth(1).getByLabel("Délai du rappel")).toHaveValue("36")534    await expect(edit.getByRole("checkbox", { name: P1 })).toBeChecked()535    await expect(edit.getByLabel("Arrêter ici")).toBeChecked()536    const renamed = `Volumineux ${h().run}`537    await edit.getByLabel("Nom", { exact: true }).fill(renamed)538    await edit.getByRole("button", { name: "Retirer l'action 3" }).click()539    await edit.getByTestId("rule-save").click()540    await expect(toastText(page, "Règle enregistrée.")).toBeVisible()541    await expect(rowOf(renamed)).toBeVisible()542    expect((await rules(h())).find((r) => r.name === renamed)?.actions).toHaveLength(2)543544    // ---- supprimer, après confirmation545    await rowOf(renamed).getByRole("button", { name: `Supprimer « ${renamed} »` }).click()546    const del = page.getByRole("alertdialog", { name: "Supprimer cette règle ?" })547    await expect(del).toContainText(renamed)548    await del.getByRole("button", { name: "Supprimer" }).click()549    await expect(toastText(page, "Règle supprimée.")).toBeVisible()550    await expect(rowOf(renamed)).toHaveCount(0)551    expect((await rules(h())).map((r) => r.name)).toEqual([name])552553    // ---- renvois dans les deux sens entre règles et filtres de livraison554    await page.getByTestId("link-filters").click()555    await expect(page).toHaveURL(/\/settings\/filters$/)556    await expect(page.getByTestId("filters-rules-note")).toContainText("Pour étiqueter, mettre en veille, créer un rappel ou préparer un brouillon après la livraison")557    await page.getByTestId("link-rules").click()558    await expect(page).toHaveURL(/\/settings\/rules$/)559    await expect(rowOf(name)).toBeVisible()560    // ---- palette561    await page.goto("/")562    await h().openBox(page, P1)563    await h().palette(page, ">réglages règles", "Réglages : Règles")564    await expect(page).toHaveURL(/\/settings\/rules$/)565    // la règle restante est retirée : elle ne doit pas agir sur les messages des autres zones566    for (const r of await rules(h())) await h().api(page, "DELETE", `/api/next/rules/${r.id}`)567    await h().api(page, "DELETE", `/api/next/labels/${label.id}`).catch(() => {})568  })569570  test("settings : téléphone — Notifications, Règles et éditeur de règle", async () => {571    const { ctx, p } = await h().fromStorage({ width: 390, height: 844 }, true)572    const created = await h().api<{ id: string }>(h().page, "POST", "/api/next/rules", { name: `Mobile ${h().run}`, conditions: [{ field: "subject", op: "contains", value: "facture" }], actions: [{ type: "pin" }, { type: "mark_read" }] })573    try {574      await p.goto("/settings/notifications")575      await expect(p.getByTestId("push-prefs")).toBeVisible()576      expect(await p.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth)).toBe(true)577      await h().axe(p, "settings-notifications-phone")578      await h().shot(p, "settings-notifications-phone")579      await p.goto("/settings/rules")580      await expect(p.getByTestId("rule-row")).toHaveCount(1)581      expect(await p.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth)).toBe(true)582      await h().axe(p, "settings-rules-phone")583      await h().shot(p, "settings-rules-phone")584      await p.getByRole("button", { name: /^Modifier «/ }).click()585      const dlg = p.getByRole("dialog", { name: "Modifier la règle" })586      await expect(dlg.getByTestId("rule-condition")).toHaveCount(1)587      // (le dialogue s'ouvre avec une légère mise à l'échelle : la mesure attend la fin de l'animation)588      await expect.poll(async () => (await dlg.getByRole("button", { name: "Retirer la condition 1" }).boundingBox())!.height).toBeGreaterThanOrEqual(44)589      await h().axe(p, "rule-editor-phone")590      await h().shot(p, "rule-editor-phone")591    } finally {592      await ctx.close()593      await h().api(h().page, "DELETE", `/api/next/rules/${created.id}`)594    }595  })596}597
Files main
Menu

Theme