@htilabs/platform-common-models 0.29.0 → 0.30.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.
@@ -12,13 +12,17 @@ import {
12
12
  CONTACT_PURPOSES,
13
13
  CONTACT_PURPOSE_CODES,
14
14
  POC_IDENTITY_INDEX_FILTER,
15
+ POC_MAX_CONTACT_ENTRIES,
15
16
  POC_PRIMARY_INDEX_FILTER,
17
+ POC_SUBJECT_TYPES,
16
18
  POC_URGENT_METHODS,
17
19
  POINTS_OF_CONTACT_COLLECTION,
18
20
  PocDetailsSchema,
21
+ PocEmailListSchema,
19
22
  PocInAppSchema,
20
23
  PocOwnerSchema,
21
24
  PocPatchSchema,
25
+ PocPhoneListSchema,
22
26
  PocSeedSchema,
23
27
  PointOfContactShapeError,
24
28
  definedPatch,
@@ -33,9 +37,16 @@ import {
33
37
  pocIdentityKey,
34
38
  pocInitialStatus,
35
39
  pocRuleViolations,
40
+ pocSubjectTypeLabel,
41
+ formatPocPhone,
42
+ pocPhoneDigits,
43
+ preferredContactEntry,
44
+ preferredEmail,
45
+ preferredPhone,
36
46
  toNetworkView,
37
47
  toOwnerView,
38
48
  toStewardView,
49
+ type PocContactEntry,
39
50
  type PocDbLike,
40
51
  type PocRuleInput,
41
52
  type PointOfContactDoc,
@@ -77,7 +88,11 @@ const db: PocDbLike = {
77
88
  },
78
89
  };
79
90
 
80
- function doc(over: Partial<PointOfContactDoc>): PointOfContactDoc {
91
+ /** A preferred entry; `E(v, false)` is a non-preferred one. */
92
+ const E = (value: string, is_preferred = true): PocContactEntry => ({ value, is_preferred });
93
+
94
+ /** A stored row; `email` is shorthand for a one-entry `emails` (null = none). */
95
+ function doc(over: Partial<PointOfContactDoc> & { email?: string | null }): PointOfContactDoc {
81
96
  const base: PointOfContactDoc = {
82
97
  id: "poc-x",
83
98
  subject_type: "agency",
@@ -87,8 +102,8 @@ function doc(over: Partial<PointOfContactDoc>): PointOfContactDoc {
87
102
  user_id: null,
88
103
  person_id: null,
89
104
  display_name: "Pat Doe",
90
- email: "pat@a.org",
91
- phone: null,
105
+ emails: [E("pat@a.org")],
106
+ phones: [],
92
107
  purposes: [],
93
108
  urgent_methods: [],
94
109
  is_primary: false,
@@ -109,7 +124,9 @@ function doc(over: Partial<PointOfContactDoc>): PointOfContactDoc {
109
124
  updatedBy: "u1",
110
125
  updatedAt: "2026-10-14T00:00:00.000Z",
111
126
  };
112
- const d = { ...base, ...over };
127
+ const { email, ...rest } = over;
128
+ const d: PointOfContactDoc = { ...base, ...rest };
129
+ if (email !== undefined) d.emails = email === null ? [] : [E(email)];
113
130
  return { ...d, identity_key: pocIdentityKey(d) };
114
131
  }
115
132
  const put = (...ds: PointOfContactDoc[]) => rows.push(...ds.map((d) => ({ ...d })));
@@ -180,33 +197,34 @@ describe("schemas", () => {
180
197
  it("lowercases email and a 24-hex seat id, dedupes purposes and urgent methods, refuses a label", () => {
181
198
  const r = PocDetailsSchema.parse({
182
199
  user_id: "0123456789ABCDEF01234567",
183
- email: " Pat@Example.ORG ",
200
+ emails: [{ value: " Pat@Example.ORG " }],
184
201
  purposes: ["TRAINING", "TRAINING"],
185
202
  urgent_methods: [EMAIL, EMAIL],
186
203
  });
187
204
  expect(r).toMatchObject({
188
205
  user_id: "0123456789abcdef01234567",
189
- email: "pat@example.org",
206
+ emails: [E("pat@example.org")],
190
207
  purposes: ["TRAINING"],
191
208
  urgent_methods: [EMAIL],
192
209
  });
193
210
  expect(PocDetailsSchema.parse({ user_id: "u-Slug" }).user_id).toBe("u-Slug");
194
211
  expect(PocDetailsSchema.safeParse({ purposes: ["Referrals (magic link)"] }).success).toBe(false);
195
212
  expect(PocDetailsSchema.safeParse({ urgent_methods: ["EMAIL"] }).success).toBe(false);
196
- expect(PocDetailsSchema.safeParse({ email: "not-an-email" }).success).toBe(false);
213
+ expect(PocDetailsSchema.safeParse({ emails: [{ value: "not-an-email" }] }).success).toBe(false);
197
214
  });
198
215
 
199
216
  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({
217
+ expect(PocInAppSchema.parse({ display_name: "Desk", emails: [{ value: "D@B.org" }], phones: [{ value: "555" }] })).toEqual({
201
218
  display_name: "Desk",
202
- email: "d@b.org",
203
- phone: "555",
219
+ emails: [E("d@b.org")],
220
+ phones: [E("555")],
204
221
  purposes: [REF],
205
222
  });
206
223
  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" };
224
+ expect(PocInAppSchema.safeParse({ display_name: "Desk", emails: [] }).success).toBe(false);
225
+ expect(PocInAppSchema.safeParse({ emails: [{ value: "d@b.org" }] }).success).toBe(false);
226
+ for (const key of ["is_primary", "is_confidential", "notes", "user_id", "person_id", "status", "email", "phone"]) {
227
+ const body = { display_name: "D", emails: [{ value: "d@b.org" }], [key]: key.startsWith("is_") ? true : "x" };
210
228
  expect(PocInAppSchema.safeParse(body).success, key).toBe(false);
211
229
  }
212
230
  });
@@ -216,12 +234,16 @@ describe("schemas", () => {
216
234
  expect(PocPatchSchema.safeParse({ person_id: "p2" }).success).toBe(false);
217
235
  expect(PocPatchSchema.safeParse({}).success).toBe(false);
218
236
  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"]);
237
+ const p = PocPatchSchema.parse({ notes: "n", is_confidential: undefined, purposes: undefined });
238
+ expect(definedPatch(p)).toEqual({ notes: "n" });
239
+ expect(Object.keys(definedPatch(p))).toEqual(["notes"]);
240
+ expect(PocPatchSchema.safeParse({ phone: "555" }).success).toBe(false);
241
+ expect(definedPatch(PocPatchSchema.parse({ phones: [{ value: " 402 555 0100 " }] }))).toEqual({
242
+ phones: [E("402 555 0100")],
243
+ });
222
244
  });
223
245
 
224
- it("the owner: agency and org subjects name themselves; program, team, site name an agency", () => {
246
+ it("the owner: agency and org subjects name themselves; program, team, location name an agency", () => {
225
247
  const ok = (o: object) => PocOwnerSchema.safeParse(o).success;
226
248
  expect(ok({ subject_type: "agency", subject_id: "a", agency_id: "a", org_id: null })).toBe(true);
227
249
  expect(ok({ subject_type: "agency", subject_id: "b", agency_id: "a", org_id: null })).toBe(false);
@@ -229,10 +251,10 @@ describe("schemas", () => {
229
251
  expect(ok({ subject_type: "org", subject_id: "o", agency_id: "a", org_id: "o" })).toBe(true);
230
252
  expect(ok({ subject_type: "org", subject_id: "x", agency_id: null, org_id: "o" })).toBe(false);
231
253
  expect(ok({ subject_type: "program", subject_id: "p", agency_id: "a", org_id: "o" })).toBe(true);
232
- for (const t of ["program", "team", "site"]) {
254
+ for (const t of ["program", "team", "location"]) {
233
255
  expect(ok({ subject_type: t, subject_id: "p", agency_id: null, org_id: "o" }), t).toBe(false);
234
256
  }
235
- expect(ok({ subject_type: "location", subject_id: "l", agency_id: "a", org_id: null })).toBe(false);
257
+ expect(ok({ subject_type: "location", subject_id: "loc-1", agency_id: "a", org_id: null })).toBe(true);
236
258
  expect(ok({ subject_type: "service", subject_id: "svc-1", agency_id: null, org_id: "o" })).toBe(true);
237
259
  expect(ok({ subject_type: "service", subject_id: "svc-1", agency_id: "a", org_id: null })).toBe(false);
238
260
  });
@@ -248,8 +270,8 @@ describe("pocRuleViolations", () => {
248
270
  user_id: null,
249
271
  person_id: null,
250
272
  display_name: "A",
251
- email: null,
252
- phone: null,
273
+ emails: [],
274
+ phones: [],
253
275
  purposes: [],
254
276
  };
255
277
  const reasons = (o: Partial<PocRuleInput>) =>
@@ -257,12 +279,13 @@ describe("pocRuleViolations", () => {
257
279
 
258
280
  it("a write-in tagged Referrals (magic link) without an email is a violation; with one it is not", () => {
259
281
  expect(reasons({ purposes: [REF] })).toEqual(["referral_contact_needs_email"]);
260
- expect(reasons({ purposes: [REF], email: "a@b.org" })).toEqual([]);
282
+ expect(reasons({ purposes: [REF], emails: [E("a@b.org")] })).toEqual([]);
261
283
  });
262
284
 
263
285
  it("seat XOR person; a seat-linked row stores no reach of its own; a write-in needs a name", () => {
264
286
  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"]);
287
+ expect(reasons({ user_id: "u", emails: [E("a@b.org")] })).toEqual(["seat_contact_has_own_reach"]);
288
+ expect(reasons({ user_id: "u", phones: [E("555")] })).toEqual(["seat_contact_has_own_reach"]);
266
289
  expect(reasons({ display_name: null })).toEqual(["display_name_required"]);
267
290
  expect(reasons({ user_id: "u", display_name: null, purposes: [REF] })).toEqual([]);
268
291
  });
@@ -272,7 +295,7 @@ describe("pocRuleViolations", () => {
272
295
  });
273
296
 
274
297
  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");
298
+ expect(pocIdentityKey({ user_id: "ABC", person_id: null, display_name: null, emails: [] })).toBe("seat:abc");
276
299
  });
277
300
  });
278
301
 
@@ -378,11 +401,11 @@ describe("reads", () => {
378
401
  await expect(listContactsForSubject(db, { ...team, agency_id: "" })).rejects.toThrow(TypeError);
379
402
  });
380
403
 
381
- it("program, team and site reads require agency_id; service names it (null allowed); agency and org may omit it", async () => {
404
+ it("program, team and location reads require agency_id; service names it (null allowed); agency and org may omit it", async () => {
382
405
  put(
383
406
  doc({ id: "poc-svc", subject_type: "service", subject_id: "svc-1", agency_id: null, org_id: "org-c", display_name: "Svc" }),
384
407
  );
385
- for (const t of ["program", "team", "site"] as const) {
408
+ for (const t of ["program", "team", "location"] as const) {
386
409
  await expect(listContactsForSubject(db, { subject_type: t, subject_id: "x" } as never), t).rejects.toThrow(TypeError);
387
410
  await expect(listOwnerContactsForSubject(db, { subject_type: t, subject_id: "x", agency_id: null } as never), t).rejects.toThrow(TypeError);
388
411
  }
@@ -472,3 +495,333 @@ describe("reads", () => {
472
495
  expect((await getContact(db, "poc-u"))?.urgent_methods).toEqual([EMAIL, CALL]);
473
496
  });
474
497
  });
498
+
499
+ describe("location subject (pl-f4c): stored `location`, displayed \"Site\"", () => {
500
+ it("stores location, never site; the display word is Site", () => {
501
+ expect(POC_SUBJECT_TYPES).toEqual(["agency", "org", "program", "team", "location", "service"]);
502
+ expect(POC_SUBJECT_TYPES).not.toContain("site");
503
+ expect(pocSubjectTypeLabel("location")).toBe("Site");
504
+ expect(pocSubjectTypeLabel("org")).toBe("Org");
505
+ expect(pocSubjectTypeLabel("service")).toBe("Service listing");
506
+ expect(pocSubjectTypeLabel("bogus")).toBe("bogus");
507
+ expect(pocSubjectTypeLabel("constructor")).toBe("constructor");
508
+ });
509
+
510
+ it("a 0.28.0 `site` owner or stored row is refused (clean cut, no legacy acceptance)", () => {
511
+ expect(PocOwnerSchema.safeParse({ subject_type: "site", subject_id: "s", agency_id: "a", org_id: null }).success).toBe(false);
512
+ expect(() => normalizePointOfContact({ ...doc({}), subject_type: "site" })).toThrow(PointOfContactShapeError);
513
+ expect(normalizePointOfContact({ ...doc({ subject_type: "location", subject_id: "loc-1" }) }).subject_type).toBe("location");
514
+ });
515
+
516
+ it("a location read is keyed with its agency and reads in the location slot of the reading order", async () => {
517
+ put(
518
+ doc({ id: "poc-loc", subject_type: "location", subject_id: "loc-1", display_name: "Front desk" }),
519
+ doc({ id: "poc-loc-b", subject_type: "location", subject_id: "loc-1", agency_id: "agency-b", display_name: "B desk" }),
520
+ );
521
+ const out = await listContactsForSubject(db, { subject_type: "location", subject_id: "loc-1", agency_id: "agency-a" });
522
+ expect(out.map((c) => c.id)).toEqual(["poc-loc"]);
523
+ });
524
+ });
525
+
526
+ describe("emails[] and phones[] (pl-e98)", () => {
527
+ it("an entry is { value, is_preferred }: no per-entry use (CVC-154 is investigative-only)", () => {
528
+ expect(PocEmailListSchema.safeParse([{ value: "a@b.org", use: "x" }]).success).toBe(false);
529
+ expect(PocEmailListSchema.safeParse([{ value: "a@b.org", is_primary: true }]).success).toBe(false);
530
+ expect(PocEmailListSchema.parse([{ value: "a@b.org" }])).toEqual([{ value: "a@b.org", is_preferred: true }]);
531
+ });
532
+
533
+ it("when none is marked preferred the FIRST entry is; a marked entry keeps it", () => {
534
+ expect(PocEmailListSchema.parse([{ value: "a@b.org" }, { value: "c@b.org" }])).toEqual([
535
+ E("a@b.org"),
536
+ E("c@b.org", false),
537
+ ]);
538
+ expect(
539
+ PocEmailListSchema.parse([{ value: "a@b.org", is_preferred: false }, { value: "c@b.org", is_preferred: true }]),
540
+ ).toEqual([E("a@b.org", false), E("c@b.org")]);
541
+ expect(PocEmailListSchema.parse([])).toEqual([]);
542
+ });
543
+
544
+ it("a writer refuses two preferred, a repeated email and a repeated phone line (by digits)", () => {
545
+ const two = [{ value: "a@b.org", is_preferred: true }, { value: "c@b.org", is_preferred: true }];
546
+ expect(PocEmailListSchema.safeParse(two).success).toBe(false);
547
+ expect(PocEmailListSchema.safeParse([{ value: "a@b.org" }, { value: " A@B.org " }]).success).toBe(false);
548
+ expect(PocPhoneListSchema.safeParse([{ value: "+1 (402) 677-3902" }, { value: "402.677.3902" }]).success).toBe(false);
549
+ expect(PocPhoneListSchema.safeParse([{ value: "402-677-3902" }, { value: "402-677-3903" }]).success).toBe(true);
550
+ });
551
+
552
+ it("a phone has at least one digit and is stored as typed, trimmed (the Admin Hub ledger)", () => {
553
+ for (const bad of ["-", "+", "()", "ext. front"]) {
554
+ expect(PocPhoneListSchema.safeParse([{ value: bad }]).success, bad).toBe(false);
555
+ }
556
+ expect(PocPhoneListSchema.parse([{ value: " +1 402.677.3902 " }])).toEqual([E("+1 402.677.3902")]);
557
+ expect(PocPhoneListSchema.parse([{ value: "555-0100" }, { value: "+44 20 7946 0958" }])).toEqual([
558
+ E("555-0100"),
559
+ E("+44 20 7946 0958", false),
560
+ ]);
561
+ });
562
+
563
+ it("an extension makes a distinct line: kept as typed, never folded into the number", () => {
564
+ const both = PocPhoneListSchema.parse([{ value: "402-677-3902 x5" }, { value: "402-677-3902" }]);
565
+ expect(both).toEqual([E("402-677-3902 x5"), E("402-677-3902", false)]);
566
+ expect(pocPhoneDigits("402-677-3902 x5")).not.toBe(pocPhoneDigits("402-677-3902"));
567
+ expect(PocPhoneListSchema.safeParse([{ value: "402-677-3902 x5" }, { value: "(402) 677-3902 ext 5" }]).success).toBe(
568
+ false,
569
+ );
570
+ });
571
+
572
+ it("formatPocPhone (display only) and pocPhoneDigits mirror canon's formatPhone / phoneDigits", () => {
573
+ expect(formatPocPhone("")).toBe("");
574
+ expect(formatPocPhone("x")).toBe("");
575
+ expect(formatPocPhone("55")).toBe("(55");
576
+ expect(formatPocPhone("55501")).toBe("(555) 01");
577
+ expect(formatPocPhone("555-0100")).toBe("(555) 010-0"); // canon draws a 7-digit local number this way
578
+ expect(formatPocPhone("14026773902")).toBe("(402) 677-3902");
579
+ expect(formatPocPhone("442079460958")).toBe("+44 (207) 946-0958");
580
+ expect(pocPhoneDigits("+1 (402) 677-3902")).toBe("4026773902");
581
+ expect(pocPhoneDigits("+44 20 7946 0958")).toBe("442079460958");
582
+ });
583
+
584
+ it("each entry is strict and a list holds at most the cap", () => {
585
+ expect(PocEmailListSchema.safeParse([{ value: "a@b.org", label: "Cell" }]).success).toBe(false);
586
+ expect(PocPhoneListSchema.safeParse([{ value: "" }]).success).toBe(false);
587
+ const many = (n: number) => Array.from({ length: n }, (_, i) => ({ value: `p${i}@b.org` }));
588
+ expect(PocEmailListSchema.safeParse(many(POC_MAX_CONTACT_ENTRIES)).success).toBe(true);
589
+ expect(PocEmailListSchema.safeParse(many(POC_MAX_CONTACT_ENTRIES + 1)).success).toBe(false);
590
+ });
591
+
592
+ it("the writer bodies take the lists, refuse the 0.28.0 single fields, clear with [] and refuse null", () => {
593
+ const r = PocDetailsSchema.parse({
594
+ display_name: "Pat",
595
+ emails: [{ value: "Work@A.org" }, { value: "home@a.org", is_preferred: true }],
596
+ phones: [{ value: "918-555-0100" }],
597
+ });
598
+ expect(r.emails).toEqual([E("work@a.org", false), E("home@a.org")]);
599
+ expect(r.phones).toEqual([E("918-555-0100")]);
600
+ expect(PocDetailsSchema.safeParse({ display_name: "Pat", email: "a@b.org" }).success).toBe(false);
601
+ expect(PocDetailsSchema.safeParse({ display_name: "Pat", phone: "555" }).success).toBe(false);
602
+ expect(PocPatchSchema.parse({ emails: [] })).toEqual({ emails: [] });
603
+ expect(PocPatchSchema.safeParse({ emails: null }).success).toBe(false);
604
+ expect(PocPatchSchema.safeParse({ phones: null }).success).toBe(false);
605
+ expect(PocSeedSchema.safeParse({ id: "poc-a", display_name: "A", emails: [{ value: "a@b.org" }] }).success).toBe(true);
606
+ });
607
+
608
+ it("preferredEmail / preferredPhone read the marked entry, else the first, else null", () => {
609
+ expect(preferredEmail({ emails: [E("a@b.org", false), E("c@b.org")] })).toBe("c@b.org");
610
+ expect(preferredEmail({ emails: [E("a@b.org", false), E("c@b.org", false)] })).toBe("a@b.org");
611
+ expect(preferredEmail({ emails: [] })).toBeNull();
612
+ expect(preferredPhone({ phones: [E("555", false), E("556")] })).toBe("556");
613
+ expect(preferredPhone({ phones: [] })).toBeNull();
614
+ expect(preferredContactEntry(undefined)).toBeNull();
615
+ });
616
+
617
+ it("a stored list is READ leniently: trimmed, lowercased, deduped, exactly one preferred", () => {
618
+ const base = doc({});
619
+ const read = (emails: unknown, phones: unknown = []) =>
620
+ normalizePointOfContact({ ...base, emails, phones });
621
+ expect(read([E(" A@B.org ", false), E("c@b.org", false)]).emails).toEqual([E("a@b.org"), E("c@b.org", false)]);
622
+ expect(read([E("a@b.org", false), E("c@b.org"), E("d@b.org")]).emails).toEqual([
623
+ E("a@b.org", false),
624
+ E("c@b.org"),
625
+ E("d@b.org", false),
626
+ ]);
627
+ expect(read([E("a@b.org", false), E(" A@b.org "), E("", true)]).emails).toEqual([E("a@b.org")]);
628
+ expect(read([], [E("+1 402 677 3902", false), E("(402) 677-3902"), E("-")]).phones).toEqual([E("+1 402 677 3902")]);
629
+ });
630
+
631
+ it("a stored entry with a missing or null is_preferred reads as not preferred (first-entry rule)", () => {
632
+ const base = doc({});
633
+ const read = (emails: unknown) => normalizePointOfContact({ ...base, emails }).emails;
634
+ expect(read([{ value: "a@b.org" }])).toEqual([E("a@b.org")]);
635
+ expect(read([{ value: "a@b.org", is_preferred: null }, { value: "c@b.org", is_preferred: true }])).toEqual([
636
+ E("a@b.org", false),
637
+ E("c@b.org"),
638
+ ]);
639
+ });
640
+
641
+ it("only structurally invalid stored data throws, never a repairable list", () => {
642
+ const base = doc({});
643
+ const broken = [null, "a@b.org", [{ value: 7, is_preferred: true }], [{ value: "a@b.org", is_preferred: "y" }], ["a@b.org"]];
644
+ for (const emails of broken) {
645
+ expect(() => normalizePointOfContact({ ...base, emails }), JSON.stringify(emails)).toThrow(
646
+ PointOfContactShapeError,
647
+ );
648
+ }
649
+ const { emails: _e, phones: _p, ...legacy } = base;
650
+ expect(() => normalizePointOfContact({ ...legacy, email: "a@b.org", phone: null })).toThrow(PointOfContactShapeError);
651
+ });
652
+
653
+ it("a partner rollup survives a row whose stored lists need repair (mixed good + bad rows)", async () => {
654
+ put(doc({ id: "poc-good", display_name: "Good", purposes: [REF], email: "good@a.org" }));
655
+ rows.push(
656
+ { ...doc({ id: "poc-twopref", display_name: "Two", purposes: [REF] }), emails: [E("Two@A.org"), E("second@a.org")] },
657
+ { ...doc({ id: "poc-nopref", display_name: "None", purposes: [REF] }), emails: [E("none@a.org", false)] },
658
+ { ...doc({ id: "poc-dup", display_name: "Dup", purposes: [REF] }), emails: [E("good@a.org", false), E("GOOD@a.org")] },
659
+ );
660
+ const out = await listReferralContactsForPartner(db, { agency_id: "agency-a" }, { resolveSeats });
661
+ expect(out.recipients.map((r) => [r.id, r.email])).toEqual([
662
+ ["poc-dup", "good@a.org"],
663
+ ["poc-nopref", "none@a.org"],
664
+ ["poc-twopref", "two@a.org"],
665
+ ]);
666
+ expect(out.unreachable).toEqual([]);
667
+ });
668
+
669
+ it("the whole-contact rules read the lists: a Referrals write-in needs at least one email", () => {
670
+ const base: PocRuleInput = { user_id: null, person_id: null, display_name: "A", emails: [], phones: [E("555")], purposes: [REF] };
671
+ expect(pocRuleViolations(base).map((v) => v.reason)).toEqual(["referral_contact_needs_email"]);
672
+ expect(pocRuleViolations({ ...base, emails: [E("a@b.org")] })).toEqual([]);
673
+ });
674
+
675
+ it("the write-in identity keys on the PREFERRED email, not the first", () => {
676
+ const c = { user_id: null, person_id: null, display_name: " Pat ", emails: [E("first@a.org", false), E("Main@A.org")] };
677
+ expect(pocIdentityKey(c)).toBe("writein:pat|main@a.org");
678
+ expect(pocIdentityKey({ ...c, emails: [] })).toBe("writein:pat|");
679
+ expect(pocIdentityKey({ ...c, person_id: "P1" })).toBe("person:p1");
680
+ });
681
+
682
+ it("the network view carries copies of the lists and projects email / phone from the preferred entries", () => {
683
+ const d = doc({ emails: [E("first@a.org", false), E("main@a.org")], phones: [E("555-0100"), E("555-0101", false)] });
684
+ const v = toNetworkView(d)!;
685
+ expect(v.emails.map((e) => e.value)).toEqual(["first@a.org", "main@a.org"]);
686
+ expect([v.email, v.phone]).toEqual(["main@a.org", "555-0100"]);
687
+ expect(v.email).toBe(preferredEmail(v));
688
+ expect(v.phone).toBe(preferredPhone(v));
689
+ expect(v.emails).not.toBe(d.emails);
690
+ expect(v.emails[0]).not.toBe(d.emails[0]);
691
+ expect(v.purposes).not.toBe(d.purposes);
692
+ v.emails[0]!.value = "mutated@a.org";
693
+ expect(d.emails[0]!.value).toBe("first@a.org");
694
+ const none = toNetworkView(doc({ email: null }))!;
695
+ expect([none.emails, none.email, none.phones, none.phone]).toEqual([[], null, [], null]);
696
+ });
697
+
698
+ it("a seat-linked view reads the seat's email (trimmed, lowercased) and phone as one preferred entry each", () => {
699
+ const seatRow = doc({ user_id: "u-seat", email: null, display_name: null });
700
+ const v = toNetworkView(seatRow, SEATS.get("u-seat"))!;
701
+ expect(v.emails).toEqual([E("seat@a.org")]);
702
+ expect(v.phones).toEqual([E("555-0100")]);
703
+ expect(toNetworkView(seatRow, { email: " Seat@A.org ", phone: null, name: null })!.email).toBe("seat@a.org");
704
+ const noMail = toNetworkView(seatRow, SEATS.get("u-noemail"))!;
705
+ expect([noMail.emails, noMail.email, noMail.phones]).toEqual([[], null, []]);
706
+ const unresolved = toNetworkView(seatRow)!;
707
+ expect([unresolved.emails, unresolved.email]).toEqual([[], null]);
708
+ });
709
+
710
+ it("the owner and steward views keep the row's own lists and add read-only email / phone projections", () => {
711
+ const seatRow = doc({ user_id: "u-seat", email: null, display_name: null });
712
+ const o = toOwnerView(seatRow, SEATS.get("u-seat"));
713
+ expect([o.emails, o.phones, o.seat?.email, o.email, o.phone]).toEqual([[], [], "Seat@A.org", "seat@a.org", "555-0100"]);
714
+ const w = doc({ emails: [E("x@a.org", false), E("y@a.org")], phones: [E("555")] });
715
+ const s = toStewardView(w);
716
+ expect([s.email, s.phone]).toEqual(["y@a.org", "555"]);
717
+ expect(s.emails).toEqual(w.emails);
718
+ expect(s.emails).not.toBe(w.emails);
719
+ expect(toOwnerView(w).email).toBe("y@a.org");
720
+ });
721
+
722
+ it("seat emails that differ only in case or spacing are one magic-link recipient", async () => {
723
+ put(
724
+ doc({ id: "poc-seat-a", user_id: "u-pad", email: null, display_name: "A", purposes: [REF] }),
725
+ doc({ id: "poc-write", display_name: "B", purposes: [REF], email: "pad@a.org" }),
726
+ );
727
+ const pad = async () => new Map([["u-pad", { email: " PAD@a.org ", phone: null, name: "Pad" }]]);
728
+ const out = await listReferralContactsForPartner(db, { agency_id: "agency-a" }, { resolveSeats: pad });
729
+ expect(out.recipients.map((r) => r.email)).toEqual(["pad@a.org"]);
730
+ });
731
+
732
+ it("a magic link goes to each Referrals contact's PREFERRED email, deduped on it", async () => {
733
+ put(
734
+ doc({ id: "poc-multi", display_name: "Multi", purposes: [REF], emails: [E("cell@a.org", false), E("intake@a.org")] }),
735
+ doc({ id: "poc-dup", display_name: "Dup", purposes: [REF], emails: [E("intake@a.org"), E("other@a.org", false)] }),
736
+ doc({ id: "poc-second", display_name: "Second", purposes: [REF], emails: [E("second@a.org"), E("cell@a.org", false)] }),
737
+ );
738
+ const out = await listReferralContactsForPartner(db, { agency_id: "agency-a" }, { resolveSeats });
739
+ expect(out.recipients.map((r) => [r.id, r.email])).toEqual([
740
+ ["poc-dup", "intake@a.org"],
741
+ ["poc-second", "second@a.org"],
742
+ ]);
743
+ expect(out.recipients.map((r) => r.email)).not.toContain("cell@a.org");
744
+ });
745
+ });
746
+
747
+ describe("listReferralContactsForPartner: the adder's own pending adds (Nate 2026-10-15)", () => {
748
+ const ADVOCATE = "auth0|advocate";
749
+ const OTHER = "auth0|carol";
750
+ const inApp = (over: Partial<PointOfContactDoc> & { email?: string | null }) =>
751
+ doc({
752
+ status: "pending",
753
+ origin: "in_app",
754
+ added_in_app: "thread",
755
+ confirmed_by: null,
756
+ confirmed_at: null,
757
+ createdBy: ADVOCATE,
758
+ purposes: [REF],
759
+ ...over,
760
+ });
761
+
762
+ beforeEach(() => {
763
+ put(
764
+ doc({ id: "poc-listed", purposes: [REF], email: "listed@a.org", display_name: "Listed" }),
765
+ inApp({ id: "poc-mine", email: "mine@a.org", display_name: "Mine" }),
766
+ inApp({ id: "poc-mine-org", subject_type: "org", subject_id: "org-a", agency_id: null, email: "org@a.org", display_name: "Org Mine" }),
767
+ inApp({ id: "poc-carols", email: "carol@a.org", createdBy: OTHER, display_name: "Carol's" }),
768
+ inApp({ id: "poc-mine-conf", email: "conf@a.org", is_confidential: true }),
769
+ inApp({ id: "poc-mine-gone", email: "gone@a.org", active: false }),
770
+ inApp({ id: "poc-mine-untagged", email: "bill@a.org", purposes: ["BILLING"] }),
771
+ inApp({ id: "poc-mine-other-partner", agency_id: "agency-b", subject_id: "agency-b", org_id: "org-b", email: "b@b.org" }),
772
+ inApp({ id: "poc-mine-dup", email: "listed@a.org", display_name: "Listed Again" }),
773
+ doc({ id: "poc-seeded-pending", purposes: [REF], email: "seed@a.org", status: "pending", origin: "steward_seed", createdBy: ADVOCATE }),
774
+ );
775
+ });
776
+
777
+ it("without the option, nothing pending is returned (unchanged)", async () => {
778
+ const r = await listReferralContactsForPartner(db, { agency_id: "agency-a", org_id: "org-a" }, { resolveSeats });
779
+ expect(r.recipients.map((x) => x.id)).toEqual(["poc-listed"]);
780
+ expect(r.recipients[0]).not.toHaveProperty("pending");
781
+ });
782
+
783
+ it("with it, the advocate's own pending in-app adds follow the confirmed ones, marked pending; nobody else's", async () => {
784
+ const r = await listReferralContactsForPartner(
785
+ db,
786
+ { agency_id: "agency-a", org_id: "org-a" },
787
+ { resolveSeats, includeOwnPendingFor: ADVOCATE },
788
+ );
789
+ expect(r.recipients.map((x) => [x.id, x.email, x.pending ?? false])).toEqual([
790
+ ["poc-listed", "listed@a.org", false],
791
+ ["poc-mine", "mine@a.org", true],
792
+ ["poc-mine-org", "org@a.org", true],
793
+ ]);
794
+ // Another advocate's pending add, a confidential, removed, untagged or seeded row,
795
+ // another partner's, and an email a confirmed recipient already has are not returned.
796
+ expect(r.recipients.map((x) => x.id)).not.toContain("poc-carols");
797
+
798
+ const carol = await listReferralContactsForPartner(db, { agency_id: "agency-a" }, { resolveSeats, includeOwnPendingFor: OTHER });
799
+ expect(carol.recipients.map((x) => [x.id, x.pending ?? false])).toEqual([
800
+ ["poc-listed", false],
801
+ ["poc-carols", true],
802
+ ]);
803
+ });
804
+
805
+ it("the pending query is scoped to the sub, in the query itself; an empty sub is refused", async () => {
806
+ const filters: Record<string, unknown>[] = [];
807
+ const recording: PocDbLike = {
808
+ collection: () => ({
809
+ find: (f: Record<string, unknown>) => (filters.push(f), { toArray: async () => [] }),
810
+ findOne: async () => null,
811
+ }),
812
+ };
813
+ await listReferralContactsForPartner(recording, { agency_id: "agency-a" }, { resolveSeats, includeOwnPendingFor: ADVOCATE });
814
+ expect(filters[1]).toEqual({
815
+ $or: [{ agency_id: "agency-a" }],
816
+ purposes: REF,
817
+ active: true,
818
+ status: "pending",
819
+ origin: "in_app",
820
+ is_confidential: { $ne: true },
821
+ createdBy: ADVOCATE,
822
+ });
823
+ await expect(
824
+ listReferralContactsForPartner(db, { agency_id: "agency-a" }, { resolveSeats, includeOwnPendingFor: "" }),
825
+ ).rejects.toThrow(TypeError);
826
+ });
827
+ });