@htilabs/platform-common-models 0.29.0 → 0.32.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -4,6 +4,7 @@
4
4
  * three views, the strict row parse, and the raw-driver reads over an
5
5
  * in-memory double, including the Referrals (magic link) partner rollup.
6
6
  */
7
+ import { inspect } from "node:util";
7
8
  import { beforeEach, describe, expect, it } from "vitest";
8
9
 
9
10
  import preferredContactMethodSot from "../../cvcs/preferredContactMethod.v1.0.0.json" with { type: "json" };
@@ -12,13 +13,17 @@ import {
12
13
  CONTACT_PURPOSES,
13
14
  CONTACT_PURPOSE_CODES,
14
15
  POC_IDENTITY_INDEX_FILTER,
16
+ POC_MAX_CONTACT_ENTRIES,
15
17
  POC_PRIMARY_INDEX_FILTER,
18
+ POC_SUBJECT_TYPES,
16
19
  POC_URGENT_METHODS,
17
20
  POINTS_OF_CONTACT_COLLECTION,
18
21
  PocDetailsSchema,
22
+ PocEmailListSchema,
19
23
  PocInAppSchema,
20
24
  PocOwnerSchema,
21
25
  PocPatchSchema,
26
+ PocPhoneListSchema,
22
27
  PocSeedSchema,
23
28
  PointOfContactShapeError,
24
29
  definedPatch,
@@ -33,9 +38,17 @@ import {
33
38
  pocIdentityKey,
34
39
  pocInitialStatus,
35
40
  pocRuleViolations,
41
+ pocSubjectTypeLabel,
42
+ formatPocPhone,
43
+ pocPhoneDigits,
44
+ preferredContactEntry,
45
+ preferredEmail,
46
+ preferredPhone,
47
+ resolveMagicLinkRecipients,
36
48
  toNetworkView,
37
49
  toOwnerView,
38
50
  toStewardView,
51
+ type PocContactEntry,
39
52
  type PocDbLike,
40
53
  type PocRuleInput,
41
54
  type PointOfContactDoc,
@@ -77,7 +90,11 @@ const db: PocDbLike = {
77
90
  },
78
91
  };
79
92
 
80
- function doc(over: Partial<PointOfContactDoc>): PointOfContactDoc {
93
+ /** A preferred entry; `E(v, false)` is a non-preferred one. */
94
+ const E = (value: string, is_preferred = true): PocContactEntry => ({ value, is_preferred });
95
+
96
+ /** A stored row; `email` is shorthand for a one-entry `emails` (null = none). */
97
+ function doc(over: Partial<PointOfContactDoc> & { email?: string | null }): PointOfContactDoc {
81
98
  const base: PointOfContactDoc = {
82
99
  id: "poc-x",
83
100
  subject_type: "agency",
@@ -87,8 +104,8 @@ function doc(over: Partial<PointOfContactDoc>): PointOfContactDoc {
87
104
  user_id: null,
88
105
  person_id: null,
89
106
  display_name: "Pat Doe",
90
- email: "pat@a.org",
91
- phone: null,
107
+ emails: [E("pat@a.org")],
108
+ phones: [],
92
109
  purposes: [],
93
110
  urgent_methods: [],
94
111
  is_primary: false,
@@ -109,7 +126,9 @@ function doc(over: Partial<PointOfContactDoc>): PointOfContactDoc {
109
126
  updatedBy: "u1",
110
127
  updatedAt: "2026-10-14T00:00:00.000Z",
111
128
  };
112
- const d = { ...base, ...over };
129
+ const { email, ...rest } = over;
130
+ const d: PointOfContactDoc = { ...base, ...rest };
131
+ if (email !== undefined) d.emails = email === null ? [] : [E(email)];
113
132
  return { ...d, identity_key: pocIdentityKey(d) };
114
133
  }
115
134
  const put = (...ds: PointOfContactDoc[]) => rows.push(...ds.map((d) => ({ ...d })));
@@ -180,33 +199,34 @@ describe("schemas", () => {
180
199
  it("lowercases email and a 24-hex seat id, dedupes purposes and urgent methods, refuses a label", () => {
181
200
  const r = PocDetailsSchema.parse({
182
201
  user_id: "0123456789ABCDEF01234567",
183
- email: " Pat@Example.ORG ",
202
+ emails: [{ value: " Pat@Example.ORG " }],
184
203
  purposes: ["TRAINING", "TRAINING"],
185
204
  urgent_methods: [EMAIL, EMAIL],
186
205
  });
187
206
  expect(r).toMatchObject({
188
207
  user_id: "0123456789abcdef01234567",
189
- email: "pat@example.org",
208
+ emails: [E("pat@example.org")],
190
209
  purposes: ["TRAINING"],
191
210
  urgent_methods: [EMAIL],
192
211
  });
193
212
  expect(PocDetailsSchema.parse({ user_id: "u-Slug" }).user_id).toBe("u-Slug");
194
213
  expect(PocDetailsSchema.safeParse({ purposes: ["Referrals (magic link)"] }).success).toBe(false);
195
214
  expect(PocDetailsSchema.safeParse({ urgent_methods: ["EMAIL"] }).success).toBe(false);
196
- expect(PocDetailsSchema.safeParse({ email: "not-an-email" }).success).toBe(false);
215
+ expect(PocDetailsSchema.safeParse({ emails: [{ value: "not-an-email" }] }).success).toBe(false);
197
216
  });
198
217
 
199
218
  it("an in-app add is a named write-in with an email, tagged Referrals by default, nothing the owner sets", () => {
200
- expect(PocInAppSchema.parse({ display_name: "Desk", email: "D@B.org", phone: "555" })).toEqual({
219
+ expect(PocInAppSchema.parse({ display_name: "Desk", emails: [{ value: "D@B.org" }], phones: [{ value: "555" }] })).toEqual({
201
220
  display_name: "Desk",
202
- email: "d@b.org",
203
- phone: "555",
221
+ emails: [E("d@b.org")],
222
+ phones: [E("555")],
204
223
  purposes: [REF],
205
224
  });
206
225
  expect(PocInAppSchema.safeParse({ display_name: "Desk" }).success).toBe(false);
207
- expect(PocInAppSchema.safeParse({ email: "d@b.org" }).success).toBe(false);
208
- for (const key of ["is_primary", "is_confidential", "notes", "user_id", "person_id", "status"]) {
209
- const body = { display_name: "D", email: "d@b.org", [key]: key.startsWith("is_") ? true : "x" };
226
+ expect(PocInAppSchema.safeParse({ display_name: "Desk", emails: [] }).success).toBe(false);
227
+ expect(PocInAppSchema.safeParse({ emails: [{ value: "d@b.org" }] }).success).toBe(false);
228
+ for (const key of ["is_primary", "is_confidential", "notes", "user_id", "person_id", "status", "email", "phone"]) {
229
+ const body = { display_name: "D", emails: [{ value: "d@b.org" }], [key]: key.startsWith("is_") ? true : "x" };
210
230
  expect(PocInAppSchema.safeParse(body).success, key).toBe(false);
211
231
  }
212
232
  });
@@ -216,12 +236,16 @@ describe("schemas", () => {
216
236
  expect(PocPatchSchema.safeParse({ person_id: "p2" }).success).toBe(false);
217
237
  expect(PocPatchSchema.safeParse({}).success).toBe(false);
218
238
  expect(PocPatchSchema.safeParse({ is_confidential: undefined }).success).toBe(false);
219
- const p = PocPatchSchema.parse({ phone: "555", is_confidential: undefined, purposes: undefined });
220
- expect(definedPatch(p)).toEqual({ phone: "555" });
221
- expect(Object.keys(definedPatch(p))).toEqual(["phone"]);
239
+ const p = PocPatchSchema.parse({ notes: "n", is_confidential: undefined, purposes: undefined });
240
+ expect(definedPatch(p)).toEqual({ notes: "n" });
241
+ expect(Object.keys(definedPatch(p))).toEqual(["notes"]);
242
+ expect(PocPatchSchema.safeParse({ phone: "555" }).success).toBe(false);
243
+ expect(definedPatch(PocPatchSchema.parse({ phones: [{ value: " 402 555 0100 " }] }))).toEqual({
244
+ phones: [E("402 555 0100")],
245
+ });
222
246
  });
223
247
 
224
- it("the owner: agency and org subjects name themselves; program, team, site name an agency", () => {
248
+ it("the owner: agency and org subjects name themselves; program, team, location name an agency", () => {
225
249
  const ok = (o: object) => PocOwnerSchema.safeParse(o).success;
226
250
  expect(ok({ subject_type: "agency", subject_id: "a", agency_id: "a", org_id: null })).toBe(true);
227
251
  expect(ok({ subject_type: "agency", subject_id: "b", agency_id: "a", org_id: null })).toBe(false);
@@ -229,10 +253,10 @@ describe("schemas", () => {
229
253
  expect(ok({ subject_type: "org", subject_id: "o", agency_id: "a", org_id: "o" })).toBe(true);
230
254
  expect(ok({ subject_type: "org", subject_id: "x", agency_id: null, org_id: "o" })).toBe(false);
231
255
  expect(ok({ subject_type: "program", subject_id: "p", agency_id: "a", org_id: "o" })).toBe(true);
232
- for (const t of ["program", "team", "site"]) {
256
+ for (const t of ["program", "team", "location"]) {
233
257
  expect(ok({ subject_type: t, subject_id: "p", agency_id: null, org_id: "o" }), t).toBe(false);
234
258
  }
235
- expect(ok({ subject_type: "location", subject_id: "l", agency_id: "a", org_id: null })).toBe(false);
259
+ expect(ok({ subject_type: "location", subject_id: "loc-1", agency_id: "a", org_id: null })).toBe(true);
236
260
  expect(ok({ subject_type: "service", subject_id: "svc-1", agency_id: null, org_id: "o" })).toBe(true);
237
261
  expect(ok({ subject_type: "service", subject_id: "svc-1", agency_id: "a", org_id: null })).toBe(false);
238
262
  });
@@ -248,8 +272,8 @@ describe("pocRuleViolations", () => {
248
272
  user_id: null,
249
273
  person_id: null,
250
274
  display_name: "A",
251
- email: null,
252
- phone: null,
275
+ emails: [],
276
+ phones: [],
253
277
  purposes: [],
254
278
  };
255
279
  const reasons = (o: Partial<PocRuleInput>) =>
@@ -257,12 +281,13 @@ describe("pocRuleViolations", () => {
257
281
 
258
282
  it("a write-in tagged Referrals (magic link) without an email is a violation; with one it is not", () => {
259
283
  expect(reasons({ purposes: [REF] })).toEqual(["referral_contact_needs_email"]);
260
- expect(reasons({ purposes: [REF], email: "a@b.org" })).toEqual([]);
284
+ expect(reasons({ purposes: [REF], emails: [E("a@b.org")] })).toEqual([]);
261
285
  });
262
286
 
263
287
  it("seat XOR person; a seat-linked row stores no reach of its own; a write-in needs a name", () => {
264
288
  expect(reasons({ user_id: "u", person_id: "p", display_name: null })).toContain("user_id_xor_person_id");
265
- expect(reasons({ user_id: "u", email: "a@b.org" })).toEqual(["seat_contact_has_own_reach"]);
289
+ expect(reasons({ user_id: "u", emails: [E("a@b.org")] })).toEqual(["seat_contact_has_own_reach"]);
290
+ expect(reasons({ user_id: "u", phones: [E("555")] })).toEqual(["seat_contact_has_own_reach"]);
266
291
  expect(reasons({ display_name: null })).toEqual(["display_name_required"]);
267
292
  expect(reasons({ user_id: "u", display_name: null, purposes: [REF] })).toEqual([]);
268
293
  });
@@ -272,7 +297,7 @@ describe("pocRuleViolations", () => {
272
297
  });
273
298
 
274
299
  it("the identity key lowercases a seat id", () => {
275
- expect(pocIdentityKey({ user_id: "ABC", person_id: null, display_name: null, email: null })).toBe("seat:abc");
300
+ expect(pocIdentityKey({ user_id: "ABC", person_id: null, display_name: null, emails: [] })).toBe("seat:abc");
276
301
  });
277
302
  });
278
303
 
@@ -378,11 +403,11 @@ describe("reads", () => {
378
403
  await expect(listContactsForSubject(db, { ...team, agency_id: "" })).rejects.toThrow(TypeError);
379
404
  });
380
405
 
381
- it("program, team and site reads require agency_id; service names it (null allowed); agency and org may omit it", async () => {
406
+ it("program, team and location reads require agency_id; service names it (null allowed); agency and org may omit it", async () => {
382
407
  put(
383
408
  doc({ id: "poc-svc", subject_type: "service", subject_id: "svc-1", agency_id: null, org_id: "org-c", display_name: "Svc" }),
384
409
  );
385
- for (const t of ["program", "team", "site"] as const) {
410
+ for (const t of ["program", "team", "location"] as const) {
386
411
  await expect(listContactsForSubject(db, { subject_type: t, subject_id: "x" } as never), t).rejects.toThrow(TypeError);
387
412
  await expect(listOwnerContactsForSubject(db, { subject_type: t, subject_id: "x", agency_id: null } as never), t).rejects.toThrow(TypeError);
388
413
  }
@@ -410,6 +435,14 @@ describe("reads", () => {
410
435
  status: "confirmed",
411
436
  is_confidential: { $ne: true },
412
437
  },
438
+ // pl-iza: the confidential holders' own query, issued after the visible one.
439
+ {
440
+ $or: [{ agency_id: "agency-a" }, { org_id: "org-a" }],
441
+ purposes: REF,
442
+ active: true,
443
+ status: "confirmed",
444
+ is_confidential: true,
445
+ },
413
446
  {
414
447
  subject_type: "program",
415
448
  subject_id: "prog-1",
@@ -472,3 +505,770 @@ describe("reads", () => {
472
505
  expect((await getContact(db, "poc-u"))?.urgent_methods).toEqual([EMAIL, CALL]);
473
506
  });
474
507
  });
508
+
509
+ describe("location subject (pl-f4c): stored `location`, displayed \"Site\"", () => {
510
+ it("stores location, never site; the display word is Site", () => {
511
+ expect(POC_SUBJECT_TYPES).toEqual(["agency", "org", "program", "team", "location", "service"]);
512
+ expect(POC_SUBJECT_TYPES).not.toContain("site");
513
+ expect(pocSubjectTypeLabel("location")).toBe("Site");
514
+ expect(pocSubjectTypeLabel("org")).toBe("Org");
515
+ expect(pocSubjectTypeLabel("service")).toBe("Service listing");
516
+ expect(pocSubjectTypeLabel("bogus")).toBe("bogus");
517
+ expect(pocSubjectTypeLabel("constructor")).toBe("constructor");
518
+ });
519
+
520
+ it("a 0.28.0 `site` owner or stored row is refused (clean cut, no legacy acceptance)", () => {
521
+ expect(PocOwnerSchema.safeParse({ subject_type: "site", subject_id: "s", agency_id: "a", org_id: null }).success).toBe(false);
522
+ expect(() => normalizePointOfContact({ ...doc({}), subject_type: "site" })).toThrow(PointOfContactShapeError);
523
+ expect(normalizePointOfContact({ ...doc({ subject_type: "location", subject_id: "loc-1" }) }).subject_type).toBe("location");
524
+ });
525
+
526
+ it("a location read is keyed with its agency and reads in the location slot of the reading order", async () => {
527
+ put(
528
+ doc({ id: "poc-loc", subject_type: "location", subject_id: "loc-1", display_name: "Front desk" }),
529
+ doc({ id: "poc-loc-b", subject_type: "location", subject_id: "loc-1", agency_id: "agency-b", display_name: "B desk" }),
530
+ );
531
+ const out = await listContactsForSubject(db, { subject_type: "location", subject_id: "loc-1", agency_id: "agency-a" });
532
+ expect(out.map((c) => c.id)).toEqual(["poc-loc"]);
533
+ });
534
+ });
535
+
536
+ describe("emails[] and phones[] (pl-e98)", () => {
537
+ it("an entry is { value, is_preferred }: no per-entry use (CVC-154 is investigative-only)", () => {
538
+ expect(PocEmailListSchema.safeParse([{ value: "a@b.org", use: "x" }]).success).toBe(false);
539
+ expect(PocEmailListSchema.safeParse([{ value: "a@b.org", is_primary: true }]).success).toBe(false);
540
+ expect(PocEmailListSchema.parse([{ value: "a@b.org" }])).toEqual([{ value: "a@b.org", is_preferred: true }]);
541
+ });
542
+
543
+ it("when none is marked preferred the FIRST entry is; a marked entry keeps it", () => {
544
+ expect(PocEmailListSchema.parse([{ value: "a@b.org" }, { value: "c@b.org" }])).toEqual([
545
+ E("a@b.org"),
546
+ E("c@b.org", false),
547
+ ]);
548
+ expect(
549
+ PocEmailListSchema.parse([{ value: "a@b.org", is_preferred: false }, { value: "c@b.org", is_preferred: true }]),
550
+ ).toEqual([E("a@b.org", false), E("c@b.org")]);
551
+ expect(PocEmailListSchema.parse([])).toEqual([]);
552
+ });
553
+
554
+ it("a writer refuses two preferred, a repeated email and a repeated phone line (by digits)", () => {
555
+ const two = [{ value: "a@b.org", is_preferred: true }, { value: "c@b.org", is_preferred: true }];
556
+ expect(PocEmailListSchema.safeParse(two).success).toBe(false);
557
+ expect(PocEmailListSchema.safeParse([{ value: "a@b.org" }, { value: " A@B.org " }]).success).toBe(false);
558
+ expect(PocPhoneListSchema.safeParse([{ value: "+1 (402) 677-3902" }, { value: "402.677.3902" }]).success).toBe(false);
559
+ expect(PocPhoneListSchema.safeParse([{ value: "402-677-3902" }, { value: "402-677-3903" }]).success).toBe(true);
560
+ });
561
+
562
+ it("a phone has at least one digit and is stored as typed, trimmed (the Admin Hub ledger)", () => {
563
+ for (const bad of ["-", "+", "()", "ext. front"]) {
564
+ expect(PocPhoneListSchema.safeParse([{ value: bad }]).success, bad).toBe(false);
565
+ }
566
+ expect(PocPhoneListSchema.parse([{ value: " +1 402.677.3902 " }])).toEqual([E("+1 402.677.3902")]);
567
+ expect(PocPhoneListSchema.parse([{ value: "555-0100" }, { value: "+44 20 7946 0958" }])).toEqual([
568
+ E("555-0100"),
569
+ E("+44 20 7946 0958", false),
570
+ ]);
571
+ });
572
+
573
+ it("an extension makes a distinct line: kept as typed, never folded into the number", () => {
574
+ const both = PocPhoneListSchema.parse([{ value: "402-677-3902 x5" }, { value: "402-677-3902" }]);
575
+ expect(both).toEqual([E("402-677-3902 x5"), E("402-677-3902", false)]);
576
+ expect(pocPhoneDigits("402-677-3902 x5")).not.toBe(pocPhoneDigits("402-677-3902"));
577
+ expect(PocPhoneListSchema.safeParse([{ value: "402-677-3902 x5" }, { value: "(402) 677-3902 ext 5" }]).success).toBe(
578
+ false,
579
+ );
580
+ });
581
+
582
+ it("formatPocPhone (display only) and pocPhoneDigits mirror canon's formatPhone / phoneDigits", () => {
583
+ expect(formatPocPhone("")).toBe("");
584
+ expect(formatPocPhone("x")).toBe("");
585
+ expect(formatPocPhone("55")).toBe("(55");
586
+ expect(formatPocPhone("55501")).toBe("(555) 01");
587
+ expect(formatPocPhone("555-0100")).toBe("(555) 010-0"); // canon draws a 7-digit local number this way
588
+ expect(formatPocPhone("14026773902")).toBe("(402) 677-3902");
589
+ expect(formatPocPhone("442079460958")).toBe("+44 (207) 946-0958");
590
+ expect(pocPhoneDigits("+1 (402) 677-3902")).toBe("4026773902");
591
+ expect(pocPhoneDigits("+44 20 7946 0958")).toBe("442079460958");
592
+ });
593
+
594
+ it("each entry is strict and a list holds at most the cap", () => {
595
+ expect(PocEmailListSchema.safeParse([{ value: "a@b.org", label: "Cell" }]).success).toBe(false);
596
+ expect(PocPhoneListSchema.safeParse([{ value: "" }]).success).toBe(false);
597
+ const many = (n: number) => Array.from({ length: n }, (_, i) => ({ value: `p${i}@b.org` }));
598
+ expect(PocEmailListSchema.safeParse(many(POC_MAX_CONTACT_ENTRIES)).success).toBe(true);
599
+ expect(PocEmailListSchema.safeParse(many(POC_MAX_CONTACT_ENTRIES + 1)).success).toBe(false);
600
+ });
601
+
602
+ it("the writer bodies take the lists, refuse the 0.28.0 single fields, clear with [] and refuse null", () => {
603
+ const r = PocDetailsSchema.parse({
604
+ display_name: "Pat",
605
+ emails: [{ value: "Work@A.org" }, { value: "home@a.org", is_preferred: true }],
606
+ phones: [{ value: "918-555-0100" }],
607
+ });
608
+ expect(r.emails).toEqual([E("work@a.org", false), E("home@a.org")]);
609
+ expect(r.phones).toEqual([E("918-555-0100")]);
610
+ expect(PocDetailsSchema.safeParse({ display_name: "Pat", email: "a@b.org" }).success).toBe(false);
611
+ expect(PocDetailsSchema.safeParse({ display_name: "Pat", phone: "555" }).success).toBe(false);
612
+ expect(PocPatchSchema.parse({ emails: [] })).toEqual({ emails: [] });
613
+ expect(PocPatchSchema.safeParse({ emails: null }).success).toBe(false);
614
+ expect(PocPatchSchema.safeParse({ phones: null }).success).toBe(false);
615
+ expect(PocSeedSchema.safeParse({ id: "poc-a", display_name: "A", emails: [{ value: "a@b.org" }] }).success).toBe(true);
616
+ });
617
+
618
+ it("preferredEmail / preferredPhone read the marked entry, else the first, else null", () => {
619
+ expect(preferredEmail({ emails: [E("a@b.org", false), E("c@b.org")] })).toBe("c@b.org");
620
+ expect(preferredEmail({ emails: [E("a@b.org", false), E("c@b.org", false)] })).toBe("a@b.org");
621
+ expect(preferredEmail({ emails: [] })).toBeNull();
622
+ expect(preferredPhone({ phones: [E("555", false), E("556")] })).toBe("556");
623
+ expect(preferredPhone({ phones: [] })).toBeNull();
624
+ expect(preferredContactEntry(undefined)).toBeNull();
625
+ });
626
+
627
+ it("a stored list is READ leniently: trimmed, lowercased, deduped, exactly one preferred", () => {
628
+ const base = doc({});
629
+ const read = (emails: unknown, phones: unknown = []) =>
630
+ normalizePointOfContact({ ...base, emails, phones });
631
+ expect(read([E(" A@B.org ", false), E("c@b.org", false)]).emails).toEqual([E("a@b.org"), E("c@b.org", false)]);
632
+ expect(read([E("a@b.org", false), E("c@b.org"), E("d@b.org")]).emails).toEqual([
633
+ E("a@b.org", false),
634
+ E("c@b.org"),
635
+ E("d@b.org", false),
636
+ ]);
637
+ expect(read([E("a@b.org", false), E(" A@b.org "), E("", true)]).emails).toEqual([E("a@b.org")]);
638
+ expect(read([], [E("+1 402 677 3902", false), E("(402) 677-3902"), E("-")]).phones).toEqual([E("+1 402 677 3902")]);
639
+ });
640
+
641
+ it("a stored entry with a missing or null is_preferred reads as not preferred (first-entry rule)", () => {
642
+ const base = doc({});
643
+ const read = (emails: unknown) => normalizePointOfContact({ ...base, emails }).emails;
644
+ expect(read([{ value: "a@b.org" }])).toEqual([E("a@b.org")]);
645
+ expect(read([{ value: "a@b.org", is_preferred: null }, { value: "c@b.org", is_preferred: true }])).toEqual([
646
+ E("a@b.org", false),
647
+ E("c@b.org"),
648
+ ]);
649
+ });
650
+
651
+ it("only structurally invalid stored data throws, never a repairable list", () => {
652
+ const base = doc({});
653
+ const broken = [null, "a@b.org", [{ value: 7, is_preferred: true }], [{ value: "a@b.org", is_preferred: "y" }], ["a@b.org"]];
654
+ for (const emails of broken) {
655
+ expect(() => normalizePointOfContact({ ...base, emails }), JSON.stringify(emails)).toThrow(
656
+ PointOfContactShapeError,
657
+ );
658
+ }
659
+ const { emails: _e, phones: _p, ...legacy } = base;
660
+ expect(() => normalizePointOfContact({ ...legacy, email: "a@b.org", phone: null })).toThrow(PointOfContactShapeError);
661
+ });
662
+
663
+ it("a partner rollup survives a row whose stored lists need repair (mixed good + bad rows)", async () => {
664
+ put(doc({ id: "poc-good", display_name: "Good", purposes: [REF], email: "good@a.org" }));
665
+ rows.push(
666
+ { ...doc({ id: "poc-twopref", display_name: "Two", purposes: [REF] }), emails: [E("Two@A.org"), E("second@a.org")] },
667
+ { ...doc({ id: "poc-nopref", display_name: "None", purposes: [REF] }), emails: [E("none@a.org", false)] },
668
+ { ...doc({ id: "poc-dup", display_name: "Dup", purposes: [REF] }), emails: [E("good@a.org", false), E("GOOD@a.org")] },
669
+ );
670
+ const out = await listReferralContactsForPartner(db, { agency_id: "agency-a" }, { resolveSeats });
671
+ expect(out.recipients.map((r) => [r.id, r.email])).toEqual([
672
+ ["poc-dup", "good@a.org"],
673
+ ["poc-nopref", "none@a.org"],
674
+ ["poc-twopref", "two@a.org"],
675
+ ]);
676
+ expect(out.unreachable).toEqual([]);
677
+ });
678
+
679
+ it("the whole-contact rules read the lists: a Referrals write-in needs at least one email", () => {
680
+ const base: PocRuleInput = { user_id: null, person_id: null, display_name: "A", emails: [], phones: [E("555")], purposes: [REF] };
681
+ expect(pocRuleViolations(base).map((v) => v.reason)).toEqual(["referral_contact_needs_email"]);
682
+ expect(pocRuleViolations({ ...base, emails: [E("a@b.org")] })).toEqual([]);
683
+ });
684
+
685
+ it("the write-in identity keys on the PREFERRED email, not the first", () => {
686
+ const c = { user_id: null, person_id: null, display_name: " Pat ", emails: [E("first@a.org", false), E("Main@A.org")] };
687
+ expect(pocIdentityKey(c)).toBe("writein:pat|main@a.org");
688
+ expect(pocIdentityKey({ ...c, emails: [] })).toBe("writein:pat|");
689
+ expect(pocIdentityKey({ ...c, person_id: "P1" })).toBe("person:p1");
690
+ });
691
+
692
+ it("the network view carries copies of the lists and projects email / phone from the preferred entries", () => {
693
+ const d = doc({ emails: [E("first@a.org", false), E("main@a.org")], phones: [E("555-0100"), E("555-0101", false)] });
694
+ const v = toNetworkView(d)!;
695
+ expect(v.emails.map((e) => e.value)).toEqual(["first@a.org", "main@a.org"]);
696
+ expect([v.email, v.phone]).toEqual(["main@a.org", "555-0100"]);
697
+ expect(v.email).toBe(preferredEmail(v));
698
+ expect(v.phone).toBe(preferredPhone(v));
699
+ expect(v.emails).not.toBe(d.emails);
700
+ expect(v.emails[0]).not.toBe(d.emails[0]);
701
+ expect(v.purposes).not.toBe(d.purposes);
702
+ v.emails[0]!.value = "mutated@a.org";
703
+ expect(d.emails[0]!.value).toBe("first@a.org");
704
+ const none = toNetworkView(doc({ email: null }))!;
705
+ expect([none.emails, none.email, none.phones, none.phone]).toEqual([[], null, [], null]);
706
+ });
707
+
708
+ it("a seat-linked view reads the seat's email (trimmed, lowercased) and phone as one preferred entry each", () => {
709
+ const seatRow = doc({ user_id: "u-seat", email: null, display_name: null });
710
+ const v = toNetworkView(seatRow, SEATS.get("u-seat"))!;
711
+ expect(v.emails).toEqual([E("seat@a.org")]);
712
+ expect(v.phones).toEqual([E("555-0100")]);
713
+ expect(toNetworkView(seatRow, { email: " Seat@A.org ", phone: null, name: null })!.email).toBe("seat@a.org");
714
+ const noMail = toNetworkView(seatRow, SEATS.get("u-noemail"))!;
715
+ expect([noMail.emails, noMail.email, noMail.phones]).toEqual([[], null, []]);
716
+ const unresolved = toNetworkView(seatRow)!;
717
+ expect([unresolved.emails, unresolved.email]).toEqual([[], null]);
718
+ });
719
+
720
+ it("the owner and steward views keep the row's own lists and add read-only email / phone projections", () => {
721
+ const seatRow = doc({ user_id: "u-seat", email: null, display_name: null });
722
+ const o = toOwnerView(seatRow, SEATS.get("u-seat"));
723
+ expect([o.emails, o.phones, o.seat?.email, o.email, o.phone]).toEqual([[], [], "Seat@A.org", "seat@a.org", "555-0100"]);
724
+ const w = doc({ emails: [E("x@a.org", false), E("y@a.org")], phones: [E("555")] });
725
+ const s = toStewardView(w);
726
+ expect([s.email, s.phone]).toEqual(["y@a.org", "555"]);
727
+ expect(s.emails).toEqual(w.emails);
728
+ expect(s.emails).not.toBe(w.emails);
729
+ expect(toOwnerView(w).email).toBe("y@a.org");
730
+ });
731
+
732
+ it("seat emails that differ only in case or spacing are one magic-link recipient", async () => {
733
+ put(
734
+ doc({ id: "poc-seat-a", user_id: "u-pad", email: null, display_name: "A", purposes: [REF] }),
735
+ doc({ id: "poc-write", display_name: "B", purposes: [REF], email: "pad@a.org" }),
736
+ );
737
+ const pad = async () => new Map([["u-pad", { email: " PAD@a.org ", phone: null, name: "Pad" }]]);
738
+ const out = await listReferralContactsForPartner(db, { agency_id: "agency-a" }, { resolveSeats: pad });
739
+ expect(out.recipients.map((r) => r.email)).toEqual(["pad@a.org"]);
740
+ });
741
+
742
+ it("a magic link goes to each Referrals contact's PREFERRED email, deduped on it", async () => {
743
+ put(
744
+ doc({ id: "poc-multi", display_name: "Multi", purposes: [REF], emails: [E("cell@a.org", false), E("intake@a.org")] }),
745
+ doc({ id: "poc-dup", display_name: "Dup", purposes: [REF], emails: [E("intake@a.org"), E("other@a.org", false)] }),
746
+ doc({ id: "poc-second", display_name: "Second", purposes: [REF], emails: [E("second@a.org"), E("cell@a.org", false)] }),
747
+ );
748
+ const out = await listReferralContactsForPartner(db, { agency_id: "agency-a" }, { resolveSeats });
749
+ expect(out.recipients.map((r) => [r.id, r.email])).toEqual([
750
+ ["poc-dup", "intake@a.org"],
751
+ ["poc-second", "second@a.org"],
752
+ ]);
753
+ expect(out.recipients.map((r) => r.email)).not.toContain("cell@a.org");
754
+ });
755
+ });
756
+
757
+ describe("listReferralContactsForPartner: the adder's own pending adds (Nate 2026-10-15)", () => {
758
+ const ADVOCATE = "auth0|advocate";
759
+ const OTHER = "auth0|carol";
760
+ const inApp = (over: Partial<PointOfContactDoc> & { email?: string | null }) =>
761
+ doc({
762
+ status: "pending",
763
+ origin: "in_app",
764
+ added_in_app: "thread",
765
+ confirmed_by: null,
766
+ confirmed_at: null,
767
+ createdBy: ADVOCATE,
768
+ purposes: [REF],
769
+ ...over,
770
+ });
771
+
772
+ beforeEach(() => {
773
+ put(
774
+ doc({ id: "poc-listed", purposes: [REF], email: "listed@a.org", display_name: "Listed" }),
775
+ inApp({ id: "poc-mine", email: "mine@a.org", display_name: "Mine" }),
776
+ inApp({ id: "poc-mine-org", subject_type: "org", subject_id: "org-a", agency_id: null, email: "org@a.org", display_name: "Org Mine" }),
777
+ inApp({ id: "poc-carols", email: "carol@a.org", createdBy: OTHER, display_name: "Carol's" }),
778
+ inApp({ id: "poc-mine-conf", email: "conf@a.org", is_confidential: true }),
779
+ inApp({ id: "poc-mine-gone", email: "gone@a.org", active: false }),
780
+ inApp({ id: "poc-mine-untagged", email: "bill@a.org", purposes: ["BILLING"] }),
781
+ inApp({ id: "poc-mine-other-partner", agency_id: "agency-b", subject_id: "agency-b", org_id: "org-b", email: "b@b.org" }),
782
+ inApp({ id: "poc-mine-dup", email: "listed@a.org", display_name: "Listed Again" }),
783
+ doc({ id: "poc-seeded-pending", purposes: [REF], email: "seed@a.org", status: "pending", origin: "steward_seed", createdBy: ADVOCATE }),
784
+ );
785
+ });
786
+
787
+ it("without the option, nothing pending is returned (unchanged)", async () => {
788
+ const r = await listReferralContactsForPartner(db, { agency_id: "agency-a", org_id: "org-a" }, { resolveSeats });
789
+ expect(r.recipients.map((x) => x.id)).toEqual(["poc-listed"]);
790
+ expect(r.recipients[0]).not.toHaveProperty("pending");
791
+ });
792
+
793
+ it("with it, the advocate's own pending in-app adds follow the confirmed ones, marked pending; nobody else's", async () => {
794
+ const r = await listReferralContactsForPartner(
795
+ db,
796
+ { agency_id: "agency-a", org_id: "org-a" },
797
+ { resolveSeats, includeOwnPendingFor: ADVOCATE },
798
+ );
799
+ expect(r.recipients.map((x) => [x.id, x.email, x.pending ?? false])).toEqual([
800
+ ["poc-listed", "listed@a.org", false],
801
+ ["poc-mine", "mine@a.org", true],
802
+ ["poc-mine-org", "org@a.org", true],
803
+ ]);
804
+ // Another advocate's pending add, a confidential, removed, untagged or seeded row,
805
+ // another partner's, and an email a confirmed recipient already has are not returned.
806
+ expect(r.recipients.map((x) => x.id)).not.toContain("poc-carols");
807
+
808
+ const carol = await listReferralContactsForPartner(db, { agency_id: "agency-a" }, { resolveSeats, includeOwnPendingFor: OTHER });
809
+ expect(carol.recipients.map((x) => [x.id, x.pending ?? false])).toEqual([
810
+ ["poc-listed", false],
811
+ ["poc-carols", true],
812
+ ]);
813
+ });
814
+
815
+ it("the pending query is scoped to the sub, in the query itself; an empty sub is refused", async () => {
816
+ const filters: Record<string, unknown>[] = [];
817
+ const recording: PocDbLike = {
818
+ collection: () => ({
819
+ find: (f: Record<string, unknown>) => (filters.push(f), { toArray: async () => [] }),
820
+ findOne: async () => null,
821
+ }),
822
+ };
823
+ await listReferralContactsForPartner(recording, { agency_id: "agency-a" }, { resolveSeats, includeOwnPendingFor: ADVOCATE });
824
+ expect(filters[1]).toEqual({
825
+ $or: [{ agency_id: "agency-a" }],
826
+ purposes: REF,
827
+ active: true,
828
+ status: "pending",
829
+ origin: "in_app",
830
+ is_confidential: { $ne: true },
831
+ createdBy: ADVOCATE,
832
+ });
833
+ await expect(
834
+ listReferralContactsForPartner(db, { agency_id: "agency-a" }, { resolveSeats, includeOwnPendingFor: "" }),
835
+ ).rejects.toThrow(TypeError);
836
+ });
837
+ });
838
+
839
+ describe("confidential Referrals (magic link) holders (pl-iza, CVC-338)", () => {
840
+ const ADVOCATE = "auth0|advocate";
841
+ /** A confidential, confirmed, tagged holder on agency-a. */
842
+ const conf = (over: Partial<PointOfContactDoc> & { email?: string | null }) =>
843
+ doc({ is_confidential: true, purposes: [REF], display_name: "Hidden", ...over });
844
+ const SECRETS = [
845
+ "hidden-agency@a.org",
846
+ "hidden-prog@a.org",
847
+ "hidden-team@a.org",
848
+ "hidden-loc@a.org",
849
+ "hidden-svc@a.org",
850
+ "hidden-org@a.org",
851
+ "seat@a.org",
852
+ ];
853
+ const BOTH = { agency_id: "agency-a", org_id: "org-a" };
854
+
855
+ function putEverySubject() {
856
+ put(
857
+ doc({ id: "poc-visible", purposes: [REF], email: "visible@a.org", display_name: "Visible" }),
858
+ conf({ id: "poc-c-agency", email: "hidden-agency@a.org" }),
859
+ conf({ id: "poc-c-prog", subject_type: "program", subject_id: "prog-1", email: "hidden-prog@a.org" }),
860
+ conf({ id: "poc-c-team", subject_type: "team", subject_id: "intake", email: "hidden-team@a.org" }),
861
+ conf({ id: "poc-c-loc", subject_type: "location", subject_id: "loc-1", email: "hidden-loc@a.org" }),
862
+ conf({ id: "poc-c-svc", subject_type: "service", subject_id: "svc-1", email: "hidden-svc@a.org" }),
863
+ conf({ id: "poc-c-org", subject_type: "org", subject_id: "org-a", agency_id: null, email: "hidden-org@a.org" }),
864
+ conf({ id: "poc-c-seat", user_id: "u-seat", email: null, display_name: null }),
865
+ );
866
+ }
867
+
868
+ /** Confidential holders at these addresses, obtained the only way a caller can: the send read. */
869
+ async function holdersAt(addresses: string[]) {
870
+ rows.length = 0;
871
+ put(...addresses.map((email, i) => conf({ id: `poc-h-${i}`, email, display_name: `H${i}` })));
872
+ const send = await resolveMagicLinkRecipients(db, { agency_id: "agency-a" }, { resolveSeats });
873
+ expect(send.confidential.count).toBe(addresses.length);
874
+ return send.confidential;
875
+ }
876
+
877
+ it("counts distinct confidential holders across agency, program, team, location, service and org subjects, seat-linked included", async () => {
878
+ putEverySubject();
879
+ const both = await listReferralContactsForPartner(db, BOTH, { resolveSeats });
880
+ expect(both.recipients.map((r) => r.id)).toEqual(["poc-visible"]);
881
+ expect(both.confidentialCount).toBe(7);
882
+ expect(both.unreachable).toEqual([]);
883
+ // The diagnostic is the send list's only, never on the UI-facing result.
884
+ expect(both).not.toHaveProperty("confidentialUnreachableCount");
885
+ // Agency-keyed only: the org-only holder (agency_id null) is not on the agency rollup.
886
+ const byAgency = await listReferralContactsForPartner(db, { agency_id: "agency-a" }, { resolveSeats });
887
+ expect(byAgency.confidentialCount).toBe(6);
888
+ const send = await resolveMagicLinkRecipients(db, BOTH, { resolveSeats });
889
+ expect(send.recipients.map((r) => r.id)).toEqual(["poc-visible"]);
890
+ expect(send.confidential.count).toBe(7);
891
+ expect(send.confidentialUnreachableCount).toBe(0);
892
+ const got: string[] = [];
893
+ const r = await send.confidential.deliver(async (to) => void got.push(to));
894
+ // Stored reading order (agency, org, program, team, location, service; the unnamed
895
+ // seat row before "Hidden"), the seat's email lowercased.
896
+ expect(got).toEqual([
897
+ "seat@a.org",
898
+ "hidden-agency@a.org",
899
+ "hidden-org@a.org",
900
+ "hidden-prog@a.org",
901
+ "hidden-team@a.org",
902
+ "hidden-loc@a.org",
903
+ "hidden-svc@a.org",
904
+ ]);
905
+ expect(r).toEqual({ count: 7, delivered: 7, failed: 0, overflow: 0, firstErrorName: null });
906
+ });
907
+
908
+ it("a partner whose only holders are confidential has a holder and can be sent to", async () => {
909
+ put(conf({ id: "poc-only", email: "only@a.org" }));
910
+ const list = await listReferralContactsForPartner(db, { agency_id: "agency-a" }, { resolveSeats });
911
+ expect(list.recipients.length + list.confidentialCount).toBeGreaterThan(0);
912
+ const send = await resolveMagicLinkRecipients(db, { agency_id: "agency-a" }, { resolveSeats });
913
+ expect(send.recipients).toEqual([]);
914
+ expect(send.confidential.count).toBe(1);
915
+ const got: string[] = [];
916
+ expect((await send.confidential.deliver((to) => void got.push(to))).delivered).toBe(1);
917
+ expect(got).toEqual(["only@a.org"]);
918
+ });
919
+
920
+ it("pending, inactive and untagged confidential rows are not counted; unreachable ones are a count, never ids", async () => {
921
+ put(
922
+ conf({ id: "poc-c-pending", email: "p@a.org", status: "pending" }),
923
+ conf({ id: "poc-c-pending-inapp", email: "q@a.org", status: "pending", origin: "in_app", createdBy: ADVOCATE }),
924
+ conf({ id: "poc-c-gone", email: "g@a.org", active: false }),
925
+ conf({ id: "poc-c-untagged", email: "u@a.org", purposes: ["BILLING"] }),
926
+ conf({ id: "poc-c-other-partner", agency_id: "agency-b", subject_id: "agency-b", org_id: "org-b", email: "b@b.org" }),
927
+ conf({ id: "poc-c-nomail", user_id: "u-noemail", email: null, display_name: null }),
928
+ conf({ id: "poc-c-unresolved", user_id: "u-missing", email: null, display_name: null }),
929
+ doc({ id: "poc-v-nomail", user_id: "u-noemail", email: null, display_name: null, purposes: [REF] }),
930
+ );
931
+ const r = await listReferralContactsForPartner(
932
+ db,
933
+ { agency_id: "agency-a" },
934
+ { resolveSeats, includeOwnPendingFor: ADVOCATE },
935
+ );
936
+ expect(r.confidentialCount).toBe(0);
937
+ expect(r.recipients).toEqual([]);
938
+ // `unreachable` is visible-only (as before pl-iza); the confidential ones are a
939
+ // server-side count on the send list only.
940
+ expect(r.unreachable).toEqual(["poc-v-nomail"]);
941
+ expect(JSON.stringify(r)).not.toContain("poc-c-");
942
+ const send = await resolveMagicLinkRecipients(db, { agency_id: "agency-a" }, { resolveSeats });
943
+ expect([send.unreachable, send.confidentialUnreachableCount, send.confidential.count]).toEqual([
944
+ ["poc-v-nomail"],
945
+ 2,
946
+ 0,
947
+ ]);
948
+ let calls = 0;
949
+ expect(await send.confidential.deliver(() => void calls++)).toEqual({
950
+ count: 0,
951
+ delivered: 0,
952
+ failed: 0,
953
+ overflow: 0,
954
+ firstErrorName: null,
955
+ });
956
+ expect(calls).toBe(0);
957
+ });
958
+
959
+ it("a corrupt confidential row is skipped and counted, never thrown or named; visible sends go on", async () => {
960
+ put(
961
+ doc({ id: "poc-visible", purposes: [REF], email: "visible@a.org", display_name: "Visible" }),
962
+ conf({ id: "poc-c-good", email: "good@a.org" }),
963
+ );
964
+ rows.push({ ...conf({ id: "poc-c-corrupt-jane-roe", email: "jane@a.org" }), origin: "bogus" });
965
+ rows.push({ ...conf({ id: "poc-c-no-emails-list" }), emails: "not-a-list" });
966
+ const list = await listReferralContactsForPartner(db, { agency_id: "agency-a" }, { resolveSeats });
967
+ expect(list.recipients.map((r) => r.id)).toEqual(["poc-visible"]);
968
+ expect(list.confidentialCount).toBe(1);
969
+ expect(list.unreachable).toEqual([]);
970
+ const send = await resolveMagicLinkRecipients(db, { agency_id: "agency-a" }, { resolveSeats });
971
+ expect(send.confidentialUnreachableCount).toBe(2);
972
+ const got: string[] = [];
973
+ const sent = await send.confidential.deliver(async (to) => void got.push(to));
974
+ expect(sent).toMatchObject({ delivered: 1 });
975
+ expect(got).toEqual(["good@a.org"]);
976
+ const text = JSON.stringify(list) + JSON.stringify(send) + inspect(send, { depth: null });
977
+ for (const s of ["corrupt", "jane", "no-emails-list"]) expect(text).not.toContain(s);
978
+ // A corrupt VISIBLE row still fails loudly (unchanged): its id is not secret.
979
+ rows.push({ ...doc({ id: "poc-v-bad", purposes: [REF] }), origin: "bogus" });
980
+ await expect(listReferralContactsForPartner(db, { agency_id: "agency-a" }, { resolveSeats })).rejects.toThrow(
981
+ PointOfContactShapeError,
982
+ );
983
+ });
984
+
985
+ it("dedupes among confidential holders ONLY: a visible, pending or typed overlap never moves the count", async () => {
986
+ put(
987
+ doc({ id: "poc-visible", purposes: [REF], email: "shared@a.org", display_name: "Visible" }),
988
+ conf({ id: "poc-c-shared", email: "shared@a.org" }), // a visible row also reaches it: still counted
989
+ conf({ id: "poc-c-one", email: "one@a.org" }),
990
+ conf({ id: "poc-c-one-again", subject_type: "program", subject_id: "prog-1", email: "one@a.org" }),
991
+ conf({ id: "poc-c-probe", email: "probe@a.org" }),
992
+ doc({
993
+ id: "poc-mine",
994
+ purposes: [REF],
995
+ email: "probe@a.org", // the advocate's own pending add of the same address
996
+ display_name: "Mine",
997
+ status: "pending",
998
+ origin: "in_app",
999
+ added_in_app: "thread",
1000
+ confirmed_by: null,
1001
+ confirmed_at: null,
1002
+ createdBy: ADVOCATE,
1003
+ }),
1004
+ );
1005
+ const without = await listReferralContactsForPartner(db, { agency_id: "agency-a" }, { resolveSeats });
1006
+ const withPending = await listReferralContactsForPartner(
1007
+ db,
1008
+ { agency_id: "agency-a" },
1009
+ { resolveSeats, includeOwnPendingFor: ADVOCATE },
1010
+ );
1011
+ expect(without.confidentialCount).toBe(3);
1012
+ // The own-pending add is listed, and the count does NOT drop (no oracle).
1013
+ expect(withPending.recipients.map((r) => [r.id, r.pending ?? false])).toEqual([
1014
+ ["poc-visible", false],
1015
+ ["poc-mine", true],
1016
+ ]);
1017
+ expect(withPending.confidentialCount).toBe(3);
1018
+ // Every overlap is sent twice: once as a visible pick, once to the holder.
1019
+ const send = await resolveMagicLinkRecipients(
1020
+ db,
1021
+ { agency_id: "agency-a" },
1022
+ { resolveSeats, includeOwnPendingFor: ADVOCATE },
1023
+ );
1024
+ const got: string[] = [];
1025
+ const r = await send.confidential.deliver(async (to) => void got.push(to));
1026
+ expect(got).toEqual(["one@a.org", "probe@a.org", "shared@a.org"]);
1027
+ expect(r).toEqual({ count: 3, delivered: 3, failed: 0, overflow: 0, firstErrorName: null });
1028
+ });
1029
+
1030
+ it("the count does not change when a visible confirmed row with a holder's address appears", async () => {
1031
+ put(
1032
+ conf({ id: "poc-c-1", email: "secret@a.org" }),
1033
+ conf({ id: "poc-c-2", email: "other@a.org" }),
1034
+ doc({ id: "poc-v-seat", user_id: "u-pad", email: null, display_name: null, purposes: [REF] }),
1035
+ doc({
1036
+ id: "poc-mine",
1037
+ purposes: [REF],
1038
+ email: "secret@a.org",
1039
+ display_name: "Mine",
1040
+ status: "pending",
1041
+ origin: "in_app",
1042
+ added_in_app: "thread",
1043
+ confirmed_by: null,
1044
+ confirmed_at: null,
1045
+ createdBy: ADVOCATE,
1046
+ }),
1047
+ );
1048
+ let padEmail = "pad@a.org";
1049
+ const seats = async () => new Map([["u-pad", { email: padEmail, phone: null, name: "Pad" }]]);
1050
+ const count = async () =>
1051
+ (await listReferralContactsForPartner(db, { agency_id: "agency-a" }, { resolveSeats: seats })).confidentialCount;
1052
+ expect(await count()).toBe(2);
1053
+ // A steward confirms the advocate's add: it is now a visible confirmed recipient.
1054
+ const mine = rows.find((r) => r.id === "poc-mine")!;
1055
+ Object.assign(mine, { status: "confirmed", confirmed_by: "steward", confirmed_at: "2026-10-16T00:00:00.000Z" });
1056
+ const after = await listReferralContactsForPartner(db, { agency_id: "agency-a" }, { resolveSeats: seats });
1057
+ expect(after.recipients.map((r) => r.email)).toContain("secret@a.org");
1058
+ expect(after.confidentialCount).toBe(2);
1059
+ // A visible seat's email is edited to match the other holder.
1060
+ padEmail = "Other@A.org";
1061
+ expect(await count()).toBe(2);
1062
+ });
1063
+
1064
+ it("a visible or pending row with a malformed confidential flag is skipped and counted, never thrown or named", async () => {
1065
+ put(doc({ id: "poc-visible", purposes: [REF], email: "visible@a.org", display_name: "Visible" }));
1066
+ rows.push(
1067
+ { ...doc({ id: "poc-flag-string-jane", purposes: [REF], email: "jane@a.org" }), is_confidential: "true" },
1068
+ { ...doc({ id: "poc-flag-one-ann", purposes: [REF], email: "ann@a.org" }), is_confidential: 1 },
1069
+ {
1070
+ ...doc({
1071
+ id: "poc-flag-pending-bo",
1072
+ purposes: [REF],
1073
+ email: "bo@a.org",
1074
+ status: "pending",
1075
+ origin: "in_app",
1076
+ added_in_app: "thread",
1077
+ confirmed_by: null,
1078
+ confirmed_at: null,
1079
+ createdBy: ADVOCATE,
1080
+ }),
1081
+ is_confidential: "yes",
1082
+ },
1083
+ );
1084
+ const opts = { resolveSeats, includeOwnPendingFor: ADVOCATE };
1085
+ const list = await listReferralContactsForPartner(db, { agency_id: "agency-a" }, opts);
1086
+ expect(list.recipients.map((r) => r.id)).toEqual(["poc-visible"]);
1087
+ expect([list.confidentialCount, list.unreachable]).toEqual([0, []]);
1088
+ const send = await resolveMagicLinkRecipients(db, { agency_id: "agency-a" }, opts);
1089
+ expect(send.confidentialUnreachableCount).toBe(3);
1090
+ const text = JSON.stringify(list) + JSON.stringify(send) + inspect(send, { depth: null });
1091
+ for (const s of ["jane", "ann", "bo@", "poc-flag"]) expect(text).not.toContain(s);
1092
+ // A corrupt row whose flag is `false` is not confidential: it still fails loudly.
1093
+ rows.push({ ...doc({ id: "poc-v-bad", purposes: [REF] }), origin: "bogus" });
1094
+ await expect(listReferralContactsForPartner(db, { agency_id: "agency-a" }, opts)).rejects.toThrow(
1095
+ PointOfContactShapeError,
1096
+ );
1097
+ const { is_confidential: _flag, ...absent } = doc({ id: "poc-v-noflag", purposes: [REF] });
1098
+ rows.splice(rows.findIndex((r) => r.id === "poc-v-bad"), 1, absent);
1099
+ await expect(listReferralContactsForPartner(db, { agency_id: "agency-a" }, opts)).rejects.toThrow(
1100
+ PointOfContactShapeError,
1101
+ );
1102
+ });
1103
+
1104
+ it("the outcome is identical whether or not an address the sender typed matches a holder (no probe)", async () => {
1105
+ put(
1106
+ doc({ id: "poc-visible", purposes: [REF], email: "visible@a.org", display_name: "Visible" }),
1107
+ conf({ id: "poc-c-1", email: "secret-1@a.org", display_name: "H1" }),
1108
+ conf({ id: "poc-c-2", email: "secret-2@a.org", display_name: "H2" }),
1109
+ conf({ id: "poc-c-3", email: "secret-3@a.org", display_name: "H3" }),
1110
+ );
1111
+ // A caller's whole send: visible and typed addresses (deduped), then the holders.
1112
+ async function sendWithTyped(typed: string) {
1113
+ const list = await resolveMagicLinkRecipients(db, { agency_id: "agency-a" }, { resolveSeats });
1114
+ const mailed: string[] = [];
1115
+ const shown = [...new Set([...list.recipients.map((r) => r.email), typed])];
1116
+ for (const to of shown) mailed.push(to);
1117
+ const outcome = await list.confidential.deliver(async (to) => void mailed.push(to), {
1118
+ capacity: 2,
1119
+ });
1120
+ return { shown, count: list.confidential.count, outcome, mailed };
1121
+ }
1122
+ const miss = await sendWithTyped("someone@else.org");
1123
+ const hit = await sendWithTyped("secret-1@a.org");
1124
+ expect(hit.count).toBe(miss.count);
1125
+ expect(hit.outcome).toEqual(miss.outcome);
1126
+ expect(hit.outcome).toEqual({
1127
+ count: 3,
1128
+ delivered: 2,
1129
+ failed: 0,
1130
+ overflow: 1,
1131
+ firstErrorName: null,
1132
+ });
1133
+ // The matching holder still gets its own link (a duplicate the sender cannot observe).
1134
+ expect(hit.mailed.filter((a) => a === "secret-1@a.org")).toHaveLength(2);
1135
+ });
1136
+
1137
+ it("issues the confidential query separately, after the visible and own-pending ones, and resolves seats once", async () => {
1138
+ const filters: Record<string, unknown>[] = [];
1139
+ const recording: PocDbLike = {
1140
+ collection: () => ({
1141
+ find: (f: Record<string, unknown>) => (filters.push(f), { toArray: async () => [] }),
1142
+ findOne: async () => null,
1143
+ }),
1144
+ };
1145
+ await resolveMagicLinkRecipients(recording, { org_id: "org-a" }, { resolveSeats, includeOwnPendingFor: ADVOCATE });
1146
+ expect(filters).toHaveLength(3);
1147
+ expect(filters[0]).toMatchObject({ is_confidential: { $ne: true }, status: "confirmed" });
1148
+ expect(filters[1]).toMatchObject({ is_confidential: { $ne: true }, status: "pending" });
1149
+ expect(filters[2]).toEqual({
1150
+ $or: [{ org_id: "org-a" }],
1151
+ purposes: REF,
1152
+ active: true,
1153
+ status: "confirmed",
1154
+ is_confidential: true,
1155
+ });
1156
+ await expect(resolveMagicLinkRecipients(db, {}, { resolveSeats })).rejects.toThrow(TypeError);
1157
+
1158
+ put(
1159
+ doc({ id: "poc-v-seat", user_id: "u-seat", email: null, display_name: null, purposes: [REF] }),
1160
+ conf({ id: "poc-c-seat", user_id: "u-pad", email: null, display_name: null }),
1161
+ );
1162
+ const calls: string[][] = [];
1163
+ const counting = async (ids: readonly string[]) => {
1164
+ calls.push([...ids].sort());
1165
+ return resolveSeats(ids);
1166
+ };
1167
+ await listReferralContactsForPartner(db, { agency_id: "agency-a" }, { resolveSeats: counting });
1168
+ expect(calls).toEqual([["u-pad", "u-seat"]]);
1169
+ });
1170
+
1171
+ it("JSON.stringify, util.inspect, String() and structuredClone of a result never carry an address", async () => {
1172
+ putEverySubject();
1173
+ const list = await listReferralContactsForPartner(db, BOTH, { resolveSeats });
1174
+ const send = await resolveMagicLinkRecipients(db, BOTH, { resolveSeats });
1175
+ const renders = [
1176
+ JSON.stringify(list),
1177
+ JSON.stringify(send),
1178
+ inspect(list, { depth: null }),
1179
+ inspect(send, { depth: null }),
1180
+ inspect(send, { depth: null, showHidden: true }),
1181
+ inspect(send.confidential, { customInspect: false, showHidden: true, depth: null }),
1182
+ String(send.confidential),
1183
+ `${send.confidential}`,
1184
+ JSON.stringify(structuredClone(send.confidential)),
1185
+ JSON.stringify(Object.entries(send.confidential)),
1186
+ ];
1187
+ for (const text of renders) {
1188
+ for (const secret of SECRETS) expect(text, text).not.toContain(secret);
1189
+ expect(text, text).not.toContain("poc-c-");
1190
+ }
1191
+ expect(JSON.parse(JSON.stringify(send)).confidential).toEqual({ count: 7 });
1192
+ expect(inspect(send.confidential)).toBe("ConfidentialReferralRecipients(7)");
1193
+ expect(Object.keys(send.confidential)).toEqual(["count"]);
1194
+ expect(Object.isFrozen(send.confidential)).toBe(true);
1195
+ });
1196
+
1197
+ it("an interface only: no constructor or class value reaches a caller", async () => {
1198
+ const mod: Record<string, unknown> = await import("../index.js");
1199
+ expect(mod).not.toHaveProperty("ConfidentialReferralRecipients");
1200
+ expect(typeof mod.resolveMagicLinkRecipients).toBe("function");
1201
+ });
1202
+
1203
+ describe("deliver", () => {
1204
+ const FOUR = ["a@x.org", "b@x.org", "c@x.org", "d@x.org"];
1205
+
1206
+ it("overflow is max(0, count - capacity): the first `capacity` holders are sent", async () => {
1207
+ const got: string[] = [];
1208
+ const holders = await holdersAt(FOUR);
1209
+ expect(await holders.deliver(async (to) => void got.push(to), { capacity: 2 })).toEqual({
1210
+ count: 4,
1211
+ delivered: 2,
1212
+ failed: 0,
1213
+ overflow: 2,
1214
+ firstErrorName: null,
1215
+ });
1216
+ expect(got).toEqual(["a@x.org", "b@x.org"]);
1217
+ const noop = async () => undefined;
1218
+ const none = await holders.deliver(noop, { capacity: 0 });
1219
+ expect(none).toMatchObject({ overflow: 4, delivered: 0 });
1220
+ const all = await holders.deliver(noop, { capacity: 9 });
1221
+ expect(all).toMatchObject({ overflow: 0, delivered: 4 });
1222
+ for (const bad of [-1, 1.5, Number.NaN, Number.POSITIVE_INFINITY]) {
1223
+ const attempt = holders.deliver(async () => undefined, { capacity: bad });
1224
+ await expect(attempt, String(bad)).rejects.toThrow(TypeError);
1225
+ }
1226
+ });
1227
+
1228
+ it("catches every send error and keeps only its name, never the message that echoes the address", async () => {
1229
+ class ProviderRejected extends Error {
1230
+ constructor(to: string) {
1231
+ super(`550 mailbox ${to} rejected`);
1232
+ this.name = "ProviderRejected";
1233
+ }
1234
+ }
1235
+ let n = 0;
1236
+ const r = await (await holdersAt(FOUR)).deliver(async (to) => {
1237
+ n++;
1238
+ if (to === "b@x.org") throw new ProviderRejected(to);
1239
+ if (to === "c@x.org") throw Object.assign(new Error(`bounce ${to}`), { name: `Bounce for ${to}` });
1240
+ });
1241
+ expect(n).toBe(4);
1242
+ expect(r).toEqual({ count: 4, delivered: 2, failed: 2, overflow: 0, firstErrorName: "ProviderRejected" });
1243
+ const text = JSON.stringify(r) + inspect(r);
1244
+ for (const a of FOUR) expect(text).not.toContain(a);
1245
+
1246
+ // A synchronous throw, a name carrying the address and a non-Error rejection all read safely.
1247
+ const one = await holdersAt(["z@x.org"]);
1248
+ const sync = await one.deliver((to) => {
1249
+ throw Object.assign(new Error(to), { name: `Err ${to}` });
1250
+ });
1251
+ expect(sync).toEqual({ count: 1, delivered: 0, failed: 1, overflow: 0, firstErrorName: "Error" });
1252
+ expect((await one.deliver(() => Promise.reject("z@x.org"))).firstErrorName).toBe("Error");
1253
+ });
1254
+
1255
+ it("an error whose name cannot be read (a throwing getter, a revoked proxy) reads Error; deliver never rejects", async () => {
1256
+ const one = await holdersAt(["z@x.org"]);
1257
+ const getter = Object.defineProperty(new Error("x"), "name", {
1258
+ get() {
1259
+ throw new Error("z@x.org");
1260
+ },
1261
+ });
1262
+ await expect(one.deliver(() => Promise.reject(getter))).resolves.toEqual({
1263
+ count: 1,
1264
+ delivered: 0,
1265
+ failed: 1,
1266
+ overflow: 0,
1267
+ firstErrorName: "Error",
1268
+ });
1269
+ const { proxy, revoke } = Proxy.revocable({}, {});
1270
+ revoke();
1271
+ expect((await one.deliver(() => Promise.reject(proxy))).firstErrorName).toBe("Error");
1272
+ });
1273
+ });
1274
+ });