SPB Git

Repository Public

DashboardWidgets.tsx 19.3 KB 375 lines tsx

1/**2 * =============================================================================3 *                  SP BOUCHER | SOFTWARE & RESEARCH4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : SP Mail8 * File             : web/src/ui/next/DashboardWidgets.tsx9 * Module           : ui10 * 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 — centre de commande : contenu des widgets (réception, attention, envois programmés, réponses, pièces jointes, contacts, stockage, incidents, synchronisation).44import type { ReactNode } from "react"45import { fmtDateTime, fmtListDate, fmtNumber, getLang, t } from "../../i18n"46import { hasFeature } from "../../next/api"47import type { WidgetId } from "../../next/dashboard"48import { PENDING_SHOWN, fmtBytes, isPartial, lagLevel, usedRatio, type DashboardData, type OutboundItem } from "../../next/dashboard-data"49import { mailboxAddress, mailboxIndex, messageHref, nextHref, searchHref } from "../../next/nav"50import { S, routeHref } from "../../state/app"51import { linkProps } from "../../state/session"52import { useStore } from "../../state/store"53import { Avatar, Icon, type IconName } from "../kit"5455export interface WidgetProps {56  data: DashboardData57  overdue: ReadonlySet<string>58  online: boolean59  onCancelScheduled: (item: OutboundItem) => void60}61export interface WidgetDef {62  icon: IconName63  /** clés de la réponse du serveur dont dépend le widget : l'une d'elles en échec (`partial`) → « indisponible » */64  needs?: string[]65  /** lien « tout voir » de l'en-tête */66  more?: () => { href: string; label: string } | null67  body: (p: WidgetProps) => ReactNode68}6970function Empty({ icon, text }: { icon: IconName; text: string }) {71  return (72    <div className="nx-empty nx-dash-empty">73      <Icon name={icon} />74      <p>{text}</p>75    </div>76  )77}78/** Bloc que le serveur n'a pas pu lire : on le dit, on ne montre ni zéro ni « rien à signaler ». */79export function Unavailable() {80  return (81    <div className="nx-empty nx-dash-empty nx-dash-unavailable" role="status" data-testid="widget-unavailable">82      <Icon name="warn" />83      <p>{t("nx.dashboard.unavailable")}</p>84    </div>85  )86}87const inboxHref = (mailboxId: string) => routeHref({ name: "mail", mbIndex: mailboxIndex(mailboxId), view: "inbox", threadId: null, q: "" })88const many = () => (S.get().me?.mailboxes.length ?? 0) > 189const flaggedHref = () => (many() ? routeHref({ name: "mail", all: true, mbIndex: 0, view: "starred", threadId: null, q: "" }) : routeHref({ name: "mail", mbIndex: 0, view: "flagged", threadId: null, q: "" }))90const scheduledHref = () => routeHref({ name: "mail", all: true, mbIndex: 0, view: "scheduled", threadId: null, q: "" })91/** La recherche qui correspond à « Réponses attendues » : le courrier reçu encore non lu, toutes boîtes confondues. */92const pendingHref = () => searchHref("in:inbox is:unread", { all: true })93const partyName = (p: { name: string | null; email: string } | undefined) => p?.name?.trim() || p?.email || t("nx.dashboard.unknownSender")9495// ---------------------------------------------------------------- attention96function Stat({ href, value, label, sub, testid }: { href: string; value: number | null; label: string; sub?: string; testid: string }) {97  return (98    <a className={`nx-stat${value !== null && value > 0 ? " on" : ""}`} {...linkProps(href)} data-testid={testid} data-unavailable={value === null ? "" : undefined}>99      <span className="nx-stat-n" aria-label={value === null ? t("nx.dashboard.unavailable") : undefined}>100        {value === null ? "—" : fmtNumber(value)}101      </span>102      <span className="nx-stat-label">{label}</span>103      {sub ? <span className="nx-stat-sub">{sub}</span> : null}104    </a>105  )106}107function Attention({ data, overdue }: WidgetProps) {108  const a = data.attention109  const late = data.pending_replies.filter((m) => overdue.has(`${m.mailbox_id}:${m.email_id}`)).length110  // un chiffre que le serveur n'a pas pu lire s'affiche « — », pas « 0 »111  const all = isPartial(data, "attention") && !data.partial.some((p) => p.startsWith("attention."))112  const val = (key: keyof typeof a): number | null => (all || data.partial.includes(`attention.${key}`) ? null : a[key])113  const quiet = !isPartial(data, "attention") && a.reminders_due + a.flagged + a.snoozed_today + a.unanswered === 0114  return (115    <>116      <div className="nx-stats">117        {hasFeature("reminders") ? <Stat testid="stat-reminders" href={nextHref("followups")} value={val("reminders_due")} label={t("nx.dashboard.att.reminders")} /> : null}118        <Stat testid="stat-flagged" href={flaggedHref()} value={val("flagged")} label={t("nx.dashboard.att.flagged")} />119        {hasFeature("snooze") ? <Stat testid="stat-snoozed" href={nextHref("snoozed")} value={val("snoozed_today")} label={t("nx.dashboard.att.snoozed")} /> : null}120        <Stat testid="stat-unanswered" href={pendingHref()} value={val("unanswered")} label={t("nx.dashboard.att.unanswered")} sub={late > 0 ? t("nx.dashboard.att.late", { n: late }) : undefined} />121      </div>122      {isPartial(data, "attention") ? <p className="nx-note nx-dash-quiet" data-testid="attention-partial">{t("nx.dashboard.att.partial")}</p> : null}123      {quiet ? <p className="nx-note nx-dash-quiet">{t("nx.dashboard.att.quiet")}</p> : null}124    </>125  )126}127128// ---------------------------------------------------------------- réception129function Inbox({ data }: WidgetProps) {130  if (!data.inbox.length) return <Empty icon="inbox" text={t("nx.dashboard.inbox.empty")} />131  return (132    <ul className="nx-list">133      {data.inbox.map((b) => (134        <li key={b.mailbox_id}>135          <a className="nx-item nx-dash-row" {...linkProps(inboxHref(b.mailbox_id))} data-testid="inbox-row">136            <Icon name="inbox" />137            <span className="nx-item-main">138              <span className="truncate">{b.address}</span>139              <span className="small">{t("nx.dashboard.inbox.total", { n: b.total, count: fmtNumber(b.total) })}</span>140            </span>141            <span className={`nx-count${b.unread > 0 ? " on" : ""}`} aria-label={t("nx.dashboard.inbox.unread", { n: b.unread, count: fmtNumber(b.unread) })}>142              {fmtNumber(b.unread)}143            </span>144          </a>145        </li>146      ))}147    </ul>148  )149}150151// ---------------------------------------------------------------- réponses attendues152function Pending({ data, overdue }: WidgetProps) {153  if (!data.pending_replies.length) return <Empty icon="check" text={t("nx.dashboard.pending.empty")} />154  const rows = data.pending_replies.slice(0, PENDING_SHOWN)155  const rest = data.pending_replies.length - rows.length156  return (157    <>158    <ul className="nx-list">159      {rows.map((m) => (160        <li key={`${m.mailbox_id}:${m.email_id}`}>161          <a className="nx-item nx-dash-row" {...linkProps(messageHref(m.mailbox_id, m.thread_id))} data-testid="pending-row">162            <Avatar addr={m.from[0] ? { name: m.from[0].name ?? "", email: m.from[0].email } : null} small />163            <span className="nx-item-main">164              <span className="truncate">165                <strong>{partyName(m.from[0])}</strong>166                {overdue.has(`${m.mailbox_id}:${m.email_id}`) ? <span className="badge warn nx-dash-badge">{t("nx.dashboard.pending.late")}</span> : null}167              </span>168              <span className="small truncate">{m.subject || t("nx.dashboard.noSubject")}</span>169            </span>170            <time className="nx-meta" dateTime={m.received_at}>171              {fmtListDate(m.received_at)}172            </time>173          </a>174        </li>175      ))}176    </ul>177    {rest > 0 ? (178      <a className="nx-dash-all" {...linkProps(pendingHref())} data-testid="pending-all">179        {t("nx.dashboard.pending.all", { n: rest })}180      </a>181    ) : null}182    </>183  )184}185186// ---------------------------------------------------------------- envois programmés187const recipientsText = (o: OutboundItem) => {188  const first = o.recipients[0]?.address ?? t("nx.dashboard.noRecipient")189  return o.recipients.length > 1 ? t("nx.dashboard.recipientsMore", { first, n: o.recipients.length - 1 }) : first190}191function Scheduled({ data, online, onCancelScheduled }: WidgetProps) {192  if (!data.scheduled.length) return <Empty icon="clock" text={t("nx.dashboard.scheduled.empty")} />193  return (194    <ul className="nx-list">195      {data.scheduled.map((o) => (196        <li key={o.id} className="nx-item nx-dash-row" data-testid="scheduled-row">197          <a className="nx-item-main nx-dash-link" {...linkProps(scheduledHref())}>198            <span className="truncate">{o.subject?.trim() || recipientsText(o)}</span>199            {o.subject?.trim() ? <span className="small truncate">{recipientsText(o)}</span> : null}200            <span className="small truncate">{o.send_at ? t("nx.dashboard.scheduled.at", { when: fmtDateTime(o.send_at) }) : t("nx.dashboard.scheduled.soon")}</span>201          </a>202          <button type="button" className="btn small" disabled={!online} title={online ? undefined : t("nx.offline")} aria-label={t("nx.dashboard.scheduled.cancelLabel", { to: recipientsText(o) })} onClick={() => onCancelScheduled(o)}>203            {t("nx.dashboard.scheduled.cancel")}204          </button>205        </li>206      ))}207    </ul>208  )209}210211// ---------------------------------------------------------------- pièces jointes récentes212const kindIcon = (kind: string): IconName => (kind === "image" ? "image" : kind === "archive" ? "zip" : "file")213function Attachments({ data }: WidgetProps) {214  if (!data.recent_attachments.length) return <Empty icon="attach" text={t("nx.dashboard.attachments.empty")} />215  const lang = getLang()216  return (217    <ul className="nx-list">218      {data.recent_attachments.map((a) => (219        <li key={`${a.mailbox_id}:${a.email_id}:${a.blob_id}`}>220          <a className="nx-item nx-dash-row" {...linkProps(messageHref(a.mailbox_id, a.thread_id))} data-testid="attachment-row">221            <Icon name={kindIcon(a.kind)} />222            <span className="nx-item-main">223              <span className="truncate">{a.name}</span>224              <span className="small truncate">225                {fmtBytes(a.size, lang)} · {partyName(a.from[0])}226              </span>227            </span>228            <time className="nx-meta" dateTime={a.received_at}>229              {fmtListDate(a.received_at)}230            </time>231          </a>232        </li>233      ))}234    </ul>235  )236}237238// ---------------------------------------------------------------- contacts importants239function Contacts({ data }: WidgetProps) {240  if (!data.top_contacts.length) return <Empty icon="users" text={t("nx.dashboard.contacts.empty")} />241  return (242    <ul className="nx-list">243      {data.top_contacts.map((c) => {244        const email = c.emails[0]?.email ?? ""245        const exchanges = c.stats.sent + c.stats.received246        return (247          <li key={c.id}>248            <a className="nx-item nx-dash-row" {...linkProps(nextHref("contacts", c.id))} data-testid="contact-row">249              <Avatar addr={{ name: c.name, email }} small />250              <span className="nx-item-main">251                <span className="truncate">252                  {c.name || email}253                  {c.vip ? <Icon name="crown" small className="nx-dash-vip" /> : c.favorite ? <Icon name="star" small className="nx-dash-vip" /> : null}254                </span>255                <span className="small truncate">{email}</span>256              </span>257              <span className="nx-meta" aria-label={t("nx.dashboard.contacts.exchanges", { n: exchanges, count: fmtNumber(exchanges) })}>258                {fmtNumber(exchanges)}259              </span>260            </a>261          </li>262        )263      })}264    </ul>265  )266}267268// ---------------------------------------------------------------- stockage269function Storage({ data }: WidgetProps) {270  if (!data.storage.length) return <Empty icon="server" text={t("nx.dashboard.storage.empty")} />271  const lang = getLang()272  return (273    <ul className="nx-list nx-dash-storage">274      {data.storage.map((s) => {275        const ratio = usedRatio(s.used_bytes, s.quota_bytes)276        const address = mailboxAddress(s.mailbox_id) || t("nx.dashboard.storage.mailbox")277        const used = s.used_bytes === null ? t("nx.dashboard.storage.unknown") : fmtBytes(s.used_bytes, lang)278        return (279          <li key={s.mailbox_id} data-testid="storage-row">280            <div className="nx-dash-storage-head">281              <span className="truncate">{address}</span>282              <span className="nx-meta">{s.quota_bytes ? t("nx.dashboard.storage.of", { used, quota: fmtBytes(s.quota_bytes, lang) }) : used}</span>283            </div>284            {ratio !== null ? (285              <progress className={ratio >= 0.9 ? "danger" : undefined} max={100} value={Math.round(ratio * 100)} aria-label={t("nx.dashboard.storage.meter", { address, pct: Math.round(ratio * 100) })} />286            ) : (287              <span className="nx-note">{t("nx.dashboard.storage.noQuota")}</span>288            )}289          </li>290        )291      })}292    </ul>293  )294}295296// ---------------------------------------------------------------- incidents de remise297function Issues({ data }: WidgetProps) {298  if (!data.delivery_issues.length) return <Empty icon="shieldOk" text={t("nx.dashboard.issues.empty")} />299  const sentHref = (o: OutboundItem) => {300    const mb = S.get().me?.mailboxes.findIndex((m) => m.address === o.from) ?? -1301    return mb >= 0 ? routeHref({ name: "mail", mbIndex: mb, view: "sent", threadId: null, q: "" }) : routeHref({ name: "mail", all: true, mbIndex: 0, view: "sent", threadId: null, q: "" })302  }303  const label = (s: string) => (s === "bounced" ? t("nx.dashboard.issues.bounced") : s === "deferred" ? t("nx.dashboard.issues.deferred") : t("nx.dashboard.issues.failed"))304  return (305    <ul className="nx-list">306      {data.delivery_issues.map((o) => (307        <li key={o.id}>308          <a className="nx-item nx-dash-row" {...linkProps(sentHref(o))} data-testid="issue-row">309            <span className="nx-item-main">310              <span className="truncate">311                <span className={`badge ${o.status === "deferred" ? "warn" : "danger"} nx-dash-badge-lead`}>{label(o.status)}</span>312                {o.subject?.trim() || recipientsText(o)}313              </span>314              {o.subject?.trim() ? <span className="small truncate">{recipientsText(o)}</span> : null}315              {o.last_error || o.recipients[0]?.smtp_reply ? <span className="small truncate">{o.last_error ?? o.recipients[0]?.smtp_reply}</span> : null}316            </span>317            <time className="nx-meta" dateTime={o.updated_at}>318              {fmtListDate(o.updated_at)}319            </time>320          </a>321        </li>322      ))}323    </ul>324  )325}326327// ---------------------------------------------------------------- synchronisation328function SyncRow({ label, value, level }: { label: string; value: string; level: "ok" | "warn" | "danger" | "muted" }) {329  return (330    <div className="nx-dash-sync-row">331      <dt>{label}</dt>332      <dd>333        <span className={`nx-dot nx-dash-dot-${level}`} aria-hidden="true" />334        {value}335      </dd>336    </div>337  )338}339function Sync({ data }: WidgetProps) {340  const live = useStore(S, (s) => {341    const all = Object.values(s.accounts).map((a) => a.push)342    return all.includes("open") ? "on" : all.some((x) => x === "connecting" || x === "retrying") ? "connecting" : "off"343  })344  const lag = data.sync.watcher_lag_ms345  const level = lagLevel(lag)346  const lagText = level === "unknown" ? t("nx.dashboard.sync.unknown") : level === "ok" ? t("nx.dashboard.sync.upToDate") : t("nx.dashboard.sync.lag", { n: Math.round((lag ?? 0) / 1000), count: fmtNumber(Math.round((lag ?? 0) / 1000)) })347  return (348    <dl className="nx-dash-sync">349      <SyncRow label={t("nx.dashboard.sync.watcher")} value={lagText} level={level === "ok" ? "ok" : level === "late" ? "danger" : level === "slow" ? "warn" : "muted"} />350      <SyncRow label={t("nx.dashboard.sync.server")} value={data.sync.mail_server === "reachable" ? t("nx.dashboard.sync.reachable") : t("nx.dashboard.sync.unreachable")} level={data.sync.mail_server === "reachable" ? "ok" : "danger"} />351      <SyncRow label={t("nx.dashboard.sync.live")} value={live === "on" ? t("nx.dashboard.sync.liveOn") : live === "connecting" ? t("nx.dashboard.sync.liveConnecting") : t("nx.dashboard.sync.liveOff")} level={live === "on" ? "ok" : "muted"} />352      {hasFeature("push") ? <SyncRow label={t("nx.dashboard.sync.push")} value={data.sync.push === "configured" ? t("nx.dashboard.sync.pushOn") : t("nx.dashboard.sync.pushOff")} level={data.sync.push === "configured" ? "ok" : "muted"} /> : null}353    </dl>354  )355}356357export const WIDGETS: Record<WidgetId, WidgetDef> = {358  // « attention » montre chaque chiffre à part : un seul en échec n'efface pas les autres (voir Attention)359  attention: { icon: "bell", body: (p) => <Attention {...p} /> },360  inbox: { icon: "inbox", needs: ["inbox"], body: (p) => <Inbox {...p} /> },361  pending: { icon: "reply", needs: ["pending_replies"], more: () => ({ href: pendingHref(), label: t("nx.dashboard.more.pending") }), body: (p) => <Pending {...p} /> },362  scheduled: { icon: "clock", needs: ["scheduled"], more: () => ({ href: scheduledHref(), label: t("nx.dashboard.more.scheduled") }), body: (p) => <Scheduled {...p} /> },363  attachments: { icon: "attach", needs: ["recent_attachments"], more: () => ({ href: nextHref("attachments"), label: t("nx.dashboard.more.attachments") }), body: (p) => <Attachments {...p} /> },364  contacts: { icon: "users", needs: ["top_contacts"], more: () => ({ href: nextHref("contacts"), label: t("nx.dashboard.more.contacts") }), body: (p) => <Contacts {...p} /> },365  storage: { icon: "server", needs: ["storage"], more: () => ({ href: "/settings/storage", label: t("nx.dashboard.more.storage") }), body: (p) => <Storage {...p} /> },366  issues: { icon: "warn", needs: ["delivery_issues"], body: (p) => <Issues {...p} /> },367  sync: { icon: "sync", needs: ["sync"], body: (p) => <Sync {...p} /> },368}369/** Corps d'un widget, ou « indisponible » si le serveur n'a pas pu lire l'un des blocs dont il dépend. */370export function widgetBody(id: WidgetId, p: WidgetProps): ReactNode {371  const def = WIDGETS[id]372  return (def.needs ?? []).some((k) => isPartial(p.data, k)) ? <Unavailable /> : def.body(p)373}374export const widgetTitle = (id: WidgetId): string => t(`nx.dashboard.w.${id}`)375
Files main
Menu

Theme