SPB Git

Repository Public

dashboard.part.ts 21.4 KB 352 lines typescript

1/**2 * =============================================================================3 *                  SP BOUCHER | SOFTWARE & RESEARCH4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : SP Mail8 * File             : tests/e2e/next-prod/dashboard.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 « dashboard » : centre de commande (chiffres réels, navigation de chaque élément, annulation d'un envoi44// programmé, états d'attente et vides), personnalisation (masquer, réordonner au clavier et au pointeur, largeur, persistance), téléphone.45import { expect, test, type Page } from "@playwright/test"46import { toastText } from "../helpers"47import type { Harness, Part } from "./harness"4849interface Dash {50  inbox: { mailbox_id: string; address: string; unread: number; total: number }[]51  attention: { reminders_due: number; flagged: number; snoozed_today: number; unanswered: number }52  scheduled: { id: string; recipients: { address: string }[] }[]53  pending_replies: { subject: string }[]54  recent_attachments: { name: string }[]55  top_contacts: { id: string; name: string }[]56  storage: { mailbox_id: string }[]57  delivery_issues: unknown[]58  sync: { mail_server: string; push: string }59}60const DEFAULT_ORDER = ["attention", "inbox", "pending", "scheduled", "attachments", "contacts", "storage", "issues", "sync"]61const widget = (p: Page, id: string) => p.locator(`[data-widget="${id}"]`)62const order = (p: Page) => p.locator("[data-widget]").evaluateAll((els) => els.map((e) => e.getAttribute("data-widget")))63const fresh = (h: Harness) => h.api<Dash>(h.page, "GET", "/api/next/dashboard?fresh=1")64const savedLayout = async (h: Harness) => ((await h.api<{ user: { prefs: { dashboard?: { id: string; hidden: boolean; wide: boolean }[] } } }>(h.page, "GET", "/api/me")).user.prefs.dashboard ?? [])65const stat = (p: Page, id: string) => p.getByTestId(`stat-${id}`).locator(".nx-stat-n")66const openDash = async (p: Page) => {67  await p.goto("/dashboard")68  await expect(p.getByRole("heading", { level: 1, name: "Centre de commande" })).toBeVisible()69  await expect(p.locator(".nx-dash-grid")).toHaveAttribute("aria-busy", "false")70}71const refresh = async (p: Page) => {72  const done = p.waitForResponse((r) => r.url().includes("/api/next/dashboard?fresh=1") && r.ok())73  await p.getByRole("button", { name: "Actualiser" }).click()74  await done75}7677export const dashboardPart: Part = (h) => {78  const subj = (x: string) => `Centre ${x} ${h().run}`79  let p2Index = 18081  test("dashboard : entrées (barre latérale, « g h », palette), attente, chiffres réels", async () => {82    const { page, P1, P2 } = h()83    const me = await h().api<{ mailboxes: { id: string; address: string }[] }>(page, "GET", "/api/me")84    p2Index = me.mailboxes.findIndex((m) => m.address === P2)85    const [, , remindId, snoozeId] = await h().seed(page, P1, [86      { subject: subj("suivi"), from: ["Cliente Externe", "cliente@example.org"], preview: "Message marqué, non lu.", keywords: ["$flagged"], minutesAgo: 50 },87      { subject: subj("pièce"), from: ["Prod Deux", P2], preview: "Avec une pièce jointe.", attachments: [{ name: `devis-${h().run}.txt`, type: "text/plain", text: "Devis : 1 200 $" }], minutesAgo: 40 },88      { subject: subj("rappel"), from: ["Prod Deux", P2], preview: "À relancer.", keywords: ["$seen"], minutesAgo: 30 },89      { subject: subj("veille"), from: ["Prod Deux", P2], preview: "À revoir plus tard.", keywords: ["$seen"], minutesAgo: 20 },90    ])91    await h().seed(page, P2, [{ subject: subj("autre boîte"), from: ["Prod Un", P1], preview: "Non lu dans la seconde boîte.", minutesAgo: 10 }])92    const mb1 = await h().mailboxId(page, P1)93    // rappel échu (le travailleur le fait passer à « due »), mise en veille de 3 h, envoi programmé à +26 h (aucun envoi réel)94    await h().api(page, "POST", "/api/next/reminders", { mailbox_id: mb1, email_id: remindId, due_at: new Date(Date.now() + 1500).toISOString() })95    await h().api(page, "POST", "/api/next/snoozes", { mailbox_id: mb1, email_ids: [snoozeId], until: new Date(Date.now() + 3 * 3600_000).toISOString() })96    const sched = await h().api<{ status: string }>(page, "POST", "/api/v1/messages/send", { from: P1, to: [{ email: P2 }], subject: subj("programmé"), text: "Plus tard.", send_at: new Date(Date.now() + 26 * 3600_000).toISOString() })97    expect(sched.status).toBe("scheduled")98    await expect.poll(async () => (await h().api<{ data: unknown[] }>(page, "GET", "/api/next/reminders?status=due")).data.length, { timeout: 20_000 }).toBe(1)99100    // ---- entrée de la barre latérale ; squelettes tant que la réponse n'est pas arrivée101    await page.goto("/")102    await h().openBox(page, P1)103    await page.route("**/api/next/dashboard*", async (route) => {104      await new Promise((r) => setTimeout(r, 900))105      await route.continue()106    })107    await page.locator("#sidebar").getByRole("link", { name: "Centre de commande" }).click()108    await expect(page).toHaveURL(/\/dashboard$/)109    await expect(page.locator(".nx-dash-skel").first()).toBeVisible()110    await expect(page.locator(".nx-dash-grid")).toHaveAttribute("aria-busy", "true")111    await expect(page.locator(".nx-dash-grid")).toHaveAttribute("aria-busy", "false")112    await page.unroute("**/api/next/dashboard*")113    await expect(page.locator(".nx-dash-skel")).toHaveCount(0)114    expect(await order(page)).toEqual(DEFAULT_ORDER)115    await expect(page.locator("#sidebar").getByRole("link", { name: "Centre de commande" })).toHaveAttribute("aria-current", "page")116117    // ---- raccourci « g h » et palette, depuis la boîte de réception118    await page.goto("/")119    await h().openBox(page, P1)120    await page.keyboard.press("g")121    await page.keyboard.press("h")122    await expect(page).toHaveURL(/\/dashboard$/)123    await page.goto("/")124    await h().openBox(page, P1)125    await h().palette(page, ">centre de commande", /Centre de commande/)126    await expect(page).toHaveURL(/\/dashboard$/)127    // « g d » reste « brouillons »128    await page.goto("/")129    await h().openBox(page, P1)130    await page.keyboard.press("g")131    await page.keyboard.press("d")132    await expect(page).toHaveURL(/\/m\/\d+\/drafts$/)133134    // ---- chiffres : ceux de l'API, lus après une actualisation135    await openDash(page)136    await refresh(page)137    const d = await fresh(h())138    const box1 = d.inbox.find((b) => b.address === P1)!139    const box2 = d.inbox.find((b) => b.address === P2)!140    expect(box1.unread).toBeGreaterThanOrEqual(2)141    expect(box2.unread).toBeGreaterThanOrEqual(1)142    const rows = widget(page, "inbox").getByTestId("inbox-row")143    await expect(rows).toHaveCount(d.inbox.length)144    await expect(rows.filter({ hasText: P1 }).locator(".nx-count")).toHaveText(String(box1.unread))145    await expect(rows.filter({ hasText: P2 }).locator(".nx-count")).toHaveText(String(box2.unread))146    await expect(rows.filter({ hasText: P1 })).toContainText(`${box1.total} message`)147    expect(d.attention.reminders_due).toBe(1)148    expect(d.attention.snoozed_today).toBe(1)149    expect(d.attention.flagged).toBeGreaterThanOrEqual(1)150    await expect(stat(page, "reminders")).toHaveText("1")151    await expect(stat(page, "snoozed")).toHaveText("1")152    // la page et l'essai lisent chacun l'API : côté serveur, un sous-total dont la requête JMAP échoue est rendu à 0 sans erreur153    // (`safe(…, 0)` dans server/src/next/dashboard.ts) — on compare donc deux lectures concordantes, en réessayant154    await expect(async () => {155      await refresh(page)156      const again = await fresh(h())157      await expect(stat(page, "flagged")).toHaveText(String(again.attention.flagged), { timeout: 3000 })158      await expect(stat(page, "unanswered")).toHaveText(String(again.attention.unanswered), { timeout: 3000 })159      expect(again.attention.flagged).toBeGreaterThanOrEqual(1)160    }).toPass({ timeout: 45_000 })161    expect(d.pending_replies.some((m) => m.subject === subj("suivi"))).toBe(true)162    await expect(widget(page, "pending").getByTestId("pending-row").filter({ hasText: subj("suivi") })).toBeVisible()163    // dans le parcours complet, d'autres zones ont déposé des pièces plus récentes : le widget montre celles que le serveur rend164    expect(d.recent_attachments.length).toBeGreaterThan(0)165    await expect(widget(page, "attachments").getByTestId("attachment-row")).toHaveCount(d.recent_attachments.length)166    await expect(widget(page, "attachments").getByTestId("attachment-row").first()).toContainText(d.recent_attachments[0].name)167    await expect(widget(page, "scheduled").getByTestId("scheduled-row")).toHaveCount(1)168    await expect(widget(page, "scheduled").getByTestId("scheduled-row")).toContainText(P2)169    await expect(widget(page, "storage").getByTestId("storage-row")).toHaveCount(d.storage.length)170    // ---- états vides et état du service171    expect(d.delivery_issues).toEqual([])172    await expect(widget(page, "issues")).toContainText("Aucun incident de remise depuis 7 jours.")173    await expect(widget(page, "sync")).toContainText("Joignable")174    await expect(widget(page, "sync")).toContainText(d.sync.push === "configured" ? "Configurées" : "Non configurées")175    await expect(page.getByTestId("dash-generated").locator("time")).toHaveAttribute("datetime", /^\d{4}-\d\d-\d\dT/)176    // chiffres tabulaires du système de design177    expect(await stat(page, "flagged").evaluate((el) => getComputedStyle(el).fontVariantNumeric)).toContain("tabular-nums")178    expect(h().consoleErrors.filter((e) => /dashboard|nx-/i.test(e))).toEqual([])179  })180181  test("dashboard : chaque élément mène à sa cible ; annulation d'un envoi programmé", async () => {182    const { page, P2 } = h()183    const go = async (click: () => Promise<void>, url: RegExp) => {184      await openDash(page)185      await click()186      await expect(page).toHaveURL(url)187    }188    await go(() => widget(page, "inbox").getByTestId("inbox-row").filter({ hasText: P2 }).click(), new RegExp(`/m/${p2Index}/inbox$`))189    await go(() => page.getByTestId("stat-reminders").click(), /\/followups$/)190    await go(() => page.getByTestId("stat-snoozed").click(), /\/snoozed$/)191    await go(() => page.getByTestId("stat-flagged").click(), /\/u\/starred$/)192    await go(() => page.getByTestId("stat-unanswered").click(), /\/u\/search\?q=in%3Ainbox%20is%3Aunread$/)193    await go(() => widget(page, "pending").getByTestId("pending-row").filter({ hasText: subj("suivi") }).click(), /\/m\/\d+\/inbox\/t\/[^/]+$/)194    await go(() => widget(page, "attachments").getByTestId("attachment-row").first().click(), /\/m\/\d+\/inbox\/t\/[^/]+$/)195    await go(() => widget(page, "attachments").getByRole("link", { name: "Galerie" }).click(), /\/attachments$/)196    await go(() => widget(page, "contacts").getByRole("link", { name: "Tous les contacts" }).click(), /\/contacts$/)197    await go(() => widget(page, "scheduled").getByRole("link", { name: "Tout voir" }).click(), /\/u\/scheduled$/)198    await go(() => widget(page, "scheduled").getByTestId("scheduled-row").getByRole("link").click(), /\/u\/scheduled$/)199    await go(() => widget(page, "storage").getByRole("link", { name: "Détails" }).click(), /\/settings\/storage$/)200    // contacts importants : la liste dépend du relevé des correspondants par le serveur ; vide → état vide, sinon lien vers la fiche201    await openDash(page)202    const d = await fresh(h())203    if (d.top_contacts.length) {204      await refresh(page)205      await widget(page, "contacts").getByTestId("contact-row").first().click()206      await expect(page).toHaveURL(new RegExp(`/contacts/${d.top_contacts[0].id}$`))207    } else {208      test.info().annotations.push({ type: "note", description: "aucun contact important relevé par le serveur dans ce parcours : seul l'état vide du widget est vérifié" })209      await expect(widget(page, "contacts")).toContainText("Vos correspondants fréquents apparaîtront ici.")210    }211212    // ---- annuler l'envoi programmé depuis le widget, après confirmation213    await openDash(page)214    await refresh(page)215    const row = widget(page, "scheduled").getByTestId("scheduled-row")216    await row.getByRole("button", { name: `Annuler l'envoi programmé à ${P2}` }).click()217    const dlg = page.getByRole("alertdialog", { name: "Annuler cet envoi ?" })218    await expect(dlg).toContainText(P2)219    // « Annuler » du dialogue ne fait rien220    await dlg.getByRole("button", { name: "Annuler", exact: true }).click()221    await expect(dlg).toHaveCount(0)222    await expect(row).toHaveCount(1)223    await row.getByRole("button", { name: /Annuler l'envoi programmé/ }).click()224    await page.getByRole("alertdialog").getByRole("button", { name: "Annuler l'envoi", exact: true }).click()225    await expect(toastText(page, "Envoi annulé.")).toBeVisible()226    await expect(row).toHaveCount(0)227    await expect(widget(page, "scheduled")).toContainText("Aucun envoi programmé.")228    expect((await fresh(h())).scheduled).toEqual([])229  })230231  test("dashboard : personnaliser — masquer, réordonner (clavier, boutons, glisser), largeur 2×, persistance", async () => {232    const { page } = h()233    await openDash(page)234    await page.getByTestId("dash-customize").click()235    await expect(page.getByTestId("dash-editbar")).toBeVisible()236    const live = page.getByTestId("dash-live")237238    // ---- masquer239    await widget(page, "storage").getByRole("button", { name: "Masquer « Stockage »" }).click()240    await expect(widget(page, "storage")).toHaveCount(0)241    await expect(live).toHaveText("« Stockage » masqué.")242    await expect(page.getByTestId("show-storage")).toBeVisible()243    await expect.poll(async () => (await savedLayout(h())).find((w) => w.id === "storage")?.hidden).toBe(true)244245    // ---- clavier : flèches sur la poignée (le focus reste sur la poignée), annonce dans la région vivante246    const handle = widget(page, "inbox").getByRole("button", { name: /Déplacer « Boîtes de réception »/ })247    await handle.focus()248    await page.keyboard.press("ArrowUp")249    await expect.poll(() => order(page)).toEqual(["inbox", "attention", "pending", "scheduled", "attachments", "contacts", "issues", "sync"])250    await expect(live).toHaveText("« Boîtes de réception » en position 1 sur 8.")251    await expect(handle).toBeFocused()252    await page.keyboard.press("ArrowUp")253    await expect(live).toHaveText("« Boîtes de réception » est déjà en premier.")254    await page.keyboard.press("ArrowDown")255    await page.keyboard.press("ArrowDown")256    await expect.poll(() => order(page)).toEqual(["attention", "pending", "inbox", "scheduled", "attachments", "contacts", "issues", "sync"])257    await expect(live).toHaveText("« Boîtes de réception » en position 3 sur 8.")258    await expect(handle).toBeFocused()259    // ---- boutons « monter / descendre »260    await widget(page, "inbox").getByRole("button", { name: "Monter « Boîtes de réception »" }).click()261    await expect.poll(() => order(page)).toEqual(["attention", "inbox", "pending", "scheduled", "attachments", "contacts", "issues", "sync"])262    await expect(widget(page, "attention").getByRole("button", { name: "Monter « À traiter »" })).toBeDisabled()263    await expect(widget(page, "sync").getByRole("button", { name: "Descendre « Synchronisation »" })).toBeDisabled()264265    // ---- glisser au pointeur : « Synchronisation » déposée sur « À traiter »266    // dans le parcours complet la page est plus longue que la fenêtre : la poignée est amenée à l'écran, puis la page remonte pendant le glissement267    await widget(page, "sync").locator('[data-ctl="handle"]').scrollIntoViewIfNeeded()268    const from = (await widget(page, "sync").locator('[data-ctl="handle"]').boundingBox())!269    await page.mouse.move(from.x + from.width / 2, from.y + from.height / 2)270    await page.mouse.down()271    await expect(widget(page, "sync")).toHaveClass(/dragging/)272    await page.mouse.wheel(0, -20_000)273    await expect.poll(async () => (await widget(page, "attention").boundingBox())!.y).toBeGreaterThanOrEqual(0)274    const to = (await widget(page, "attention").boundingBox())!275    await page.mouse.move(to.x + to.width / 2, to.y + 60, { steps: 12 })276    await page.mouse.move(to.x + 80, to.y + 30, { steps: 6 })277    await page.mouse.up()278    await expect(widget(page, "sync")).not.toHaveClass(/dragging/)279    await expect.poll(async () => (await order(page))[0]).toBe("sync")280    await expect(live).toHaveText("« Synchronisation » en position 1 sur 8.")281282    // ---- largeur 2×283    const before = (await widget(page, "inbox").boundingBox())!.width284    const wide = widget(page, "inbox").getByRole("button", { name: "Largeur 2× pour « Boîtes de réception »" })285    await expect(wide).toHaveAttribute("aria-pressed", "false")286    await wide.click()287    await expect(widget(page, "inbox")).toHaveAttribute("data-wide", "true")288    await expect(wide).toHaveAttribute("aria-pressed", "true")289    await expect(wide).toBeFocused()290    expect((await widget(page, "inbox").boundingBox())!.width).toBeGreaterThan(before * 1.6)291292    await h().axeThemes(page, "dashboard-edit")293    await h().shotThemes(page, "dashboard-edit")294    await page.getByTestId("dash-customize").click()295    await expect(page.getByTestId("dash-editbar")).toHaveCount(0)296297    // ---- persistance : préférence synchronisée du compte, relue après rechargement298    const expected = await order(page)299    expect(expected[0]).toBe("sync")300    await expect.poll(async () => (await savedLayout(h())).filter((w) => !w.hidden).map((w) => w.id)).toEqual(expected)301    const saved = await savedLayout(h())302    expect(saved.find((w) => w.id === "inbox")).toEqual({ id: "inbox", hidden: false, wide: true })303    expect(saved.find((w) => w.id === "storage")?.hidden).toBe(true)304    await page.reload()305    await expect(page.locator(".nx-dash-grid")).toHaveAttribute("aria-busy", "false")306    expect(await order(page)).toEqual(expected)307    await expect(widget(page, "inbox")).toHaveAttribute("data-wide", "true")308    await expect(widget(page, "storage")).toHaveCount(0)309310    // ---- réafficher, puis réinitialiser311    await page.getByTestId("dash-customize").click()312    await page.getByTestId("show-storage").click()313    await expect(widget(page, "storage")).toBeVisible()314    await expect(live).toHaveText("« Stockage » affiché.")315    await page.getByRole("button", { name: "Réinitialiser la disposition" }).click()316    await expect.poll(() => order(page)).toEqual(DEFAULT_ORDER)317    await expect(widget(page, "inbox")).toHaveAttribute("data-wide", "false")318    await expect(page.getByRole("button", { name: "Réinitialiser la disposition" })).toBeDisabled()319    await page.getByTestId("dash-customize").click()320    await expect.poll(async () => (await savedLayout(h())).map((w) => `${w.id}:${w.hidden}:${w.wide}`)).toEqual(DEFAULT_ORDER.map((id) => `${id}:false:${id === "attention" || id === "pending"}`))321322    await h().axeThemes(page, "dashboard")323    await h().shotThemes(page, "dashboard")324  })325326  test("dashboard : téléphone — entrée « Centre » de la barre du bas, une colonne", async () => {327    const { ctx, p } = await h().fromStorage({ width: 390, height: 844 }, true)328    try {329      await p.goto("/")330      const nav = p.getByRole("navigation", { name: "Navigation principale" }).or(p.locator(".bottom-nav")).last()331      await nav.getByRole("link", { name: "Centre" }).click()332      await expect(p).toHaveURL(/\/dashboard$/)333      await expect(p.getByRole("heading", { level: 1, name: "Centre de commande" })).toBeVisible()334      await expect(p.locator(".nx-dash-grid")).toHaveAttribute("aria-busy", "false")335      await expect(p.locator(".bottom-nav")).toBeVisible()336      // une seule colonne : tous les widgets ont le même bord gauche et la même largeur337      const boxes = await p.locator("[data-widget]").evaluateAll((els) => els.map((e) => [Math.round(e.getBoundingClientRect().left), Math.round(e.getBoundingClientRect().width)]))338      expect(new Set(boxes.map((b) => b.join(":"))).size).toBe(1)339      expect(await p.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth)).toBe(true)340      await h().axe(p, "dashboard-phone")341      await h().shot(p, "dashboard-phone")342      await p.getByTestId("dash-customize").click()343      const handle = p.locator('[data-widget="inbox"] [data-ctl="handle"]')344      expect((await handle.boundingBox())!.height).toBeGreaterThanOrEqual(44)345      await h().shot(p, "dashboard-edit-phone")346      await p.getByTestId("dash-customize").click()347    } finally {348      await ctx.close()349    }350  })351}352
Files main
Menu

Theme