SPB Git

Repository Public

next-contacts.test.ts 23.9 KB 270 lines typescript

1// SP Mail Next — contacts : moisson sur du vrai courrier reçu et envoyé (stg.spboucher.ai), classement de l'autocomplétion, fiches et groupes,2// aller-retour vCard (noms accentués, lignes pliées, quoted-printable), doublons, fusion, historique des échanges, cloisonnement entre deux utilisateurs.3import assert from "node:assert/strict"4import { after, before, test } from "node:test"5import { ApiError, ApiKey, Client, RUN, STG, cli, sql, startServer, stopServer, tokenOf, until } from "../harness"6import { mkKey, mkMailbox, purgeAll, sendAndWait, setupAdmin, type Box } from "./v1-helpers"7import { parseVcards } from "../../server/src/next/vcard"89let admin: Client, member: Client10let A: Box, C: Box, D: Box11let ka: ApiKey, kc: ApiKey, kd: ApiKey12let memberId = ""13const ALL = ["mail.send", "mail.read", "mail.search", "mail.modify", "mail.drafts"]1415async function rejects(p: Promise<unknown>, status: number, code?: string) {16  await assert.rejects(p, (e: unknown) => e instanceof ApiError && e.status === status && (!code || e.code === code), `attendu ${status} ${code ?? ""}`)17}18const contacts = async (c: Client, qs = "") => (await c.call("GET", `/api/next/contacts${qs}`)).data as any[]19const byEmail = async (c: Client, email: string) => (await contacts(c, `?q=${encodeURIComponent(email)}`)).find((x) => x.emails.some((e: any) => e.email === email))20const waitStats = (c: Client, email: string, ok: (s: { sent: number; received: number }) => boolean, what: string) => until(async () => { const x = await byEmail(c, email); return x && ok(x.stats) ? x : null }, what)21const acctOf = async (c: Client, b: Box) => (await c.call("GET", `/api/jmap/${b.id}/session`)).primaryAccounts["urn:ietf:params:jmap:mail"] as string22const vcf = (c: Client, body: string | Uint8Array, type = "text/vcard") => c.raw("POST", "/api/next/contacts/import", typeof body === "string" ? new TextEncoder().encode(body) : body, { "content-type": type })2324before(async () => {25  await startServer()26  admin = await setupAdmin()27  member = new Client("web")28  await member.enroll(tokenOf(await cli("invite")), "membre", "Membre")29  memberId = (await sql`select id from users where handle = 'membre'`)[0].id30  ;[A, C, D] = await Promise.all([mkMailbox(admin, "ca"), mkMailbox(admin, "cc", memberId), mkMailbox(admin, "cd", memberId)])31  ka = await mkKey(admin, { scopes: ALL, addresses: [A.addressId] })32  kc = await mkKey(admin, { scopes: ALL, addresses: [C.addressId] })33  kd = await mkKey(admin, { scopes: ALL, addresses: [D.addressId] })34})35after(async () => {36  await purgeAll(admin)37  await stopServer()38})3940test("moisson : un message reçu crée une suggestion ; liste de diffusion et « no-reply » ignorés ; copies « Envoyés » comptées une fois", async () => {41  assert.deepEqual(await contacts(admin), [])42  // C écrit deux fois à A : une seule suggestion, deux réceptions43  await sendAndWait(kc, { from: C.address, to: [A.address], subject: "Bonjour de C", text: "Premier message." })44  await sendAndWait(kc, { from: C.address, to: [A.address], subject: "Encore C", text: "Second message." })45  const c = await waitStats(admin, C.address, (s) => s.received === 2, "deux réceptions de C")46  assert.deepEqual([c.kind, c.name, c.favorite, c.vip, c.groups, c.stats.sent], ["suggested", "Essai cc", false, false, [], 0])47  assert.match(c.avatar_color, /^#[0-9a-f]{6}$/)48  assert.ok(Date.now() - Date.parse(c.stats.last_at) < 120_000)4950  // D envoie par JMAP un message de liste (List-Id) puis un message ordinaire : seul le second compte51  await sendAndWait(kd, { from: D.address, to: [C.address], subject: "amorce identité D", text: "x" })52  const acct = await acctOf(member, D)53  const r0 = await member.jmap(D.id, [["Identity/get", { accountId: acct }, "i"], ["Mailbox/get", { accountId: acct, properties: ["role"] }, "m"]])54  const identityId = (r0[0][1].list as any[]).find((i) => i.email === D.address).id55  const drafts = (r0[1][1].list as any[]).find((m) => m.role === "drafts").id56  const r1 = await member.jmap(D.id, [57    ["Email/set", { accountId: acct, create: { e: { mailboxIds: { [drafts]: true }, keywords: { $draft: true }, from: [{ email: D.address, name: "Annonces" }], to: [{ email: A.address }], subject: "Infolettre de D", "header:List-Id:asText": "Annonces <annonces.stg.spboucher.ai>", bodyValues: { t: { value: "Trafic de liste." } }, textBody: [{ partId: "t", type: "text/plain" }] } } }, "c"],58    ["EmailSubmission/set", { accountId: acct, create: { s: { identityId, emailId: "#e" } }, onSuccessDestroyEmail: ["#s"] }, "s"],59  ])60  assert.ok(r1[1][1].created?.s, JSON.stringify(r1))61  await until(async () => (await ka.call("GET", "/messages?folder=inbox&limit=50")).data.some((m: any) => m.subject === "Infolettre de D"), "réception de l'infolettre")62  await sendAndWait(kd, { from: D.address, to: [A.address], subject: "Vrai message de D", text: "Un vrai correspondant." })63  const d = await waitStats(admin, D.address, (s) => s.received >= 1, "réception de D")64  assert.equal(d.stats.received, 1, "le message de liste n'a pas été compté")6566  // A écrit trois fois à C : la copie « Envoyés » compte une fois par message, même si elle est modifiée ensuite67  const first = await sendAndWait(ka, { from: A.address, to: [{ email: C.address, name: "Camille C" }], subject: "Réponse 1", text: "x" })68  await sendAndWait(ka, { from: A.address, to: [C.address], cc: [D.address], subject: "Réponse 2", text: "x" })69  await waitStats(admin, C.address, (s) => s.sent === 2, "deux envois à C")70  await ka.call("PATCH", `/messages/${first.message_id}`, { starred: true })71  await sendAndWait(ka, { from: A.address, to: [C.address], subject: "Réponse 3", text: "x" })72  const c3 = await waitStats(admin, C.address, (s) => s.sent === 3, "trois envois à C")73  assert.deepEqual([c3.stats.sent, c3.stats.received, c3.name], [3, 2, "Essai cc"], "le drapeau posé sur la copie « Envoyés » ne recompte rien ; le nom moissonné reste")74  assert.equal((await waitStats(admin, D.address, (s) => s.sent === 1, "copie à D")).stats.received, 1)75  // l'utilisateur ne se moissonne pas lui-même, et l'autre utilisateur a son propre carnet76  assert.equal(await byEmail(admin, A.address), undefined)77  const mine = await waitStats(member, A.address, (s) => s.received >= 4, "réceptions de A chez le membre")78  assert.equal(mine.kind, "suggested")79  assert.equal(await byEmail(member, C.address), undefined, "ses propres adresses ne sont pas des contacts")80  assert.deepEqual((await contacts(admin)).map((x) => x.emails[0].email).sort(), [C.address, D.address].sort())81})8283test("autocomplétion : enregistré > favori > fréquence × récence", async () => {84  const zoe = await admin.call("POST", "/api/next/contacts", { name: "Zoé Ami", emails: [{ email: `zoe-${RUN}@${STG}`, label: "work" }] })85  const fav = await admin.call("POST", "/api/next/contacts", { name: "Carl Favori", emails: [{ email: `carl-${RUN}@${STG}` }, { email: `carl.perso-${RUN}@${STG}`, label: "home" }], favorite: true })86  assert.deepEqual([zoe.kind, zoe.emails, fav.favorite], ["saved", [{ email: `zoe-${RUN}@${STG}`, label: "work" }], true])87  const s = (await admin.call("GET", "/api/next/contacts/suggest?limit=10")).data as any[]88  assert.deepEqual(s.slice(0, 2).map((x) => x.email).sort(), [`carl-${RUN}@${STG}`, `carl.perso-${RUN}@${STG}`].sort())89  assert.deepEqual(s.slice(2).map((x) => x.email), [`zoe-${RUN}@${STG}`, C.address, D.address])90  assert.ok(s[0].score > s[2].score && s[2].score > s[3].score && s[3].score > s[4].score, JSON.stringify(s.map((x) => x.score)))91  assert.deepEqual([s[0].name, s[0].contact_id, s[0].favorite, s[3].kind], ["Carl Favori", fav.id, true, "suggested"])92  // filtre par nom ou par adresse, limite respectée93  assert.deepEqual(((await admin.call("GET", "/api/next/contacts/suggest?q=ZOÉ")).data as any[]).map((x) => x.email), [`zoe-${RUN}@${STG}`])94  assert.deepEqual(((await admin.call("GET", `/api/next/contacts/suggest?q=${encodeURIComponent(`api-cc-${RUN}`)}`)).data as any[]).map((x) => x.email), [C.address])95  assert.equal(((await admin.call("GET", "/api/next/contacts/suggest?limit=2")).data as any[]).length, 2)96  assert.deepEqual(((await admin.call("GET", "/api/next/contacts/suggest?q=%25")).data as any[]), [], "% n'est pas un joker")97  // le membre ne voit que ses correspondants98  assert.deepEqual(((await member.call("GET", "/api/next/contacts/suggest")).data as any[]).map((x) => x.email), [A.address])99})100101test("fiches : création, modification partielle, promotion d'une suggestion, conflit d'adresse, groupes, liste paginée, cloisonnement", async () => {102  const g = await admin.call("POST", "/api/next/contact-groups", { name: "Équipe", color: "#00AA00" })103  assert.deepEqual([g.name, g.color, g.members], ["Équipe", "#00aa00", 0])104  await rejects(admin.call("POST", "/api/next/contact-groups", { name: "équipe" }), 409, "name_taken")105  const full = await admin.call("POST", "/api/next/contacts", { name: "Béatrice Côté", emails: [{ email: "Bea@Exemple.test", label: "work" }], organization: "UQO", title: "Professeure", phones: [{ number: "+1 819 555-0100", label: "mobile" }], notes: "Rencontrée à Gatineau.", vip: true, groups: [g.id] })106  assert.deepEqual([full.name, full.emails, full.organization, full.title, full.phones, full.notes, full.vip, full.favorite, full.groups, full.kind, full.stats], ["Béatrice Côté", [{ email: "bea@exemple.test", label: "work" }], "UQO", "Professeure", [{ number: "+1 819 555-0100", label: "mobile" }], "Rencontrée à Gatineau.", true, false, [g.id], "saved", { sent: 0, received: 0, last_at: null }])107  assert.deepEqual(await admin.call("GET", `/api/next/contacts/${full.id}`), full)108  await rejects(admin.call("POST", "/api/next/contacts", {}), 400, "invalid_request")109  await rejects(admin.call("POST", "/api/next/contacts", { name: "x", emails: [{ email: "pas une adresse" }] }), 400, "invalid_request")110  await rejects(admin.call("POST", "/api/next/contacts", { name: "x", groups: [crypto.randomUUID()] }), 400, "unknown_group")111  await rejects(admin.call("POST", "/api/next/contacts", { name: "Autre", emails: [{ email: "bea@exemple.test" }] }), 409, "email_in_use")112  // modification : seules les clés envoyées changent113  const p = await admin.call("PATCH", `/api/next/contacts/${full.id}`, { favorite: true })114  assert.deepEqual({ ...p, updated_at: 0 }, { ...full, favorite: true, updated_at: 0 })115  const p2 = await admin.call("PATCH", `/api/next/contacts/${full.id}`, { organization: null, emails: [{ email: "bea@exemple.test" }, { email: "bea2@exemple.test", label: "home" }], groups: [] })116  assert.deepEqual([p2.organization, p2.emails, p2.groups, p2.title, p2.vip, p2.favorite], [null, [{ email: "bea@exemple.test", label: null }, { email: "bea2@exemple.test", label: "home" }], [], "Professeure", true, true])117  // une suggestion modifiée par l'utilisateur devient une fiche enregistrée, ses compteurs sont gardés118  const d = await byEmail(admin, D.address)119  const saved = await admin.call("PATCH", `/api/next/contacts/${d.id}`, { name: "Denis D", groups: [g.id] })120  assert.deepEqual([saved.kind, saved.name, saved.stats.received, saved.stats.sent, saved.groups], ["saved", "Denis D", 1, 1, [g.id]])121  // reprendre l'adresse d'une suggestion l'absorbe (compteurs compris) ; celle d'une fiche enregistrée est refusée122  const c = await byEmail(admin, C.address)123  const adopted = await admin.call("POST", "/api/next/contacts", { name: "Camille C", emails: [{ email: C.address }] })124  assert.deepEqual([adopted.kind, adopted.stats.sent, adopted.stats.received], ["saved", 3, 2])125  await rejects(admin.call("GET", `/api/next/contacts/${c.id}`), 404, "not_found")126  await rejects(admin.call("PATCH", `/api/next/contacts/${full.id}`, { emails: [{ email: C.address }] }), 409, "email_in_use")127  assert.equal((await admin.call("GET", `/api/next/contacts/${full.id}`)).emails.length, 2, "le refus n'a rien modifié")128  // groupes129  assert.equal((await admin.call("GET", "/api/next/contact-groups")).data[0].members, 1)130  assert.deepEqual((await contacts(admin, `?group=${g.id}`)).map((x) => x.name), ["Denis D"])131  assert.equal((await admin.call("PATCH", `/api/next/contact-groups/${g.id}`, { name: "Équipe A" })).color, "#00aa00")132  // liste : filtres et pagination sans doublon ni trou133  assert.deepEqual((await contacts(admin, "?favorite=1")).map((x) => x.name), ["Béatrice Côté", "Carl Favori"])134  assert.deepEqual((await contacts(admin, "?kind=suggested")).map((x) => x.name), [])135  assert.deepEqual((await contacts(admin, "?q=uqo")).map((x) => x.name), [], "organisation effacée")136  assert.deepEqual((await contacts(admin, "?q=bea2")).map((x) => x.name), ["Béatrice Côté"])137  const names: string[] = []138  for (let cursor = "", i = 0; i < 10; i++) {139    const page = await admin.call("GET", `/api/next/contacts?limit=2${cursor ? `&cursor=${cursor}` : ""}`)140    names.push(...page.data.map((x: any) => x.name))141    if (!page.next_cursor) break142    assert.equal(page.data.length, 2)143    cursor = page.next_cursor144  }145  assert.deepEqual(names, ["Béatrice Côté", "Camille C", "Carl Favori", "Denis D", "Zoé Ami"])146  await rejects(admin.call("GET", "/api/next/contacts?cursor=abc"), 400, "invalid_cursor")147  // cloisonnement : identifiants d'autrui → 404 partout148  for (const [method, path, body] of [["GET", `/api/next/contacts/${full.id}`], ["PATCH", `/api/next/contacts/${full.id}`, { name: "volé" }], ["DELETE", `/api/next/contacts/${full.id}`], ["GET", `/api/next/contacts/${full.id}/history`],149    ["PATCH", `/api/next/contact-groups/${g.id}`, { name: "x" }], ["DELETE", `/api/next/contact-groups/${g.id}`]] as [string, string, unknown?][]) await rejects(member.call(method, path, body), 404, "not_found")150  await rejects(member.call("POST", "/api/next/contacts", { name: "x", groups: [g.id] }), 400, "unknown_group")151  assert.deepEqual((await member.call("GET", "/api/next/contact-groups")).data, [])152  assert.equal((await member.call("POST", "/api/next/contacts", { name: "Béa du membre", emails: [{ email: "bea@exemple.test" }] })).kind, "saved", "une adresse n'est unique que par utilisateur")153  assert.equal((await admin.call("GET", `/api/next/contacts/${full.id}`)).name, "Béatrice Côté")154  // suppression155  assert.deepEqual(await admin.call("DELETE", `/api/next/contact-groups/${g.id}`), { ok: true })156  assert.deepEqual((await admin.call("GET", `/api/next/contacts/${saved.id}`)).groups, [])157  assert.deepEqual(await admin.call("DELETE", `/api/next/contacts/${full.id}`), { ok: true })158  await rejects(admin.call("GET", `/api/next/contacts/${full.id}`), 404, "not_found")159})160161test("historique : messages échangés avec le contact dans toutes les boîtes, du plus récent au plus ancien", async () => {162  const c = await byEmail(admin, C.address)163  const h = await admin.call("GET", `/api/next/contacts/${c.id}/history`)164  assert.deepEqual(h.data.map((m: any) => [m.subject, m.direction]).sort(), [["Bonjour de C", "received"], ["Encore C", "received"], ["Réponse 1", "sent"], ["Réponse 2", "sent"], ["Réponse 3", "sent"]].sort())165  assert.deepEqual(h.data.map((m: any) => m.received_at), [...h.data.map((m: any) => m.received_at)].sort().reverse())166  assert.ok(h.data.every((m: any) => m.mailbox_id === A.id && m.email_id && m.thread_id))167  assert.ok(Array.isArray(h.reminders))168  const two = await admin.call("GET", `/api/next/contacts/${c.id}/history?limit=2`)169  assert.deepEqual(two.data.map((m: any) => m.email_id), h.data.slice(0, 2).map((m: any) => m.email_id))170  const zoe = await byEmail(admin, `zoe-${RUN}@${STG}`)171  assert.deepEqual(await admin.call("GET", `/api/next/contacts/${zoe.id}/history`), { data: [], reminders: [] })172})173174const VCF = [175  "BEGIN:VCARD", "VERSION:3.0", "FN:Élodie Dupré-Lévesque", "N:Dupré-Lévesque;Élodie;;;", "EMAIL;TYPE=INTERNET,WORK:elodie@exemple.test", "EMAIL;TYPE=HOME:Elodie.Perso@Exemple.test",176  "TEL;TYPE=CELL:+1 819 555-0101", "ORG:Société Générale\\, Division Été;Recherche", "TITLE:Directrice",177  "NOTE:Ligne 1\\nLigne 2 avec une très longue phrase qui sera pliée sur plusieurs lignes par l'export et", "  doit revenir intacte\\; vraiment.", "END:VCARD",178  "BEGIN:VCARD", "VERSION:4.0", "FN:François Noël", "EMAIL;TYPE=work:francois@exemple.test", 'TEL;VALUE=uri;TYPE="voice,cell":tel:+33-1-23-45-67-89', "item1.EMAIL;PREF=1:fn@exemple.test", "PHOTO;ENCODING=b;TYPE=JPEG:AAAA", "END:VCARD",179  "BEGIN:VCARD", "VERSION:2.1", "N;CHARSET=UTF-8;ENCODING=QUOTED-PRINTABLE:Gagn=C3=A9;Ren=C3=A9e", "EMAIL;INTERNET:renee@exemple.test", "NOTE;ENCODING=QUOTED-PRINTABLE:Premi=C3=A8re ligne=0D=0A=", "deuxi=C3=A8me ligne", "END:VCARD",180  "BEGIN:VCARD", "VERSION:3.0", "END:VCARD",181].join("\r\n")182183test("vCard : import 3.0 / 4.0 / 2.1 (accents, lignes pliées, quoted-printable), export, réimport sans doublon", async () => {184  const before = (await contacts(admin, "?limit=200")).length185  const r = await vcf(admin, VCF)186  assert.equal(r.status, 200)187  assert.deepEqual(await r.json(), { total: 4, imported: 3, updated: 0, skipped: 1 })188  const elodie = await byEmail(admin, "elodie@exemple.test")189  assert.deepEqual([elodie.name, elodie.emails, elodie.phones, elodie.organization, elodie.title, elodie.notes, elodie.kind], ["Élodie Dupré-Lévesque", [{ email: "elodie@exemple.test", label: "work" }, { email: "elodie.perso@exemple.test", label: "home" }],190    [{ number: "+1 819 555-0101", label: "mobile" }], "Société Générale, Division Été, Recherche", "Directrice", "Ligne 1\nLigne 2 avec une très longue phrase qui sera pliée sur plusieurs lignes par l'export et doit revenir intacte; vraiment.", "saved"])191  const fr = await byEmail(admin, "fn@exemple.test")192  assert.deepEqual([fr.name, fr.emails.map((e: any) => e.email), fr.phones], ["François Noël", ["francois@exemple.test", "fn@exemple.test"], [{ number: "+33-1-23-45-67-89", label: "mobile" }]])193  const renee = await byEmail(admin, "renee@exemple.test")194  assert.deepEqual([renee.name, renee.notes], ["Renée Gagné", "Première ligne\ndeuxième ligne"])195  // ancien export en Latin-1 : relu correctement196  const latin = await vcf(admin, new Uint8Array(Buffer.from("BEGIN:VCARD\r\nVERSION:3.0\r\nFN:Zoé Latin\r\nEMAIL:zoe.latin@exemple.test\r\nEND:VCARD\r\n", "latin1")), "text/x-vcard")197  assert.deepEqual(await latin.json(), { total: 1, imported: 1, updated: 0, skipped: 0 })198  assert.equal((await byEmail(admin, "zoe.latin@exemple.test")).name, "Zoé Latin")199  // entrées refusées200  assert.equal((await vcf(admin, "pas une vCard")).status, 400)201  assert.equal((await vcf(admin, new Uint8Array(2 * 1024 * 1024 + 8192))).status, 413)202  assert.equal((await vcf(new Client("web"), VCF)).status, 401)203204  // export : vCard 3.0 UTF-8, lignes pliées à 75 octets, relue à l'identique205  const ex = await admin.raw("GET", "/api/next/contacts/export.vcf")206  assert.equal(ex.status, 200)207  assert.match(ex.headers.get("content-type")!, /^text\/vcard/)208  assert.match(ex.headers.get("content-disposition")!, /contacts\.vcf/)209  const text = await ex.text()210  assert.ok(text.split("\r\n").every((l) => Buffer.byteLength(l, "utf8") <= 75), "aucune ligne de plus de 75 octets")211  const saved = await contacts(admin, "?kind=saved&limit=200")212  assert.equal(saved.length, before + 4)213  const parsed = parseVcards(text)214  assert.equal(parsed.skipped, 0)215  const key = (x: { name: string; emails: { email: string }[] }) => `${x.name}|${x.emails.map((e) => e.email).join(",")}`216  assert.deepEqual(parsed.cards.map((c) => ({ name: c.name, emails: c.emails, phones: c.phones, organization: c.organization, title: c.title, notes: c.notes })).sort((a, b) => key(a).localeCompare(key(b))),217    saved.map((c) => ({ name: c.name, emails: c.emails, phones: c.phones, organization: c.organization, title: c.title, notes: c.notes })).sort((a, b) => key(a).localeCompare(key(b))))218  // réimporter son propre export ne crée aucun doublon219  const again = await (await vcf(admin, text)).json()220  assert.deepEqual([again.imported, again.updated, again.skipped], [0, saved.length, 0])221  const strip = (l: any[]) => l.map((c) => ({ ...c, updated_at: null }))222  assert.deepEqual(strip(await contacts(admin, "?kind=saved&limit=200")), strip(saved), "le réimport n'a rien changé")223  assert.equal((await contacts(admin, "?limit=200")).length, before + 4)224  // l'import complète une fiche existante sans rien écraser225  const more = await (await vcf(admin, "BEGIN:VCARD\nVERSION:3.0\nFN:Autre Nom\nEMAIL:renee@exemple.test\nEMAIL:renee.gagne@exemple.test\nTEL:555-0199\nORG:Nouvelle organisation\nEND:VCARD\n")).json()226  assert.deepEqual([more.imported, more.updated], [0, 1])227  const r2 = await byEmail(admin, "renee@exemple.test")228  assert.deepEqual([r2.name, r2.emails.map((e: any) => e.email), r2.phones.map((p: any) => p.number), r2.organization, r2.notes], ["Renée Gagné", ["renee@exemple.test", "renee.gagne@exemple.test"], ["555-0199"], "Nouvelle organisation", "Première ligne\ndeuxième ligne"])229  // l'export du membre ne contient que les siens230  const theirs = await (await member.raw("GET", "/api/next/contacts/export.vcf")).text()231  assert.deepEqual(parseVcards(theirs).cards.map((c) => c.name), ["Béa du membre"])232})233234test("doublons (même adresse normalisée ou même nom) et fusion transactionnelle", async () => {235  const j1 = await admin.call("POST", "/api/next/contacts", { name: "Jean Doe", emails: [{ email: "j.doe+travail@gmail.com" }], phones: [{ number: "514 555-0001" }], notes: "Note 1", organization: "Alpha" })236  const j2 = await admin.call("POST", "/api/next/contacts", { name: "J. Doe", emails: [{ email: "jdoe@googlemail.com" }], phones: [{ number: "(514) 555-0001" }, { number: "514 555-0002" }], notes: "Note 2", title: "Analyste", favorite: true })237  const e1 = await admin.call("POST", "/api/next/contacts", { name: "Élodie  DUPRÉ-lévesque", emails: [{ email: "elodie.autre@exemple.test" }] })238  const dups = (await admin.call("GET", "/api/next/contacts/duplicates")).data as any[]239  const byMail = dups.find((d) => d.reason === "email")240  assert.deepEqual([byMail.key, byMail.contacts.map((c: any) => c.id).sort()], ["jdoe@gmail.com", [j1.id, j2.id].sort()])241  const byName = dups.find((d) => d.reason === "name")242  assert.equal(byName.key, "elodie dupre levesque")243  const elodie = byName.contacts.find((c: any) => c.id !== e1.id)244  assert.equal(byName.contacts.length, 2)245  assert.equal(dups.length, 2)246  assert.deepEqual((await member.call("GET", "/api/next/contacts/duplicates")).data, [])247  // fusion refusée si un identifiant n'appartient pas à l'utilisateur : rien ne bouge248  const foreign = (await contacts(member))[0]249  await rejects(admin.call("POST", "/api/next/contacts/merge", { keep: j1.id, merge: [j2.id, foreign.id] }), 404, "not_found")250  await rejects(member.call("POST", "/api/next/contacts/merge", { keep: j1.id, merge: [j2.id] }), 404, "not_found")251  await rejects(admin.call("POST", "/api/next/contacts/merge", { keep: j1.id, merge: [j1.id] }), 400, "invalid_request")252  assert.equal((await admin.call("GET", `/api/next/contacts/${j2.id}`)).name, "J. Doe")253  // fusion : adresses, téléphones (sans doublon), champs manquants, favori et compteurs rejoignent la fiche gardée254  const c = await byEmail(admin, C.address)255  const m = await admin.call("POST", "/api/next/contacts/merge", { keep: j1.id, merge: [j2.id, c.id] })256  assert.deepEqual([m.id, m.name, m.organization, m.title, m.favorite, m.kind], [j1.id, "Jean Doe", "Alpha", "Analyste", true, "saved"])257  assert.deepEqual(m.emails.map((e: any) => e.email), ["j.doe+travail@gmail.com", "jdoe@googlemail.com", C.address])258  assert.deepEqual(m.phones.map((p: any) => p.number), ["514 555-0001", "514 555-0002"])259  assert.equal(m.notes, "Note 1\n\nNote 2")260  assert.deepEqual([m.stats.sent, m.stats.received], [3, 2])261  await rejects(admin.call("GET", `/api/next/contacts/${j2.id}`), 404, "not_found")262  await rejects(admin.call("GET", `/api/next/contacts/${c.id}`), 404, "not_found")263  assert.equal((await byEmail(admin, C.address)).id, j1.id)264  // la moisson continue sur la fiche fusionnée265  await sendAndWait(kc, { from: C.address, to: [A.address], subject: "Après fusion", text: "x" })266  assert.equal((await waitStats(admin, C.address, (s) => s.received === 3, "réception après fusion")).id, j1.id)267  await admin.call("POST", "/api/next/contacts/merge", { keep: elodie.id, merge: [e1.id] })268  assert.deepEqual((await admin.call("GET", "/api/next/contacts/duplicates")).data, [])269})270
Files main
Menu

Theme