Repository Public
1// SP Mail Next — aperçus de la boîte de réception calculés SANS modèle (infolettres, réponses attendues, envois restés sans réponse) :2// lecture de /api/next/inbox/insights, magasin par boîte avec garde de génération, mise en lignes pour les pastilles.3import { createStore } from "../state/store"4import { isAbort, nx, toNextError, type NextErrorKind } from "./api"5import { normalizeMessage } from "./ai"6import type { MessageSummary } from "./types"78export const INSIGHT_KINDS = ["newsletters", "needs_reply", "unanswered_sent"] as const9export type InsightKind = (typeof INSIGHT_KINDS)[number]10export interface Insights {11 mailbox_id: string12 newsletters: MessageSummary[]13 needs_reply: MessageSummary[]14 unanswered_sent: MessageSummary[]15 generated_at: string16}17const arr = (v: unknown): MessageSummary[] => (Array.isArray(v) ? v.slice(0, 200).map(normalizeMessage).filter((m): m is MessageSummary => !!m) : [])18/** Forme attendue, rien d'autre ; une réponse inattendue donne des listes vides. Fonction pure. */19export function normalizeInsights(raw: unknown, mailboxId = ""): Insights {20 const r = (raw && typeof raw === "object" ? raw : {}) as Record<string, unknown>21 return {22 mailbox_id: typeof r.mailbox_id === "string" ? r.mailbox_id : mailboxId,23 newsletters: arr(r.newsletters), needs_reply: arr(r.needs_reply), unanswered_sent: arr(r.unanswered_sent),24 generated_at: typeof r.generated_at === "string" ? r.generated_at : "",25 }26}2728/** Ligne d'un aperçu : assez pour l'afficher et ouvrir la conversation dans la bonne vue. */29export interface InsightRow {30 mailboxId: string31 emailId: string32 threadId: string33 /** correspondant : l'expéditeur, ou le premier destinataire pour un envoi */34 who: string35 subject: string36 receivedAt: string37 unread: boolean38 /** vue où la conversation s'ouvre (« inbox », « sent ») */39 view: string40}41const name = (p: { email: string; name: string | null } | undefined): string => p?.name?.trim() || p?.email || ""42/** Lignes d'un aperçu, de la plus récente à la plus ancienne, une par conversation. Fonction pure. */43export function insightRows(insights: Insights | null, kind: InsightKind): InsightRow[] {44 if (!insights) return []45 const sent = kind === "unanswered_sent"46 const seen = new Set<string>()47 return [...insights[kind]]48 .sort((a, b) => Date.parse(b.received_at) - Date.parse(a.received_at))49 .filter((m) => (seen.has(m.thread_id) ? false : (seen.add(m.thread_id), true)))50 .map((m) => ({ mailboxId: m.mailbox_id, emailId: m.email_id, threadId: m.thread_id, who: name(sent ? m.to[0] : m.from[0]), subject: m.subject, receivedAt: m.received_at, unread: !sent && !m.keywords.includes("$seen"), view: sent ? "sent" : "inbox" }))51}52/** Pastilles à montrer : seulement celles qui ont au moins une conversation, dans un ordre stable. Fonction pure. */53export function insightChips(insights: Insights | null): { kind: InsightKind; count: number }[] {54 return INSIGHT_KINDS.map((kind) => ({ kind, count: insightRows(insights, kind).length })).filter((c) => c.count > 0)55}5657// ---------------------------------------------------------------- magasin58interface InsightState {59 /** boîte dont `data` décrit la réception */60 mailboxId: string | null61 data: Insights | null62 loading: boolean63 error: NextErrorKind | null64}65export const insightStore = createStore<InsightState>({ mailboxId: null, data: null, loading: false, error: null })66let gen = 067let controller: AbortController | null = null68const memory = new Map<string, Insights>()6970/** Lit les aperçus d'une boîte ; une réponse arrivée après un changement de boîte (ou une demande plus récente) est ignorée. */71export async function loadInsights(mailboxId: string): Promise<void> {72 const my = ++gen73 controller?.abort()74 controller = new AbortController()75 const cur = insightStore.get()76 insightStore.set({ mailboxId, data: cur.mailboxId === mailboxId ? cur.data : (memory.get(mailboxId) ?? null), loading: true, error: null })77 try {78 const data = normalizeInsights(await nx.get<unknown>("inbox/insights", { mailbox_id: mailboxId }, controller.signal), mailboxId)79 if (my !== gen) return80 memory.set(mailboxId, data)81 insightStore.set({ data, loading: false, error: null })82 } catch (e) {83 if (my !== gen || isAbort(e)) return84 // discret : les pastilles déjà connues restent, aucune alerte (ce n'est qu'un aperçu)85 insightStore.set({ loading: false, error: toNextError(e).kind })86 }87}88export function resetInsights() {89 gen++90 controller?.abort()91 controller = null92 memory.clear()93 insightStore.set({ mailboxId: null, data: null, loading: false, error: null })94}95