Repository Public
1// SP Mail Next — contacts unifiés : un carnet par utilisateur pour toutes ses boîtes. Correspondants moissonnés par le veilleur (suggestions),2// fiches gérées par l'utilisateur, groupes, autocomplétion classée, import/export vCard, doublons et fusion, historique des échanges.3import crypto from "node:crypto"4import type { FastifyInstance, FastifyRequest } from "fastify"5import type { Readable } from "node:stream"6import { z } from "zod"7import { sql, type Sql } from "../db.js"8import { folders, jmapOk } from "../mailjmap.js"9import { bad, parse, zUuid } from "../util.js"10import { decodeCursor, encodeCursor } from "../v1/ids.js"11import { nextUser, userMailboxes } from "./common.js"12import { onInbound, type InboundEmail } from "./hooks.js"13import { fold } from "./query.js"14import { presentSummary } from "./search.js"15import { decodeVcf, parseVcards, writeVcards, type VCard } from "./vcard.js"1617const MAX_SAVED = 10_00018const IMPORT_MAX_BYTES = 2 * 1024 * 102419// Les dix teintes du système de design ; la teinte d'une adresse suit la même règle (FNV-1a 32 bits) que les apps natives et le webmail.20const PALETTE = ["#b3261e", "#a14a00", "#7a5c00", "#2e6b2e", "#00695c", "#1d5fa8", "#4a4fb5", "#7a3fa0", "#a8327a", "#5c5f66"]21const EMAIL_RE = /^[^\s@<>"]+@[^\s@<>"]+\.[^\s@<>"]+$/22const iso = (d: Date | string | null | undefined) => (d ? new Date(d).toISOString() : null)23export function avatarColor(seed: string): string {24 let h = 216613626125 for (const b of Buffer.from(seed.trim().toLowerCase(), "utf8")) h = Math.imul(h ^ b, 16777619) >>> 026 return PALETTE[h % PALETTE.length]27}28const likeEscape = (s: string) => s.replace(/[\\%_]/g, (c) => `\\${c}`)2930// ------------------------------------------------------------------ formes31type ContactRow = {32 id: string; user_id: string; kind: "saved" | "suggested"; name: string; organization: string | null; title: string | null; phones: { number: string; label?: string | null }[]33 notes: string | null; favorite: boolean; vip: boolean; avatar_color: string; sent_count: number; received_count: number; last_at: Date | null; created_at: Date; updated_at: Date34}35type EmailRow = { contact_id: string; email: string; label: string | null; position: number }36function present(c: ContactRow, emails: EmailRow[], groups: string[]) {37 return {38 id: c.id, kind: c.kind, name: c.name, emails: emails.map((e) => ({ email: e.email, label: e.label ?? null })), organization: c.organization ?? null, title: c.title ?? null,39 phones: (c.phones ?? []).map((p) => ({ number: p.number, label: p.label ?? null })), notes: c.notes ?? null, favorite: c.favorite, vip: c.vip, groups, avatar_color: c.avatar_color,40 stats: { sent: c.sent_count, received: c.received_count, last_at: iso(c.last_at) }, created_at: iso(c.created_at), updated_at: iso(c.updated_at),41 }42}43export type Contact = ReturnType<typeof present>44/** Complète des lignes `contacts` avec leurs adresses et leurs groupes (ordre conservé). */45async function hydrate(rows: ContactRow[], db: Sql = sql): Promise<Contact[]> {46 if (!rows.length) return []47 const ids = rows.map((r) => r.id)48 const emails = (await db`select contact_id, email, label, position from contact_emails where contact_id = any(${ids}::uuid[]) order by position, email`) as unknown as EmailRow[]49 const members = await db`select contact_id, group_id from contact_group_members where contact_id = any(${ids}::uuid[])`50 return rows.map((r) => present(r, emails.filter((e) => e.contact_id === r.id), members.filter((m) => m.contact_id === r.id).map((m) => m.group_id as string)))51}52async function ownContact(userId: string, id: string, db: Sql = sql): Promise<ContactRow> {53 if (!zUuid.safeParse(id).success) throw bad("not_found", 404)54 const [c] = await db`select * from contacts where id = ${id} and user_id = ${userId}`55 if (!c) throw bad("not_found", 404)56 return c as unknown as ContactRow57}58/** Activité d'un contact : fréquence (un envoi pèse plus qu'une réception) × récence (demi-vie d'environ un mois). */59export function activity(sent: number, received: number, lastAt: Date | string | null, now = Date.now()): number {60 const days = lastAt ? Math.max(0, (now - new Date(lastAt).getTime()) / 86400_000) : 36561 return (sent * 3 + received) / (1 + days / 30)62}63/** Classement de l'autocomplétion : enregistré > favori > fréquence × récence. */64export const suggestScore = (c: { kind: string; favorite: boolean; sent_count: number; received_count: number; last_at: Date | string | null }, now = Date.now()) =>65 Math.round(((c.kind === "saved" ? 2000 : 0) + (c.favorite ? 1000 : 0) + Math.min(999, activity(c.sent_count, c.received_count, c.last_at, now))) * 1000) / 10006667// ------------------------------------------------------------------ validation68const zText = (max: number) => z.string().trim().max(max).refine((s) => !/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/.test(s), "control characters are not allowed")69const zEmail = z.string().trim().toLowerCase().max(254).regex(EMAIL_RE, "invalid e-mail address")70const zLabel = z.string().trim().max(24).nullable().optional()71const zContactFields = {72 name: zText(120), emails: z.array(z.object({ email: zEmail, label: zLabel }).strict()).max(20),73 organization: zText(160).nullable(), title: zText(160).nullable(), phones: z.array(z.object({ number: zText(40).min(1), label: zLabel }).strict()).max(20),74 notes: zText(4000).nullable(), favorite: z.boolean(), vip: z.boolean(), groups: z.array(zUuid).max(100), kind: z.enum(["saved"]),75}76const zCreate = z.object({ ...zContactFields, name: zContactFields.name.optional(), emails: zContactFields.emails.optional(), organization: zContactFields.organization.optional(), title: zContactFields.title.optional(),77 phones: zContactFields.phones.optional(), notes: zContactFields.notes.optional(), favorite: z.boolean().optional(), vip: z.boolean().optional(), groups: zContactFields.groups.optional(), kind: zContactFields.kind.optional() }).strict()78type Input = z.infer<typeof zCreate>7980// ------------------------------------------------------------------ écriture (toujours dans une transaction)81/**82 * Fixe la liste d'adresses d'une fiche. Une adresse n'appartient qu'à une fiche par utilisateur : celle d'une suggestion est reprise83 * (la suggestion vidée est absorbée, avec ses compteurs) ; celle d'une autre fiche enregistrée est un conflit (409).84 */85async function setEmails(tx: Sql, userId: string, contactId: string, emails: { email: string; label?: string | null }[]) {86 const wanted = [...new Map(emails.map((e) => [e.email, e])).values()]87 await tx`delete from contact_emails where contact_id = ${contactId} and email <> all(${wanted.map((e) => e.email)}::text[])`88 for (const [i, e] of wanted.entries()) {89 const [cur] = await tx`select ce.contact_id, c.kind from contact_emails ce join contacts c on c.id = ce.contact_id where ce.user_id = ${userId} and ce.email = ${e.email} for update of ce`90 if (!cur) await tx`insert into contact_emails (contact_id, user_id, email, label, position) values (${contactId}, ${userId}, ${e.email}, ${e.label ?? null}, ${i})`91 else if (cur.contact_id === contactId) await tx`update contact_emails set label = ${e.label ?? null}, position = ${i} where contact_id = ${contactId} and email = ${e.email}`92 else if (cur.kind === "suggested") {93 await tx`update contact_emails set contact_id = ${contactId}, label = ${e.label ?? null}, position = ${i} where user_id = ${userId} and email = ${e.email}`94 await absorbIfEmpty(tx, cur.contact_id, contactId)95 } else throw bad("email_in_use", 409, `${e.email} already belongs to another contact`)96 }97}98/** Une suggestion qui n'a plus d'adresse disparaît ; ses compteurs rejoignent la fiche qui a repris son adresse. */99async function absorbIfEmpty(tx: Sql, fromId: string, intoId: string) {100 const [left] = await tx`select 1 from contact_emails where contact_id = ${fromId} limit 1`101 if (left) return102 const [old] = await tx`delete from contacts where id = ${fromId} and kind = 'suggested' returning sent_count, received_count, last_at`103 if (old) await tx`update contacts set sent_count = sent_count + ${old.sent_count}, received_count = received_count + ${old.received_count},104 last_at = greatest(last_at, ${old.last_at}::timestamptz) where id = ${intoId}`105}106async function setGroups(tx: Sql, userId: string, contactId: string, groups: string[]) {107 const ids = [...new Set(groups)]108 if (ids.length) {109 const known = await tx`select id from contact_groups where user_id = ${userId} and id = any(${ids}::uuid[])`110 if (known.length !== ids.length) throw bad("unknown_group", 400, "groups must be ids of your contact groups")111 }112 await tx`delete from contact_group_members where contact_id = ${contactId} and group_id <> all(${ids}::uuid[])`113 for (const g of ids) await tx`insert into contact_group_members (group_id, contact_id) values (${g}, ${contactId}) on conflict do nothing`114}115async function createContact(tx: Sql, userId: string, b: Input): Promise<string> {116 const emails = b.emails ?? []117 if (!(b.name ?? "") && !emails.length && !(b.phones ?? []).length) throw bad("invalid_request", 400, "A contact needs a name, an e-mail address or a phone number")118 const [n] = await tx`select count(*)::int as n from contacts where user_id = ${userId} and kind = 'saved'`119 if (n.n >= MAX_SAVED) throw bad("limit_reached", 409, `At most ${MAX_SAVED} saved contacts per user`)120 const [c] = await tx`insert into contacts (user_id, kind, name, organization, title, phones, notes, favorite, vip, avatar_color)121 values (${userId}, 'saved', ${b.name ?? ""}, ${b.organization || null}, ${b.title || null}, ${tx.json((b.phones ?? []) as never)}, ${b.notes || null}, ${b.favorite ?? false}, ${b.vip ?? false}, ${avatarColor(emails[0]?.email ?? b.name ?? "")}) returning id`122 await setEmails(tx, userId, c.id, emails)123 if (b.groups) await setGroups(tx, userId, c.id, b.groups)124 return c.id as string125}126127// ------------------------------------------------------------------ moisson (crochet du veilleur : écritures en base seulement)128const AUTOMATED = /^(mailer-daemon|postmaster|no[-_.]?reply|do[-_.]?not[-_.]?reply|bounces?|notifications?|auto[-_.]?reply|autoreply|listserv|majordomo)([+\-._=].*)?$/129/** Expéditeur automatique (jamais un correspondant) : démon de courrier, « no-reply », rebonds, notifications. */130export const isAutomatedSender = (email: string) => AUTOMATED.test(email.toLowerCase().split("@")[0] ?? "")131/** Trafic de liste ou automatique d'après les en-têtes demandés par le veilleur. */132export function isBulk(e: InboundEmail): boolean {133 const h = (k: string) => String(e[k] ?? "").trim().toLowerCase()134 if (h("header:List-Id:asText")) return true135 if (/^(bulk|list|junk)\b/.test(h("header:Precedence:asText"))) return true136 const auto = h("header:Auto-Submitted:asText")137 return !!auto && !auto.startsWith("no")138}139const cleanName = (name: unknown, email: string) => {140 const n = String(name ?? "").replace(/[\u0000-\u001f\u007f]/g, " ").replace(/^['"\s]+|['"\s]+$/g, "").replace(/\s+/g, " ").slice(0, 120)141 return n.toLowerCase() === email ? "" : n142}143/** Compte un échange avec un correspondant ; inconnu, il devient une suggestion. Sûr face à une moisson concurrente d'une autre boîte du même utilisateur. */144async function bump(tx: Sql, userId: string, email: string, name: string, dir: "sent" | "received", at: Date) {145 let [hit] = await tx`select contact_id from contact_emails where user_id = ${userId} and email = ${email}`146 if (!hit) {147 const [c] = await tx`insert into contacts (user_id, kind, name, avatar_color) values (${userId}, 'suggested', ${name}, ${avatarColor(email)}) returning id`148 const ins = await tx`insert into contact_emails (contact_id, user_id, email) values (${c.id}, ${userId}, ${email}) on conflict (user_id, email) do nothing returning contact_id`149 if (ins.length) hit = ins[0]150 else {151 await tx`delete from contacts where id = ${c.id}`152 ;[hit] = await tx`select contact_id from contact_emails where user_id = ${userId} and email = ${email}`153 if (!hit) return154 }155 }156 await tx`update contacts set sent_count = sent_count + ${dir === "sent" ? 1 : 0}, received_count = received_count + ${dir === "received" ? 1 : 0},157 last_at = greatest(last_at, ${at}::timestamptz),158 name = case when name = '' and kind = 'suggested' then ${name} else name end where id = ${hit.contact_id}`159}160const dateOf = (e: InboundEmail) => { const t = Date.parse(String(e.sentAt ?? e.receivedAt ?? "")); return new Date(Number.isNaN(t) ? Date.now() : Math.min(t, Date.now())) }161162onInbound("contacts", async (tx, batch) => {163 const userId = batch.mb.user_id164 const sentCopies = [...batch.createdOther, ...batch.updated].filter((x) => x.roles.includes("sent") && !x.email.keywords?.$draft)165 const received = batch.received.filter((x) => !x.roles.includes("junk") && !x.roles.includes("trash"))166 if (batch.destroyed.length) await tx`delete from contact_sent_seen where mailbox_id = ${batch.mb.id} and email_id = any(${batch.destroyed}::text[])`167 if (!received.length && !sentCopies.length) return168 const own = new Set((await tx`select a.address from addresses a join mailboxes m on m.id = a.mailbox_id where m.user_id = ${userId} union select address from mailboxes where user_id = ${userId}`).map((r) => String(r.address).toLowerCase()))169 for (const { email: e } of received) {170 const from = (e.from ?? [])[0] as { email?: string; name?: string } | undefined171 const addr = String(from?.email ?? "").trim().toLowerCase()172 if (!EMAIL_RE.test(addr) || addr.length > 254 || own.has(addr) || isAutomatedSender(addr) || isBulk(e)) continue173 await bump(tx, userId, addr, cleanName(from?.name, addr), "received", dateOf(e))174 }175 // Copies « Envoyés » : un message peut y arriver par création directe ou par modification du brouillon soumis — il n'est compté qu'une fois.176 for (const { email: e } of sentCopies) {177 const first = await tx`insert into contact_sent_seen (mailbox_id, email_id) values (${batch.mb.id}, ${e.id}) on conflict do nothing returning 1`178 if (!first.length) continue179 const seen = new Set<string>()180 for (const r of [...(e.to ?? []), ...(e.cc ?? []), ...(e.bcc ?? [])] as { email?: string; name?: string }[]) {181 const addr = String(r?.email ?? "").trim().toLowerCase()182 if (!EMAIL_RE.test(addr) || addr.length > 254 || own.has(addr) || seen.has(addr) || isAutomatedSender(addr)) continue183 seen.add(addr)184 await bump(tx, userId, addr, cleanName(r.name, addr), "sent", dateOf(e))185 }186 }187})188189// ------------------------------------------------------------------ doublons190/** Adresse normalisée pour la détection de doublons : sans « +étiquette », et sans points pour Gmail. */191export function normalizeEmail(email: string): string {192 const [rawLocal, rawDomain = ""] = email.toLowerCase().split("@")193 const domain = rawDomain === "googlemail.com" ? "gmail.com" : rawDomain194 let local = rawLocal.split("+")[0]195 if (domain === "gmail.com") local = local.replace(/\./g, "")196 return `${local}@${domain}`197}198export const normalizeName = (name: string) => fold(name).replace(/[^\p{L}\p{N}]+/gu, " ").trim()199200// ------------------------------------------------------------------ import vCard201async function readText(req: FastifyRequest): Promise<string> {202 const b = req.body as unknown203 if (typeof b === "string") return b.replace(/^/, "")204 if (Buffer.isBuffer(b)) return decodeVcf(b)205 if (b && typeof (b as Readable).on === "function") {206 const chunks: Buffer[] = []207 let size = 0208 for await (const chunk of b as Readable) {209 size += (chunk as Buffer).length210 if (size > IMPORT_MAX_BYTES) throw bad("too_large", 413, "The vCard file is larger than 2 MB")211 chunks.push(chunk as Buffer)212 }213 return decodeVcf(Buffer.concat(chunks))214 }215 throw bad("invalid_request", 400, "Send the .vcf file as the request body (Content-Type: text/vcard)")216}217/** Importe une fiche : complète la fiche enregistrée qui possède déjà l'une de ses adresses, sinon en crée une. */218async function importCard(tx: Sql, userId: string, card: VCard): Promise<"imported" | "updated"> {219 const emails = card.emails.map((e) => e.email)220 const [owner] = emails.length ? await tx`select c.* from contact_emails ce join contacts c on c.id = ce.contact_id where ce.user_id = ${userId} and ce.email = any(${emails}::text[]) and c.kind = 'saved' order by c.created_at limit 1` : []221 if (!owner) {222 // Les adresses déjà portées par une AUTRE fiche enregistrée restent où elles sont.223 const taken = new Set(emails.length ? (await tx`select ce.email from contact_emails ce join contacts c on c.id = ce.contact_id where ce.user_id = ${userId} and ce.email = any(${emails}::text[]) and c.kind = 'saved'`).map((r) => r.email as string) : [])224 await createContact(tx, userId, { name: card.name, emails: card.emails.filter((e) => !taken.has(e.email)), organization: card.organization, title: card.title, phones: card.phones, notes: card.notes })225 return "imported"226 }227 const cur = owner as unknown as ContactRow228 const mine = (await tx`select email, label, position from contact_emails where contact_id = ${cur.id} order by position, email`) as unknown as EmailRow[]229 const foreign = new Set((await tx`select ce.email from contact_emails ce join contacts c on c.id = ce.contact_id where ce.user_id = ${userId} and ce.email = any(${emails}::text[]) and c.kind = 'saved' and c.id <> ${cur.id}`).map((r) => r.email as string))230 const merged = [...mine.map((e) => ({ email: e.email, label: e.label })), ...card.emails.filter((e) => !foreign.has(e.email) && !mine.some((m) => m.email === e.email))].slice(0, 20)231 await setEmails(tx, userId, cur.id, merged)232 const digits = (s: string) => s.replace(/\D/g, "")233 const phones = [...(cur.phones ?? []), ...card.phones.filter((p) => !(cur.phones ?? []).some((x) => digits(x.number) === digits(p.number)))].slice(0, 20)234 await tx`update contacts set name = ${cur.name || card.name}, organization = ${cur.organization ?? card.organization}, title = ${cur.title ?? card.title}, notes = ${cur.notes ?? card.notes},235 phones = ${tx.json(phones as never)}, updated_at = now() where id = ${cur.id}`236 return "updated"237}238239export function contactRoutes(app: FastifyInstance) {240 // ---------------------------------------------------------------- liste et autocomplétion241 app.get("/api/next/contacts", async (req) => {242 const a = await nextUser(req)243 const q = parse(z.object({244 q: z.string().trim().max(200).optional(), group: zUuid.optional(), favorite: z.enum(["0", "1", "true", "false"]).optional(), kind: z.enum(["saved", "suggested", "all"]).default("all"),245 limit: z.coerce.number().int().min(1).max(200).default(50), cursor: z.string().max(2000).optional(),246 }), req.query)247 const c = decodeCursor<{ e: number; n: string; i: string }>(q.cursor, (x) => (x.e === 0 || x.e === 1) && typeof x.n === "string" && zUuid.safeParse(x.i).success)248 const like = q.q ? `%${likeEscape(q.q.toLowerCase())}%` : null249 const fav = q.favorite === "1" || q.favorite === "true"250 // Les fiches sans nom (suggestions réduites à une adresse) viennent après les fiches nommées.251 const rows = (await sql`select c.* from contacts c where c.user_id = ${a.userId}252 ${q.kind === "all" ? sql`` : sql`and c.kind = ${q.kind}`} ${fav ? sql`and c.favorite` : sql``}253 ${q.group ? sql`and exists (select 1 from contact_group_members m where m.contact_id = c.id and m.group_id = ${q.group})` : sql``}254 ${like ? sql`and (lower(c.name) like ${like} or lower(coalesce(c.organization, '')) like ${like} or exists (select 1 from contact_emails e where e.contact_id = c.id and e.email like ${like}))` : sql``}255 ${c ? sql`and ((case when c.name = '' then 1 else 0 end), lower(c.name), c.id) > (${c.e}, ${c.n}, ${c.i}::uuid)` : sql``}256 order by (case when c.name = '' then 1 else 0 end), lower(c.name), c.id limit ${q.limit + 1}`) as unknown as ContactRow[]257 const page = rows.slice(0, q.limit)258 const last = page[page.length - 1]259 return { data: await hydrate(page), next_cursor: rows.length > q.limit ? encodeCursor({ e: last.name === "" ? 1 : 0, n: last.name.toLowerCase(), i: last.id }) : null }260 })261262 app.get("/api/next/contacts/suggest", async (req) => {263 const a = await nextUser(req, "next-suggest", 1200)264 const q = parse(z.object({ q: z.string().trim().max(120).default(""), limit: z.coerce.number().int().min(1).max(50).default(8) }), req.query)265 const needle = q.q.toLowerCase()266 const like = `%${likeEscape(needle)}%`267 const rows = await sql`select c.id, c.kind, c.name, c.favorite, c.sent_count, c.received_count, c.last_at, e.email268 from contacts c join contact_emails e on e.contact_id = c.id269 where c.user_id = ${a.userId} ${needle ? sql`and (e.email like ${like} or lower(c.name) like ${like})` : sql``}270 order by (c.kind = 'saved') desc, c.favorite desc, (c.sent_count * 3 + c.received_count) desc, c.last_at desc nulls last limit 400`271 const now = Date.now()272 const data = rows.map((r) => ({ name: r.name as string, email: r.email as string, contact_id: r.id as string, kind: r.kind as string, favorite: r.favorite as boolean, score: suggestScore(r as never, now) }))273 .sort((x, y) => y.score - x.score || x.email.localeCompare(y.email)).slice(0, q.limit)274 return { data }275 })276277 // ---------------------------------------------------------------- vCard, doublons, fusion (avant les routes « :id »)278 app.post("/api/next/contacts/import", { bodyLimit: IMPORT_MAX_BYTES + 4096 }, async (req) => {279 const a = await nextUser(req, "next-import", 30)280 const text = await readText(req)281 if (Buffer.byteLength(text, "utf8") > IMPORT_MAX_BYTES * 2) throw bad("too_large", 413, "The vCard file is larger than 2 MB")282 const { cards, skipped } = parseVcards(text)283 if (!cards.length) throw bad("invalid_vcard", 400, "No usable vCard was found in the file")284 const out = { total: cards.length + skipped, imported: 0, updated: 0, skipped }285 await sql.begin(async (tx) => {286 for (const card of cards) out[await importCard(tx as never, a.userId, card)]++287 })288 return out289 })290291 app.get("/api/next/contacts/export.vcf", async (req, reply) => {292 const a = await nextUser(req, "next-export", 30)293 const q = parse(z.object({ kind: z.enum(["saved", "suggested", "all"]).default("saved"), group: zUuid.optional() }), req.query)294 const rows = (await sql`select c.* from contacts c where c.user_id = ${a.userId} ${q.kind === "all" ? sql`` : sql`and c.kind = ${q.kind}`}295 ${q.group ? sql`and exists (select 1 from contact_group_members m where m.contact_id = c.id and m.group_id = ${q.group})` : sql``}296 order by lower(c.name), c.id`) as unknown as ContactRow[]297 const cards = (await hydrate(rows)).map((c) => ({ name: c.name, emails: c.emails, phones: c.phones, organization: c.organization, title: c.title, notes: c.notes }))298 reply.header("content-type", "text/vcard; charset=utf-8").header("content-disposition", `attachment; filename="contacts.vcf"`)299 return reply.send(writeVcards(cards))300 })301302 app.get("/api/next/contacts/duplicates", async (req) => {303 const a = await nextUser(req)304 const rows = (await sql`select * from contacts where user_id = ${a.userId} order by (kind = 'saved') desc, created_at limit 20000`) as unknown as ContactRow[]305 const emails = await sql`select contact_id, email from contact_emails where user_id = ${a.userId}`306 const sets = new Map<string, Set<string>>()307 const add = (key: string, id: string) => { const s = sets.get(key) ?? new Set<string>(); s.add(id); sets.set(key, s) }308 for (const e of emails) add(`email:${normalizeEmail(e.email)}`, e.contact_id)309 for (const r of rows) { const n = normalizeName(r.name); if (n.length >= 2) add(`name:${n}`, r.id) }310 const seen = new Set<string>()311 const groups: { reason: "email" | "name"; key: string; ids: string[] }[] = []312 for (const [key, ids] of sets) {313 if (ids.size < 2) continue314 const sig = [...ids].sort().join(",")315 if (seen.has(sig)) continue // même ensemble de fiches trouvé par l'adresse ET par le nom : une seule entrée316 seen.add(sig)317 groups.push({ reason: key.startsWith("email:") ? "email" : "name", key: key.slice(key.indexOf(":") + 1), ids: [...ids] })318 }319 const all = new Map((await hydrate(rows.filter((r) => groups.some((g) => g.ids.includes(r.id))))).map((c) => [c.id, c]))320 return { data: groups.slice(0, 200).map((g) => ({ reason: g.reason, key: g.key, contacts: g.ids.map((id) => all.get(id)!).filter(Boolean) })) }321 })322323 app.post("/api/next/contacts/merge", async (req) => {324 const a = await nextUser(req)325 const b = parse(z.object({ keep: zUuid, merge: z.array(zUuid).min(1).max(50) }).strict(), req.body)326 const others = [...new Set(b.merge)]327 if (others.includes(b.keep)) throw bad("invalid_request", 400, "`merge` must not contain `keep`")328 // Tout ou rien : adresses, téléphones, groupes et compteurs rejoignent la fiche gardée, puis les autres disparaissent.329 await sql.begin(async (tx) => {330 const rows = (await tx`select * from contacts where user_id = ${a.userId} and id = any(${[b.keep, ...others]}::uuid[]) for update`) as unknown as ContactRow[]331 const keep = rows.find((r) => r.id === b.keep)332 if (!keep || rows.length !== others.length + 1) throw bad("not_found", 404)333 const gone = others.map((id) => rows.find((r) => r.id === id)!)334 // Les adresses suivent dans l'ordre de `merge`, après celles de la fiche gardée.335 for (const other of others) {336 const [pos] = await tx`select coalesce(max(position) + 1, 0)::int as p from contact_emails where contact_id = ${keep.id}`337 await tx`update contact_emails set contact_id = ${keep.id}, position = position + ${pos.p} where contact_id = ${other}`338 }339 await tx`insert into contact_group_members (group_id, contact_id) select distinct group_id, ${keep.id}::uuid from contact_group_members where contact_id = any(${others}::uuid[]) on conflict do nothing`340 const digits = (s: string) => s.replace(/\D/g, "")341 const phones = [...(keep.phones ?? [])]342 for (const g of gone) for (const p of g.phones ?? []) if (!phones.some((x) => digits(x.number) === digits(p.number))) phones.push(p)343 const first = <K extends keyof ContactRow>(k: K) => keep[k] || gone.map((g) => g[k]).find(Boolean) || keep[k]344 const lastAt = [keep, ...gone].map((r) => (r.last_at ? new Date(r.last_at).getTime() : 0)).reduce((x, y) => Math.max(x, y), 0)345 await tx`update contacts set kind = ${[keep, ...gone].some((r) => r.kind === "saved") ? "saved" : "suggested"}, name = ${first("name") as string}, organization = ${(first("organization") as string | null) ?? null},346 title = ${(first("title") as string | null) ?? null}, notes = ${[keep.notes, ...gone.map((g) => g.notes)].filter(Boolean).join("\n\n").slice(0, 4000) || null}, phones = ${tx.json(phones.slice(0, 20) as never)},347 favorite = ${[keep, ...gone].some((r) => r.favorite)}, vip = ${[keep, ...gone].some((r) => r.vip)},348 sent_count = ${[keep, ...gone].reduce((n, r) => n + r.sent_count, 0)}, received_count = ${[keep, ...gone].reduce((n, r) => n + r.received_count, 0)},349 last_at = ${lastAt ? new Date(lastAt) : null}, updated_at = now() where id = ${keep.id}`350 await tx`delete from contacts where id = any(${others}::uuid[])`351 })352 return (await hydrate([await ownContact(a.userId, b.keep)]))[0]353 })354355 // ---------------------------------------------------------------- fiches356 app.post("/api/next/contacts", async (req, reply) => {357 const a = await nextUser(req)358 const b = parse(zCreate, req.body)359 const id = await sql.begin((tx) => createContact(tx as never, a.userId, b))360 return reply.status(201).send((await hydrate([await ownContact(a.userId, id)]))[0])361 })362 app.get("/api/next/contacts/:id", async (req) => {363 const a = await nextUser(req)364 return (await hydrate([await ownContact(a.userId, (req.params as { id: string }).id)]))[0]365 })366 app.patch("/api/next/contacts/:id", async (req) => {367 const a = await nextUser(req)368 const id = (req.params as { id: string }).id369 const b = parse(zCreate, req.body)370 const raw = (req.body ?? {}) as Record<string, unknown>371 const given = (k: string) => Object.prototype.hasOwnProperty.call(raw, k)372 await sql.begin(async (tx) => {373 const cur = await ownContact(a.userId, id, tx as never)374 // Toute modification par l'utilisateur fait d'une suggestion une fiche enregistrée.375 await tx`update contacts set kind = 'saved', name = ${given("name") ? b.name ?? "" : cur.name}, organization = ${given("organization") ? b.organization || null : cur.organization},376 title = ${given("title") ? b.title || null : cur.title}, phones = ${tx.json((given("phones") ? b.phones ?? [] : cur.phones ?? []) as never)}, notes = ${given("notes") ? b.notes || null : cur.notes},377 favorite = ${b.favorite ?? cur.favorite}, vip = ${b.vip ?? cur.vip}, updated_at = now() where id = ${id}`378 if (b.emails) await setEmails(tx as never, a.userId, id, b.emails)379 if (b.groups) await setGroups(tx as never, a.userId, id, b.groups)380 })381 return (await hydrate([await ownContact(a.userId, id)]))[0]382 })383 app.delete("/api/next/contacts/:id", async (req) => {384 const a = await nextUser(req)385 const c = await ownContact(a.userId, (req.params as { id: string }).id)386 await sql`delete from contacts where id = ${c.id}`387 return { ok: true }388 })389390 // ---------------------------------------------------------------- historique des échanges391 app.get("/api/next/contacts/:id/history", async (req) => {392 const a = await nextUser(req, "next-search", 240)393 const c = await ownContact(a.userId, (req.params as { id: string }).id)394 const { limit } = parse(z.object({ limit: z.coerce.number().int().min(1).max(100).default(20) }), req.query)395 const emails = (await sql`select email from contact_emails where contact_id = ${c.id}`).map((r) => r.email as string)396 if (!emails.length) return { data: [], reminders: [] }397 const set = new Set(emails)398 const who = { operator: "OR", conditions: emails.flatMap((e) => [{ from: e }, { to: e }, { cc: e }]) }399 const boxes = await userMailboxes(a.userId)400 const parts = await Promise.all(boxes.map(async (mb) => {401 const fl = await folders(mb)402 const hidden = fl.filter((f) => f.role === "trash" || f.role === "junk").map((f) => f.id)403 const res = await jmapOk(mb, [404 ["Email/query", { filter: hidden.length ? { operator: "AND", conditions: [who, { inMailboxOtherThan: hidden }] } : who, sort: [{ property: "receivedAt", isAscending: false }], limit }, "q"],405 ["Email/get", { "#ids": { resultOf: "q", name: "Email/query", path: "/ids" }, properties: ["threadId", "mailboxIds", "keywords", "from", "to", "cc", "subject", "preview", "receivedAt", "size", "hasAttachment"] }, "g"],406 ])407 // La recherche plein texte du serveur peut être plus large que l'adresse exacte : on ne garde que les vrais échanges.408 return (res[1].list as (Record<string, any> & { id: string })[]).filter((e) => [...(e.from ?? []), ...(e.to ?? []), ...(e.cc ?? [])].some((x: { email?: string }) => set.has(String(x.email ?? "").toLowerCase())))409 .map((e) => ({ ...presentSummary(mb, e, fl), direction: (e.from ?? []).some((x: { email?: string }) => set.has(String(x.email ?? "").toLowerCase())) ? "received" as const : "sent" as const }))410 }))411 const data = parts.flat().sort((x, y) => Date.parse(y.received_at) - Date.parse(x.received_at) || (x.email_id < y.email_id ? -1 : 1)).slice(0, limit)412 // Rappels en attente sur ces fils ou avec ce correspondant (la table appartient au module des rappels : absente, la liste est vide).413 let reminders: Record<string, unknown>[] = []414 try {415 const [t] = await sql`select to_regclass('public.reminders') as t`416 if (t?.t) reminders = (await sql`select id, mailbox_id, email_id, thread_id, subject, due_at, only_if_no_reply, note, status from reminders417 where user_id = ${a.userId} and status in ('pending', 'due') and (thread_id = any(${data.map((d) => d.thread_id)}::text[]) or lower(counterpart->>'email') = any(${emails}::text[])) order by due_at limit 50`)418 .map((r) => ({ ...r, due_at: iso(r.due_at as Date) }))419 } catch { reminders = [] }420 return { data, reminders }421 })422423 // ---------------------------------------------------------------- groupes424 const zColor = z.string().regex(/^#[0-9a-fA-F]{6}$/, "expected #rrggbb").transform((s) => s.toLowerCase())425 const presentGroup = (g: Record<string, any>) => ({ id: g.id as string, name: g.name as string, color: g.color as string, members: (g.members ?? 0) as number })426 const dup = (e: unknown) => { if ((e as { code?: string })?.code === "23505") throw bad("name_taken", 409, "A group with this name already exists"); throw e }427 app.get("/api/next/contact-groups", async (req) => {428 const a = await nextUser(req)429 return { data: (await sql`select g.*, (select count(*)::int from contact_group_members m where m.group_id = g.id) as members from contact_groups g where g.user_id = ${a.userId} order by lower(g.name)`).map(presentGroup) }430 })431 app.post("/api/next/contact-groups", async (req, reply) => {432 const a = await nextUser(req)433 const b = parse(z.object({ name: zText(60).min(1), color: zColor.optional() }).strict(), req.body)434 const [n] = await sql`select count(*)::int as n from contact_groups where user_id = ${a.userId}`435 if (n.n >= 200) throw bad("limit_reached", 409, "At most 200 contact groups per user")436 const [g] = await sql`insert into contact_groups (user_id, name, color) values (${a.userId}, ${b.name}, ${b.color ?? avatarColor(b.name)}) returning *`.catch(dup)437 return reply.status(201).send(presentGroup(g))438 })439 app.patch("/api/next/contact-groups/:id", async (req) => {440 const a = await nextUser(req)441 const id = (req.params as { id: string }).id442 if (!zUuid.safeParse(id).success) throw bad("not_found", 404)443 const b = parse(z.object({ name: zText(60).min(1).optional(), color: zColor.optional() }).strict(), req.body)444 const [g] = await sql`update contact_groups set name = coalesce(${b.name ?? null}, name), color = coalesce(${b.color ?? null}, color) where id = ${id} and user_id = ${a.userId}445 returning *, (select count(*)::int from contact_group_members m where m.group_id = contact_groups.id) as members`.catch(dup)446 if (!g) throw bad("not_found", 404)447 return presentGroup(g)448 })449 app.delete("/api/next/contact-groups/:id", async (req) => {450 const a = await nextUser(req)451 const id = (req.params as { id: string }).id452 const r = zUuid.safeParse(id).success ? await sql`delete from contact_groups where id = ${id} and user_id = ${a.userId} returning id` : []453 if (!r.length) throw bad("not_found", 404)454 return { ok: true }455 })456}457458/** Contacts les plus actifs (tableau de bord) : fréquence × récence, favoris en tête. */459export async function topContacts(userId: string, limit = 8): Promise<Contact[]> {460 const rows = (await sql`select * from contacts where user_id = ${userId} and (sent_count + received_count > 0 or favorite)461 order by last_at desc nulls last limit 300`) as unknown as ContactRow[]462 const now = Date.now()463 const score = (r: ContactRow) => (r.favorite ? 1000 : 0) + activity(r.sent_count, r.received_count, r.last_at, now)464 return hydrate(rows.sort((x, y) => score(y) - score(x)).slice(0, limit))465}466