Repository Public
1// SP Mail Next — centre de commande : données (`GET /api/next/dashboard`, « insights » par boîte), relecture, annulation d'un envoi programmé.2import { HttpError } from "../jmap/errors"3import { v1 } from "../mail/v1"4import { S } from "../state/app"5import { createStore } from "../state/store"6import { hasFeature, isAbort, nx, toNextError, type NextErrorKind } from "./api"7import type { WidgetId } from "./dashboard"8import type { MessageSummary, Party } from "./types"910// ---------------------------------------------------------------- formes du serveur (server/src/next/dashboard.ts fait foi)11export interface OutboundItem {12 id: string13 status: string14 from: string15 message_id: string | null16 recipients: { address: string; status: string; smtp_reply: string | null }[]17 send_at: string | null18 last_error: string | null19 /** objet du message (brouillon ou e-mail conservé) ; null si le serveur ne l'a plus */20 subject?: string | null21 created_at: string22 updated_at: string23}24export interface AttachmentItem {25 mailbox_id: string26 email_id: string27 thread_id: string28 blob_id: string29 name: string30 type: string31 size: number32 kind: string33 from: Party[]34 subject: string35 received_at: string36}37export interface ContactItem {38 id: string39 name: string40 emails: { email: string; label: string | null }[]41 organization: string | null42 favorite: boolean43 vip: boolean44 avatar_color: string45 stats: { sent: number; received: number; last_at: string | null }46}47export interface DashboardData {48 inbox: { mailbox_id: string; address: string; unread: number; total: number }[]49 attention: { reminders_due: number; flagged: number; snoozed_today: number; unanswered: number }50 scheduled: OutboundItem[]51 pending_replies: MessageSummary[]52 recent_attachments: AttachmentItem[]53 top_contacts: ContactItem[]54 storage: { mailbox_id: string; used_bytes: number | null; quota_bytes: number | null }[]55 delivery_issues: OutboundItem[]56 sync: { watcher_lag_ms: number | null; mail_server: "reachable" | "unreachable"; push: "configured" | "disabled" }57 /** blocs dont la lecture a échoué côté serveur (noms des clés ci-dessus, parfois « bloc.champ ») : à montrer « indisponible », jamais comme un zéro */58 partial: string[]59 generated_at: string60}61/** Vrai si ce bloc (ou l'un de ses champs) figure parmi ceux que le serveur n'a pas pu lire. */62export const isPartial = (data: Pick<DashboardData, "partial">, key: string): boolean => data.partial.some((p) => p === key || p.startsWith(`${key}.`))63/** Lignes de « Réponses attendues » montrées dans le widget ; le reste est derrière « Voir tout ». */64export const PENDING_SHOWN = 565const arr = <T>(v: unknown): T[] => (Array.isArray(v) ? (v as T[]) : [])66const n = (v: unknown): number => (typeof v === "number" && Number.isFinite(v) ? v : 0)67/** Une réponse partielle (serveur plus ancien, bloc absent) ne doit pas faire tomber l'écran : chaque bloc a sa valeur vide. */68export function normalizeDashboard(raw: unknown): DashboardData {69 const r = raw && typeof raw === "object" ? (raw as Record<string, unknown>) : {}70 const a = (r.attention && typeof r.attention === "object" ? r.attention : {}) as Record<string, unknown>71 const s = (r.sync && typeof r.sync === "object" ? r.sync : {}) as Record<string, unknown>72 return {73 inbox: arr(r.inbox),74 attention: { reminders_due: n(a.reminders_due), flagged: n(a.flagged), snoozed_today: n(a.snoozed_today), unanswered: n(a.unanswered) },75 scheduled: arr(r.scheduled),76 pending_replies: arr(r.pending_replies),77 recent_attachments: arr(r.recent_attachments),78 top_contacts: arr(r.top_contacts),79 storage: arr(r.storage),80 delivery_issues: arr(r.delivery_issues),81 sync: { watcher_lag_ms: typeof s.watcher_lag_ms === "number" ? s.watcher_lag_ms : null, mail_server: s.mail_server === "unreachable" ? "unreachable" : "reachable", push: s.push === "configured" ? "configured" : "disabled" },82 partial: arr<unknown>(r.partial).filter((x): x is string => typeof x === "string"),83 generated_at: typeof r.generated_at === "string" ? r.generated_at : new Date().toISOString(),84 }85}8687/** Un widget n'est proposé que si le serveur offre la fonction dont ses données dépendent. */88export function widgetAvailable(id: WidgetId): boolean {89 if (id === "attachments") return hasFeature("attachments")90 if (id === "contacts") return hasFeature("contacts")91 return true92}9394// ---------------------------------------------------------------- état95export interface DashboardState {96 data: DashboardData | null97 loading: boolean98 error: NextErrorKind | null99 /** messages restés sans réponse depuis plus d'un jour (insights), par identifiant `boîte:message` */100 overdue: ReadonlySet<string>101}102export const DASH = createStore<DashboardState>({ data: null, loading: false, error: null, overdue: new Set() })103let gen = 0104let flight: Promise<void> | null = null105106async function loadOverdue(my: number, mailboxIds: string[]) {107 if (!hasFeature("ai") || !mailboxIds.length) return108 // « insights » fonctionne IA coupée ; une boîte en échec n'empêche pas les autres109 const parts = await Promise.all(mailboxIds.map((id) => nx.get<{ needs_reply?: MessageSummary[] }>("inbox/insights", { mailbox_id: id, limit: 100 }).then((r) => arr<MessageSummary>(r.needs_reply), () => [] as MessageSummary[])))110 if (my !== gen) return111 DASH.set({ overdue: new Set(parts.flat().map((m) => `${m.mailbox_id}:${m.email_id}`)) })112}113114/** Lit le tableau ; `fresh` contourne le court cache du serveur (après une action). Les appels concurrents partagent la requête. */115export function loadDashboard(fresh = false): Promise<void> {116 if (flight && !fresh) return flight117 const my = ++gen118 DASH.set({ loading: true })119 const p = (async () => {120 try {121 const data = normalizeDashboard(await nx.get<unknown>("dashboard", { fresh }))122 if (my !== gen) return123 DASH.set({ data, loading: false, error: null })124 void loadOverdue(my, data.inbox.map((b) => b.mailbox_id))125 } catch (e) {126 if (my !== gen || isAbort(e)) return127 DASH.set({ loading: false, error: toNextError(e).kind })128 }129 })().finally(() => {130 if (flight === p) flight = null131 })132 flight = p133 return p134}135export function resetDashboard() {136 gen++137 flight = null138 DASH.set({ data: null, loading: false, error: null, overdue: new Set() })139}140141export type CancelResult = "cancelled" | "tooLate" | "offline" | "failed"142/** Annule un envoi programmé (même route que la vue « Programmés ») ; le tableau est relu dans tous les cas. */143export async function cancelScheduledSend(id: string): Promise<CancelResult> {144 if (!S.get().online) return "offline"145 let result: CancelResult = "cancelled"146 try {147 await v1(`/messages/scheduled/${encodeURIComponent(id)}`, { method: "DELETE" })148 // retrait immédiat : la relecture confirmera149 gen++150 DASH.set((d) => (d.data ? { data: { ...d.data, scheduled: d.data.scheduled.filter((x) => x.id !== id) } } : {}))151 } catch (e) {152 const err = toNextError(e)153 result = err.kind === "offline" ? "offline" : (e instanceof HttpError && e.code === "not_cancellable") || err.kind === "conflict" || err.kind === "not_found" ? "tooLate" : "failed"154 }155 void loadDashboard(true)156 return result157}158159// ---------------------------------------------------------------- présentation (pure)160export function fmtBytes(bytes: number, lang: "fr" | "en"): string {161 const units = lang === "fr" ? ["o", "Ko", "Mo", "Go", "To"] : ["B", "KB", "MB", "GB", "TB"]162 let v = Math.max(0, bytes)163 let u = 0164 while (v >= 1024 && u < units.length - 1) {165 v /= 1024166 u++167 }168 const digits = u === 0 || v >= 100 ? 0 : 1169 return `${v.toLocaleString(lang === "fr" ? "fr-CA" : "en-CA", { maximumFractionDigits: digits, minimumFractionDigits: 0 })} ${units[u]}`170}171/** Part utilisée d'un quota (0–1), ou null sans quota ou sans mesure. */172export function usedRatio(used: number | null, quota: number | null): number | null {173 if (used === null || !quota || quota <= 0) return null174 return Math.min(1, Math.max(0, used / quota))175}176/** Retard du veilleur, en classes lisibles : à jour, léger (< 2 min), en retard. */177export function lagLevel(ms: number | null): "unknown" | "ok" | "slow" | "late" {178 if (ms === null) return "unknown"179 if (ms < 5_000) return "ok"180 return ms < 120_000 ? "slow" : "late"181}182