SPB Git

Repository Public

contacts.ts 23.2 KB 492 lines typescript

1// SP Mail Next — contacts : formes de /api/next/contacts, normalisation, aides pures (doublons, vCard, saisie), état de la liste et de la fiche.2import { createStore } from "../state/store"3import { isAbort, nx, toNextError, type NextErrorKind, type Params } from "./api"4import { createCollection } from "./collection"5import type { MessageSummary } from "./types"67// ---------------------------------------------------------------- formes (server/src/next/contacts.ts fait foi)8export type ContactKind = "saved" | "suggested"9export interface ContactEmail {10  email: string11  label: string | null12}13export interface ContactPhone {14  number: string15  label: string | null16}17export interface Contact {18  id: string19  kind: ContactKind20  name: string21  emails: ContactEmail[]22  organization: string | null23  title: string | null24  phones: ContactPhone[]25  notes: string | null26  favorite: boolean27  vip: boolean28  /** identifiants de groupes */29  groups: string[]30  avatar_color: string31  stats: { sent: number; received: number; last_at: string | null }32  created_at: string | null33  updated_at: string | null34}35export interface ContactGroup {36  id: string37  name: string38  color: string39  members: number40}41export interface ContactSuggestion {42  name: string43  email: string44  contact_id: string45  kind: ContactKind46  favorite: boolean47  score: number48}49export interface DuplicateGroup {50  reason: "email" | "name"51  key: string52  contacts: Contact[]53}54export interface ImportResult {55  total: number56  imported: number57  updated: number58  skipped: number59}60export interface HistoryItem extends MessageSummary {61  direction: "sent" | "received"62}63export interface ContactReminder {64  id: string65  mailbox_id: string66  email_id: string67  thread_id: string68  subject: string69  due_at: string | null70  note: string | null71  status: string72}73/** Champs modifiables d'une fiche (création et modification). */74export interface ContactInput {75  name?: string76  emails?: { email: string; label?: string | null }[]77  organization?: string | null78  title?: string | null79  phones?: { number: string; label?: string | null }[]80  notes?: string | null81  favorite?: boolean82  vip?: boolean83  groups?: string[]84  kind?: "saved"85}8687// ---------------------------------------------------------------- normalisation (tout champ est un texte non fiable)88const str = (v: unknown): string => (typeof v === "string" ? v : "")89const strOrNull = (v: unknown): string | null => (typeof v === "string" && v !== "" ? v : null)90const num = (v: unknown): number => (typeof v === "number" && Number.isFinite(v) ? v : 0)91const arr = (v: unknown): unknown[] => (Array.isArray(v) ? v : [])92const obj = (v: unknown): Record<string, unknown> => (v && typeof v === "object" ? (v as Record<string, unknown>) : {})9394/** Ne garde d'une fiche reçue que ce qui a la forme attendue ; `null` si elle n'a pas d'identifiant. */95export function normalizeContact(raw: unknown): Contact | null {96  const r = obj(raw)97  if (typeof r.id !== "string" || !r.id) return null98  const stats = obj(r.stats)99  return {100    id: r.id,101    kind: r.kind === "saved" ? "saved" : "suggested",102    name: str(r.name),103    emails: arr(r.emails).map(obj).filter((e) => typeof e.email === "string" && e.email).map((e) => ({ email: e.email as string, label: strOrNull(e.label) })),104    organization: strOrNull(r.organization),105    title: strOrNull(r.title),106    phones: arr(r.phones).map(obj).filter((p) => typeof p.number === "string" && p.number).map((p) => ({ number: p.number as string, label: strOrNull(p.label) })),107    notes: strOrNull(r.notes),108    favorite: r.favorite === true,109    vip: r.vip === true,110    groups: arr(r.groups).filter((g): g is string => typeof g === "string"),111    avatar_color: str(r.avatar_color),112    stats: { sent: num(stats.sent), received: num(stats.received), last_at: strOrNull(stats.last_at) },113    created_at: strOrNull(r.created_at),114    updated_at: strOrNull(r.updated_at),115  }116}117export const normalizeContacts = (raw: unknown): Contact[] => arr(raw).map(normalizeContact).filter((c): c is Contact => c !== null)118export function normalizeGroup(raw: unknown): ContactGroup | null {119  const r = obj(raw)120  if (typeof r.id !== "string" || !r.id) return null121  return { id: r.id, name: str(r.name), color: str(r.color), members: num(r.members) }122}123124/** Nom affiché : le nom, à défaut la première adresse, à défaut le premier téléphone. */125export const contactTitle = (c: Pick<Contact, "name" | "emails" | "phones">): string => c.name.trim() || c.emails[0]?.email || c.phones[0]?.number || ""126/** Initiales (deux lettres au plus) d'après le nom affiché. */127export function contactInitials(c: Pick<Contact, "name" | "emails" | "phones">): string {128  const title = contactTitle(c)129  const words = (c.name.trim() ? title : title.split("@")[0]).split(/[\s._-]+/).filter(Boolean)130  const letters = words.length > 1 ? `${[...words[0]][0] ?? ""}${[...words[words.length - 1]][0] ?? ""}` : [...(words[0] ?? "")].slice(0, 2).join("")131  return letters.toUpperCase() || "?"132}133134// ---------------------------------------------------------------- couleurs : les dix teintes du système de design135/** Valeurs échangées avec le serveur ; l'affichage passe toujours par le jeton `--label-N` correspondant (thèmes). */136export const PALETTE = ["#b3261e", "#a14a00", "#7a5c00", "#2e6b2e", "#00695c", "#1d5fa8", "#4a4fb5", "#7a3fa0", "#a8327a", "#5c5f66"] as const137/** Jeton CSS d'une couleur du serveur ; une couleur hors palette reçoit une teinte stable de la palette. */138export function colorToken(hex: string): string {139  const i = (PALETTE as readonly string[]).indexOf(hex.trim().toLowerCase())140  if (i >= 0) return `var(--label-${i + 1})`141  let h = 0142  for (const ch of hex) h = (h * 31 + ch.charCodeAt(0)) >>> 0143  return `var(--label-${(h % PALETTE.length) + 1})`144}145146// ---------------------------------------------------------------- liste : filtres → paramètres147export type KindFilter = "all" | "saved" | "suggested"148export interface ContactFilter {149  q: string150  kind: KindFilter151  favorite: boolean152  group: string | null153}154export const emptyFilter = (): ContactFilter => ({ q: "", kind: "all", favorite: false, group: null })155export const PAGE_SIZE = 50156export function listParams(f: ContactFilter, cursor?: string | null, limit = PAGE_SIZE): Params {157  return { q: f.q.trim().slice(0, 200), kind: f.kind === "all" ? undefined : f.kind, favorite: f.favorite, group: f.group, limit, cursor }158}159/** Une fiche satisfait-elle le filtre courant ? (insertion locale après une écriture, sans relire la liste) */160export function matchesFilter(c: Contact, f: ContactFilter): boolean {161  if (f.kind !== "all" && c.kind !== f.kind) return false162  if (f.favorite && !c.favorite) return false163  if (f.group && !c.groups.includes(f.group)) return false164  const q = f.q.trim().toLowerCase()165  if (!q) return true166  return c.name.toLowerCase().includes(q) || (c.organization ?? "").toLowerCase().includes(q) || c.emails.some((e) => e.email.includes(q))167}168/** Ordre du serveur : fiches nommées d'abord, par nom, puis par identifiant. */169export function compareContacts(a: Contact, b: Contact): number {170  const ea = a.name === "" ? 1 : 0171  const eb = b.name === "" ? 1 : 0172  if (ea !== eb) return ea - eb173  const na = a.name.toLowerCase()174  const nb = b.name.toLowerCase()175  return na < nb ? -1 : na > nb ? 1 : a.id < b.id ? -1 : a.id > b.id ? 1 : 0176}177/** Remplace, insère ou retire une fiche dans une page de liste selon le filtre ; l'ordre du serveur est conservé. */178export function upsertContact(items: Contact[], c: Contact, f: ContactFilter): Contact[] {179  const rest = items.filter((x) => x.id !== c.id)180  if (!matchesFilter(c, f)) return rest181  return [...rest, c].sort(compareContacts)182}183184// ---------------------------------------------------------------- saisie185const EMAIL_RE = /^[^\s@<>"]+@[^\s@<>"]+\.[^\s@<>"]+$/186export const isEmail = (s: string): boolean => s.length <= 254 && EMAIL_RE.test(s.trim())187export interface ContactForm {188  name: string189  organization: string190  title: string191  notes: string192  emails: { email: string; label: string }[]193  phones: { number: string; label: string }[]194  favorite: boolean195  vip: boolean196  groups: string[]197}198export const formOf = (c?: Contact | null, init: Partial<ContactForm> = {}): ContactForm => ({199  name: c?.name ?? "",200  organization: c?.organization ?? "",201  title: c?.title ?? "",202  notes: c?.notes ?? "",203  emails: c?.emails.length ? c.emails.map((e) => ({ email: e.email, label: e.label ?? "" })) : [{ email: "", label: "" }],204  phones: c?.phones.length ? c.phones.map((p) => ({ number: p.number, label: p.label ?? "" })) : [],205  favorite: c?.favorite ?? false,206  vip: c?.vip ?? false,207  groups: c?.groups ?? [],208  ...init,209})210export type FormProblem = "empty" | "email" | null211/** Ce qui empêche d'enregistrer : fiche vide (ni nom, ni adresse, ni téléphone) ou adresse mal formée. */212export function formProblem(f: ContactForm): FormProblem {213  const emails = f.emails.map((e) => e.email.trim()).filter(Boolean)214  if (emails.some((e) => !isEmail(e))) return "email"215  if (!f.name.trim() && !emails.length && !f.phones.some((p) => p.number.trim())) return "empty"216  return null217}218/** Corps de POST/PATCH : textes rognés, lignes vides retirées, adresses en minuscules et sans doublon, vide → `null`. */219export function formToInput(f: ContactForm): ContactInput {220  const seen = new Set<string>()221  const emails: { email: string; label: string | null }[] = []222  for (const e of f.emails) {223    const email = e.email.trim().toLowerCase()224    if (!email || seen.has(email)) continue225    seen.add(email)226    emails.push({ email, label: e.label.trim().slice(0, 24) || null })227  }228  return {229    name: f.name.trim().slice(0, 120),230    emails,231    organization: f.organization.trim().slice(0, 160) || null,232    title: f.title.trim().slice(0, 160) || null,233    phones: f.phones.map((p) => ({ number: p.number.trim().slice(0, 40), label: p.label.trim().slice(0, 24) || null })).filter((p) => p.number),234    notes: f.notes.trim().slice(0, 4000) || null,235    favorite: f.favorite,236    vip: f.vip,237    groups: [...new Set(f.groups)],238  }239}240241// ---------------------------------------------------------------- doublons et fusion242/** Fiche proposée comme fiche gardée : enregistrée avant suggérée, puis la plus riche (adresses, téléphones, champs), puis la plus active. */243export function pickKeep(contacts: Contact[]): string | null {244  const weight = (c: Contact) => (c.kind === "saved" ? 1e6 : 0) + (c.emails.length + c.phones.length + (c.name ? 1 : 0) + (c.organization ? 1 : 0) + (c.title ? 1 : 0) + (c.notes ? 1 : 0)) * 1e3 + Math.min(999, c.stats.sent + c.stats.received)245  return [...contacts].sort((a, b) => weight(b) - weight(a) || (a.id < b.id ? -1 : 1))[0]?.id ?? null246}247const digits = (s: string) => s.replace(/\D/g, "")248/** Résultat annoncé d'une fusion, selon la même règle que le serveur : la fiche gardée l'emporte, les autres la complètent. */249export function mergePreview(keep: Contact, others: Contact[]): Pick<Contact, "name" | "emails" | "phones" | "organization" | "title" | "favorite" | "vip" | "groups" | "kind"> & { sent: number; received: number } {250  const all = [keep, ...others]251  const emails = [...keep.emails]252  for (const o of others) for (const e of o.emails) if (!emails.some((x) => x.email === e.email)) emails.push(e)253  const phones = [...keep.phones]254  for (const o of others) for (const p of o.phones) if (!phones.some((x) => digits(x.number) === digits(p.number))) phones.push(p)255  const first = (k: "name" | "organization" | "title") => keep[k] || others.map((o) => o[k]).find(Boolean) || keep[k]256  return {257    kind: all.some((c) => c.kind === "saved") ? "saved" : "suggested",258    name: first("name") ?? "",259    organization: first("organization") ?? null,260    title: first("title") ?? null,261    emails,262    phones: phones.slice(0, 20),263    favorite: all.some((c) => c.favorite),264    vip: all.some((c) => c.vip),265    groups: [...new Set(all.flatMap((c) => c.groups))],266    sent: all.reduce((n, c) => n + c.stats.sent, 0),267    received: all.reduce((n, c) => n + c.stats.received, 0),268  }269}270/** Retire d'une liste de groupes de doublons les fiches fusionnées ; un groupe réduit à une fiche disparaît. */271export function pruneDuplicates(groups: DuplicateGroup[], goneIds: string[], kept?: Contact): DuplicateGroup[] {272  const gone = new Set(goneIds)273  return groups274    .map((g) => ({ ...g, contacts: g.contacts.filter((c) => !gone.has(c.id)).map((c) => (kept && c.id === kept.id ? kept : c)) }))275    .filter((g) => g.contacts.length > 1)276}277278// ---------------------------------------------------------------- vCard279export const VCF_MAX_BYTES = 2 * 1024 * 1024280export type VcfProblem = "type" | "too_large" | "empty" | null281/** Contrôle d'un fichier avant envoi : extension .vcf/.vcard (ou type MIME vCard), non vide, 2 Mo au plus. */282export function vcfProblem(file: { name: string; size: number; type?: string }): VcfProblem {283  const named = /\.(vcf|vcard)$/i.test(file.name.trim())284  const typed = /^text\/(x-)?vcard\b|^text\/directory\b/i.test(file.type ?? "")285  if (!named && !typed) return "type"286  if (file.size <= 0) return "empty"287  if (file.size > VCF_MAX_BYTES) return "too_large"288  return null289}290export function normalizeImportResult(raw: unknown): ImportResult {291  const r = obj(raw)292  return { total: num(r.total), imported: num(r.imported), updated: num(r.updated), skipped: num(r.skipped) }293}294295// ---------------------------------------------------------------- groupes (petite collection synchronisée)296export const groups = createCollection<ContactGroup>("contact-groups", async () => (await nx.list<unknown>("contact-groups")).map(normalizeGroup).filter((g): g is ContactGroup => g !== null))297const byName = (a: ContactGroup, b: ContactGroup) => a.name.toLowerCase().localeCompare(b.name.toLowerCase())298export async function createGroup(name: string, color?: string): Promise<ContactGroup> {299  const g = normalizeGroup(await nx.post<unknown>("contact-groups", { name, ...(color ? { color } : {}) }))300  if (!g) throw toNextError(new Error("bad group"))301  groups.mutate((items) => [...items.filter((x) => x.id !== g.id), g].sort(byName))302  return g303}304export async function updateGroup(id: string, patch: { name?: string; color?: string }): Promise<void> {305  const g = normalizeGroup(await nx.patch<unknown>(`contact-groups/${encodeURIComponent(id)}`, patch))306  if (g) groups.mutate((items) => items.map((x) => (x.id === g.id ? g : x)).sort(byName))307}308export async function deleteGroup(id: string): Promise<void> {309  await nx.del(`contact-groups/${encodeURIComponent(id)}`)310  groups.mutate((items) => items.filter((x) => x.id !== id))311  const strip = (c: Contact): Contact => (c.groups.includes(id) ? { ...c, groups: c.groups.filter((g) => g !== id) } : c)312  const s = CT.get()313  CT.set({ items: s.items.map(strip), card: s.card ? strip(s.card) : null })314  if (s.filter.group === id) setFilter({ group: null })315}316317// ---------------------------------------------------------------- état de l'écran318export interface ContactsState {319  filter: ContactFilter320  items: Contact[]321  next: string | null322  status: "idle" | "loading" | "ready" | "error"323  error: NextErrorKind | null324  loadingMore: boolean325  /** fiche affichée (route /contacts/<id>) */326  cardId: string | null327  card: Contact | null328  cardStatus: "idle" | "loading" | "ready" | "error"329  cardError: NextErrorKind | null330  history: HistoryItem[]331  reminders: ContactReminder[]332  historyStatus: "idle" | "loading" | "ready" | "error"333}334const initial = (): ContactsState => ({335  filter: emptyFilter(), items: [], next: null, status: "idle", error: null, loadingMore: false,336  cardId: null, card: null, cardStatus: "idle", cardError: null, history: [], reminders: [], historyStatus: "idle",337})338export const CT = createStore<ContactsState>(initial())339let listGen = 0340let cardGen = 0341let listAbort: AbortController | null = null342343/** Relit la première page avec le filtre courant ; une réponse dépassée par un filtre plus récent est ignorée. */344export async function loadContacts(): Promise<void> {345  const my = ++listGen346  listAbort?.abort()347  const ctrl = (listAbort = new AbortController())348  CT.set((s) => ({ status: s.items.length ? s.status : "loading", error: null, loadingMore: false }))349  try {350    const r = await nx.get<{ data: unknown; next_cursor: string | null }>("contacts", listParams(CT.get().filter), ctrl.signal)351    if (my !== listGen) return352    CT.set({ items: normalizeContacts(r.data), next: typeof r.next_cursor === "string" ? r.next_cursor : null, status: "ready", error: null })353  } catch (e) {354    if (my !== listGen || isAbort(e)) return355    CT.set({ status: "error", error: toNextError(e).kind })356  }357}358export async function loadMoreContacts(): Promise<void> {359  const s = CT.get()360  if (!s.next || s.loadingMore || s.status !== "ready") return361  const my = listGen362  CT.set({ loadingMore: true })363  try {364    const r = await nx.get<{ data: unknown; next_cursor: string | null }>("contacts", listParams(s.filter, s.next))365    if (my !== listGen) return366    const more = normalizeContacts(r.data)367    CT.set((cur) => ({ items: [...cur.items, ...more.filter((c) => !cur.items.some((x) => x.id === c.id))], next: typeof r.next_cursor === "string" ? r.next_cursor : null, loadingMore: false }))368  } catch (e) {369    if (my !== listGen) return370    CT.set({ loadingMore: false, error: toNextError(e).kind })371  }372}373export function setFilter(patch: Partial<ContactFilter>) {374  const f = { ...CT.get().filter, ...patch }375  // nouvelle liste : les lignes de l'ancienne ne doivent pas rester affichées sous le nouveau filtre376  CT.set({ filter: f, items: [], next: null, status: "loading" })377  void loadContacts()378}379380/** Ouvre la fiche de la route ; l'historique des échanges est lu à part (il interroge toutes les boîtes). */381export async function openCard(id: string | null): Promise<void> {382  const my = ++cardGen383  if (!id) return CT.set({ cardId: null, card: null, cardStatus: "idle", cardError: null, history: [], reminders: [], historyStatus: "idle" })384  const known = CT.get().items.find((c) => c.id === id) ?? (CT.get().card?.id === id ? CT.get().card : null)385  CT.set({ cardId: id, card: known ?? null, cardStatus: known ? "ready" : "loading", cardError: null, history: [], reminders: [], historyStatus: "loading" })386  void (async () => {387    try {388      const c = normalizeContact(await nx.get<unknown>(`contacts/${encodeURIComponent(id)}`))389      if (my !== cardGen) return390      if (!c) throw toNextError(new Error("bad contact"))391      CT.set({ card: c, cardStatus: "ready" })392    } catch (e) {393      if (my !== cardGen || isAbort(e)) return394      CT.set({ card: null, cardStatus: "error", cardError: toNextError(e).kind })395    }396  })()397  await loadHistory(id, my)398}399async function loadHistory(id: string, my: number): Promise<void> {400  try {401    const r = await nx.get<{ data: unknown; reminders: unknown }>(`contacts/${encodeURIComponent(id)}/history`, { limit: 30 })402    if (my !== cardGen) return403    CT.set({ history: arr(r.data).filter((x): x is HistoryItem => !!x && typeof (x as HistoryItem).thread_id === "string"), reminders: arr(r.reminders).filter((x): x is ContactReminder => !!x && typeof (x as ContactReminder).id === "string"), historyStatus: "ready" })404  } catch (e) {405    if (my !== cardGen || isAbort(e)) return406    CT.set({ historyStatus: "error" })407  }408}409export function reloadHistory() {410  const id = CT.get().cardId411  if (!id) return412  CT.set({ historyStatus: "loading" })413  void loadHistory(id, cardGen)414}415416/** Répercute une fiche écrite par le serveur dans la liste et dans la fiche ouverte. */417function applyContact(c: Contact) {418  listGen++ // une lecture de liste en vol rendrait l'état d'avant419  CT.set((s) => ({ items: upsertContact(s.items, c, s.filter), status: s.status === "loading" ? "ready" : s.status, ...(s.cardId === c.id ? { card: c, cardStatus: "ready" as const } : {}) }))420}421function dropContacts(ids: string[]) {422  listGen++423  CT.set((s) => ({ items: s.items.filter((c) => !ids.includes(c.id)), status: s.status === "loading" ? "ready" : s.status }))424}425function must(raw: unknown): Contact {426  const c = normalizeContact(raw)427  if (!c) throw toNextError(new Error("bad contact"))428  return c429}430export async function createContact(input: ContactInput): Promise<Contact> {431  const c = must(await nx.post<unknown>("contacts", input))432  applyContact(c)433  void groups.refresh()434  return c435}436export async function updateContact(id: string, patch: ContactInput): Promise<Contact> {437  const c = must(await nx.patch<unknown>(`contacts/${encodeURIComponent(id)}`, patch))438  applyContact(c)439  if (patch.groups) void groups.refresh()440  return c441}442/** Une suggestion devient une fiche enregistrée. */443export const saveSuggestion = (id: string): Promise<Contact> => updateContact(id, { kind: "saved" })444export async function deleteContact(id: string): Promise<void> {445  await nx.del(`contacts/${encodeURIComponent(id)}`)446  dropContacts([id])447  void groups.refresh()448}449export const fetchDuplicates = async (signal?: AbortSignal): Promise<DuplicateGroup[]> =>450  (await nx.list<unknown>("contacts/duplicates", undefined, signal)).map(obj).map((g) => ({ reason: g.reason === "name" ? ("name" as const) : ("email" as const), key: str(g.key), contacts: normalizeContacts(g.contacts) })).filter((g) => g.contacts.length > 1)451export async function mergeContacts(keep: string, merge: string[]): Promise<Contact> {452  const c = must(await nx.post<unknown>("contacts/merge", { keep, merge }))453  dropContacts(merge)454  applyContact(c)455  void groups.refresh()456  return c457}458/** Envoie un fichier .vcf tel quel (le serveur détecte son encodage) ; la liste est relue ensuite. */459export async function importVcf(file: Blob | string): Promise<ImportResult> {460  const r = await nx.raw("contacts/import", { method: "POST", body: file, headers: { "content-type": "text/vcard" } })461  const out = normalizeImportResult(await r.json())462  void loadContacts()463  void groups.refresh()464  return out465}466export async function exportVcf(): Promise<Blob> {467  const r = await nx.raw("contacts/export.vcf", { headers: { accept: "text/vcard" } })468  return new Blob([await r.arrayBuffer()], { type: "text/vcard;charset=utf-8" })469}470export const suggestContacts = async (q: string, signal?: AbortSignal, limit = 8): Promise<ContactSuggestion[]> =>471  (await nx.list<ContactSuggestion>("contacts/suggest", { q: q.slice(0, 120), limit }, signal)).filter((s) => s && typeof s.email === "string" && typeof s.contact_id === "string")472/** Fiche (enregistrée ou suggérée) qui porte exactement cette adresse, s'il y en a une. */473export async function findByEmail(email: string, signal?: AbortSignal): Promise<Contact | null> {474  const addr = email.trim().toLowerCase()475  if (!addr) return null476  const r = await nx.get<{ data: unknown }>("contacts", { q: addr, limit: 10 }, signal)477  return normalizeContacts(r.data).find((c) => c.emails.some((e) => e.email === addr)) ?? null478}479/** Perte de session ou retrait du module : rien ne survit en mémoire. */480export function resetContacts() {481  listGen++482  cardGen++483  listAbort?.abort()484  CT.set(initial())485  CU.set({ dialog: null })486}487488// ---------------------------------------------------------------- dialogues de l'écran (ouverts aussi depuis la palette)489export type ContactDialog = { type: "edit"; contact: Contact | null; init?: Partial<ContactForm> } | { type: "duplicates" } | { type: "groups" } | { type: "imported"; result: ImportResult }490export const CU = createStore<{ dialog: ContactDialog | null }>({ dialog: null })491export const closeContactDialog = () => CU.set({ dialog: null })492
Files main
Menu

Theme