@htilabs/platform-common-models 0.85.0 → 0.87.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.
Files changed (64) hide show
  1. package/README.md +30 -0
  2. package/dist/{index-XWSYon40.d.cts → index-1pWiqEBC.d.cts} +1 -1
  3. package/dist/{index-Bh1zO_Vu.d.ts → index-uz57Fic9.d.ts} +1 -1
  4. package/dist/index.cjs +12 -1
  5. package/dist/index.cjs.map +1 -1
  6. package/dist/index.d.cts +3 -3
  7. package/dist/index.d.ts +3 -3
  8. package/dist/index.js +12 -1
  9. package/dist/index.js.map +1 -1
  10. package/dist/models/index.d.cts +2 -2
  11. package/dist/models/index.d.ts +2 -2
  12. package/dist/org-directory/index.cjs +8 -2
  13. package/dist/org-directory/index.cjs.map +1 -1
  14. package/dist/org-directory/index.d.cts +11 -2
  15. package/dist/org-directory/index.d.ts +11 -2
  16. package/dist/org-directory/index.js +8 -2
  17. package/dist/org-directory/index.js.map +1 -1
  18. package/dist/org-merge/index.cjs +8 -2
  19. package/dist/org-merge/index.cjs.map +1 -1
  20. package/dist/org-merge/index.js +8 -2
  21. package/dist/org-merge/index.js.map +1 -1
  22. package/dist/points-of-contact/index.cjs +229 -24
  23. package/dist/points-of-contact/index.cjs.map +1 -1
  24. package/dist/points-of-contact/index.d.cts +50 -5
  25. package/dist/points-of-contact/index.d.ts +50 -5
  26. package/dist/points-of-contact/index.js +226 -23
  27. package/dist/points-of-contact/index.js.map +1 -1
  28. package/dist/reader-BmhzOis-.d.ts +273 -0
  29. package/dist/reader-DfQtdw6n.d.cts +273 -0
  30. package/dist/schemas/index.cjs +12 -1
  31. package/dist/schemas/index.cjs.map +1 -1
  32. package/dist/schemas/index.d.cts +57 -27
  33. package/dist/schemas/index.d.ts +57 -27
  34. package/dist/schemas/index.js +12 -1
  35. package/dist/schemas/index.js.map +1 -1
  36. package/dist/seat-logs/index.cjs +815 -0
  37. package/dist/seat-logs/index.cjs.map +1 -0
  38. package/dist/seat-logs/index.d.cts +274 -0
  39. package/dist/seat-logs/index.d.ts +274 -0
  40. package/dist/seat-logs/index.js +742 -0
  41. package/dist/seat-logs/index.js.map +1 -0
  42. package/dist/validation/index.d.cts +1 -1
  43. package/dist/validation/index.d.ts +1 -1
  44. package/package.json +6 -1
  45. package/src/orgDirectory/__tests__/programDetails.test.ts +2 -1
  46. package/src/orgDirectory/__tests__/programTeamLink.test.ts +107 -0
  47. package/src/orgDirectory/schemas.ts +8 -1
  48. package/src/pointsOfContact/__tests__/seatContactLog.test.ts +170 -0
  49. package/src/pointsOfContact/readRules.ts +22 -4
  50. package/src/pointsOfContact/reader.ts +95 -1
  51. package/src/pointsOfContact/schemas.ts +4 -3
  52. package/src/schemas/organization-program.ts +25 -2
  53. package/src/seatLogs/__tests__/seatLogs.review.test.ts +222 -0
  54. package/src/seatLogs/__tests__/seatLogs.test.ts +335 -0
  55. package/src/seatLogs/index.ts +15 -0
  56. package/src/seatLogs/log.ts +700 -0
  57. package/src/seatLogs/personId.ts +100 -0
  58. package/src/seatLogs/personSlugWordlists.ts +40 -0
  59. package/src/seatLogs/reader.ts +143 -0
  60. package/src/seatLogs/schemas.ts +118 -0
  61. package/dist/{agency-CnVTwLeV.d.ts → agency-BHv54o79.d.ts} +4 -4
  62. package/dist/{agency-8ufZJJDH.d.cts → agency-Djp57S71.d.cts} +4 -4
  63. package/dist/{cvcEntry-D787utvP.d.cts → cvcEntry-DAuhe0cd.d.cts} +8 -8
  64. package/dist/{cvcEntry-D787utvP.d.ts → cvcEntry-DAuhe0cd.d.ts} +8 -8
@@ -0,0 +1,222 @@
1
+ /**
2
+ * The pre-review fix batch (B3, S1, S2, S3, S4, S5, S6, S7). Each case failed
3
+ * on the branch before the fix.
4
+ */
5
+ import { describe, expect, it } from "vitest";
6
+
7
+ import {
8
+ SeatLogRefusal,
9
+ addSeatContact,
10
+ addSeatName,
11
+ correctSeatContact,
12
+ correctSeatName,
13
+ liveSeatNames,
14
+ isPersonId,
15
+ mintPersonId,
16
+ readSeatContactLogs,
17
+ retireSeatName,
18
+ seatEmailProjection,
19
+ setPreferredSeatContact,
20
+ setSeatDisplayName,
21
+ type SeatContactEntry,
22
+ type SeatLogSubject,
23
+ type SeatNameEntry,
24
+ } from "../index.js";
25
+
26
+ const S: SeatLogSubject = { subject_type: "user", subject_id: "u1" };
27
+ let n = 0;
28
+ const ctx = (extra: Record<string, unknown> = {}) => ({
29
+ actor: "a",
30
+ at: "2026-11-16T15:00:00.000Z",
31
+ mintId: (k: "name" | "contact") => `${k}-${++n}`,
32
+ ...extra,
33
+ });
34
+ const later = (extra: Record<string, unknown> = {}) => ({ ...ctx(extra), at: "2026-12-01T09:00:00.000Z" });
35
+ const acts = (e: { events?: { act: string }[] }) => (e.events ?? []).map((x) => x.act);
36
+
37
+ /** Ava (display) + Avie, then Avie retired. */
38
+ function namesWithRetired(): { es: SeatNameEntry[]; ava: string; avie: string } {
39
+ const es0 = addSeatName([], S, { raw: "Avie", name_type: "alias" }, ctx({ flatName: "Ava" })).entries;
40
+ const ava = es0.find((e) => e.raw === "Ava")!.entry_id;
41
+ const avie = es0.find((e) => e.raw === "Avie")!.entry_id;
42
+ const es = retireSeatName(es0, S, avie, ctx()).entries;
43
+ return { es, ava, avie };
44
+ }
45
+
46
+ describe("B3: the default entry-id minter", () => {
47
+ it("never collides seeding and adding on a seat with no name log (many iterations)", () => {
48
+ const seen = new Set<string>();
49
+ for (let i = 0; i < 5000; i++) {
50
+ const r = addSeatName([], S, { raw: "B", name_type: "alias" }, { actor: "a", flatName: "A" });
51
+ expect(r.inserted).toHaveLength(2);
52
+ for (const e of r.inserted) {
53
+ expect(e.entry_id.startsWith("nm-u1-rt")).toBe(true);
54
+ expect(seen.has(e.entry_id)).toBe(false);
55
+ seen.add(e.entry_id);
56
+ }
57
+ }
58
+ });
59
+
60
+ it("re-mints when an injected minter returns an id already in the log", () => {
61
+ const ids = ["dup", "dup", "fresh"];
62
+ let i = 0;
63
+ const r = addSeatName([], S, { raw: "B", name_type: "alias" },
64
+ { actor: "a", flatName: "A", mintId: () => ids[i++] });
65
+ expect(r.inserted.map((e) => e.entry_id)).toEqual(["dup", "fresh"]);
66
+ });
67
+ });
68
+
69
+ describe("S1: acts on a retired entry are refused and change nothing", () => {
70
+ const refusedUnchanged = (fn: () => unknown) => {
71
+ expect(fn).toThrow(SeatLogRefusal);
72
+ try { fn(); } catch (e) { expect((e as SeatLogRefusal).code).toBe("entry_not_live"); }
73
+ };
74
+
75
+ it("starring, retiring again and correcting a retired name", () => {
76
+ const { es, avie } = namesWithRetired();
77
+ const snapshot = JSON.stringify(es);
78
+ refusedUnchanged(() => setSeatDisplayName(es, S, avie, ctx()));
79
+ refusedUnchanged(() => retireSeatName(es, S, avie, later()));
80
+ refusedUnchanged(() => correctSeatName(es, S, avie, "Avy", ctx()));
81
+ expect(JSON.stringify(es)).toBe(snapshot);
82
+ expect(liveSeatNames(es).filter((e) => e.is_display).map((e) => e.raw)).toEqual(["Ava"]);
83
+ });
84
+
85
+ it("preferring and correcting a retired email", () => {
86
+ let es: SeatContactEntry[] = addSeatContact([], S, { contact_type: "email", value: "a@x.org" }, ctx()).entries;
87
+ es = addSeatContact(es, S, { contact_type: "email", value: "b@x.org" }, ctx()).entries;
88
+ const b = es.find((e) => e.value === "b@x.org")!.entry_id;
89
+ es = correctSeatContact(es, S, b, "c@x.org", ctx()).entries; // b retired
90
+ refusedUnchanged(() => setPreferredSeatContact(es, S, b, ctx()));
91
+ refusedUnchanged(() => correctSeatContact(es, S, b, "d@x.org", ctx()));
92
+ expect(seatEmailProjection(es)).toBe("a@x.org");
93
+ });
94
+ });
95
+
96
+ describe("S2: correcting a name to the same text", () => {
97
+ it("is a no-op on a logged name", () => {
98
+ const es = addSeatName([], S, { raw: "A", name_type: "legal" }, ctx()).entries;
99
+ const r = correctSeatName(es, S, es[0].entry_id, " A ", ctx());
100
+ expect([r.inserted, r.updated]).toEqual([[], []]);
101
+ });
102
+
103
+ it("is a no-op on the __flat__ row (nothing is seeded)", () => {
104
+ const r = correctSeatName([], S, "__flat__", "A", ctx({ flatName: "A" }));
105
+ expect(r.entries).toEqual([]);
106
+ });
107
+ });
108
+
109
+ describe("S7: events are stamped as the prototype store stamps them", () => {
110
+ it("an archived target reads cascade, archive", () => {
111
+ const { es, avie } = namesWithRetired();
112
+ expect(acts(es.find((e) => e.entry_id === avie)!)).toEqual(["add", "cascade", "archive"]);
113
+ });
114
+
115
+ it("a correction of the display name: the new row and the old row", () => {
116
+ const es0 = addSeatName([], S, { raw: "A", name_type: "legal" }, ctx()).entries;
117
+ const r = correctSeatName(es0, S, es0[0].entry_id, "B", ctx());
118
+ const added = r.inserted[0];
119
+ const old = r.updated[0];
120
+ expect(acts(added)).toEqual(["add", "cascade", "set_display", "cascade", "set_preferred"]);
121
+ // cleared by set_display, cleared by set_preferred, then dated by archive
122
+ expect(acts(old)).toEqual(["add", "cascade", "cascade", "cascade", "archive"]);
123
+ });
124
+
125
+ it("an add that takes the preferred mark leaves its own events at add", () => {
126
+ const r = addSeatContact([], S, { contact_type: "phone", value: "4026773902" }, ctx());
127
+ expect(acts(r.inserted[0])).toEqual(["add"]);
128
+ });
129
+ });
130
+
131
+ describe("S6: mintPersonId", () => {
132
+ const words = { first: ["a", "b"], second: ["x", "y"] };
133
+
134
+ it("clamps an out-of-range random draw", () => {
135
+ expect(mintPersonId(words, [], () => 1)).toBe("per-b-y");
136
+ expect(mintPersonId(words, [], () => -0.5)).toBe("per-a-x");
137
+ expect(mintPersonId(words, [], () => Number.NaN)).toBe("per-a-x");
138
+ });
139
+
140
+ it("finds the last free pair by scanning after the random draws", () => {
141
+ const all = ["per-a-x", "per-a-y", "per-b-x", "per-b-y"];
142
+ expect(mintPersonId(words, all.slice(0, 3), () => 0)).toBe("per-b-y");
143
+ });
144
+
145
+ it("a full pair pool mints a numeric suffix (the records generator's rule), unique vs taken", () => {
146
+ const all = ["per-a-x", "per-a-y", "per-b-x", "per-b-y"];
147
+ const id = mintPersonId(words, all)!;
148
+ expect(id).toMatch(/^per-[ab]-[xy]-\d{1,3}$/);
149
+ expect(all).not.toContain(id);
150
+ // random() = 0 always draws per-a-x-0: taken too, so the scan takes the next free one.
151
+ expect(mintPersonId(words, [...all, "per-a-x-0"], () => 0)).toBe("per-a-y-0");
152
+ // every pair at every suffix 0-999 taken: the scan goes past 999 and still ends.
153
+ const huge: string[] = [...all];
154
+ for (const p of all) for (let i = 0; i < 1000; i++) huge.push(`${p}-${i}`);
155
+ expect(mintPersonId(words, huge, () => 0)).toBe("per-a-x-1000");
156
+ });
157
+
158
+ it("null only when there are no wordlists", () => {
159
+ expect(mintPersonId(null, [])).toBeNull();
160
+ expect(mintPersonId({ first: ["a"], second: [] })).toBeNull();
161
+ });
162
+
163
+ it("the id pattern accepts both forms", () => {
164
+ expect(isPersonId("per-amber-beacon")).toBe(true);
165
+ expect(isPersonId("per-amber-beacon-42")).toBe(true);
166
+ expect(isPersonId("per-amber-beacon-")).toBe(false);
167
+ expect(isPersonId("per-amber")).toBe(false);
168
+ expect(isPersonId("per-Amber-beacon")).toBe(false);
169
+ });
170
+ });
171
+
172
+ describe("S3 + S4 + S5: reading a log", () => {
173
+ const row = (subject_id: string, entry_id: string, value: string): Record<string, unknown> => ({
174
+ entry_id, subject_id, subject_type: "user", contact_type: "email", value, use: "",
175
+ is_preferred: false, safety_status: "", period_start: "", period_end: "",
176
+ source: "admin_hub", method: "direct_entry", notes: "",
177
+ });
178
+ const dbOf = (rows: Record<string, unknown>[]) => {
179
+ const asked: unknown[] = [];
180
+ return {
181
+ asked,
182
+ db: {
183
+ collection: () => ({
184
+ find: (f: Record<string, unknown>) => {
185
+ asked.push(f.subject_id);
186
+ const ids = (f.subject_id as { $in: string[] }).$in;
187
+ const hit = rows.filter((r) => ids.includes(r.subject_id as string));
188
+ return { toArray: async () => hit };
189
+ },
190
+ }),
191
+ },
192
+ };
193
+ };
194
+ const HEX = "0123456789abcdef01234567";
195
+
196
+ it("matches a seat id asked upper-case to its log stored lower-case, keyed as asked", async () => {
197
+ const { db } = dbOf([row(HEX, "ci-1", "a@x.org")]);
198
+ const m = await readSeatContactLogs(db, [HEX.toUpperCase()]);
199
+ expect(m.get(HEX.toUpperCase())?.map((e) => e.value)).toEqual(["a@x.org"]);
200
+ });
201
+
202
+ it("lists a subject's entries in entry_id order", async () => {
203
+ const { db } = dbOf([
204
+ row("u1", "ci-c", "c@x.org"), row("u1", "ci-a", "a@x.org"), row("u1", "ci-b", "b@x.org"),
205
+ ]);
206
+ const m = await readSeatContactLogs(db, ["u1"]);
207
+ expect(m.get("u1")?.map((e) => e.entry_id)).toEqual(["ci-a", "ci-b", "ci-c"]);
208
+ });
209
+
210
+ it("skips a malformed row when asked to, keeping the subject's good rows", async () => {
211
+ const bad = { ...row("u1", "ci-bad", "z@x.org"), notes: undefined };
212
+ const { db } = dbOf([row("u1", "ci-a", "a@x.org"), bad, row("u2", "ci-b", "b@x.org")]);
213
+ const seen: string[] = [];
214
+ const m = await readSeatContactLogs(db, ["u1", "u2"], "user", {
215
+ invalid: "skip", onInvalidRow: (e) => seen.push(e.entryId ?? ""),
216
+ });
217
+ expect(m.get("u1")?.map((e) => e.entry_id)).toEqual(["ci-a"]);
218
+ expect(m.get("u2")?.map((e) => e.entry_id)).toEqual(["ci-b"]);
219
+ expect(seen).toEqual(["ci-bad"]);
220
+ await expect(readSeatContactLogs(db, ["u1"])).rejects.toThrow("ci-bad");
221
+ });
222
+ });
@@ -0,0 +1,335 @@
1
+ import { describe, expect, it } from "vitest";
2
+
3
+ import {
4
+ FLAT_NAME_ENTRY_ID,
5
+ SeatContactEntrySchema,
6
+ SeatLogRefusal,
7
+ SeatNameEntrySchema,
8
+ addSeatContact,
9
+ addSeatName,
10
+ canRetireSeatContact,
11
+ canonSeatContactValue,
12
+ correctSeatContact,
13
+ correctSeatName,
14
+ formatSeatPhone,
15
+ isPersonId,
16
+ liveSeatContacts,
17
+ liveSeatNames,
18
+ mintNewPersonId,
19
+ mintPersonId,
20
+ PERSON_SLUG_FIRST,
21
+ PERSON_SLUG_SECOND,
22
+ PERSON_SLUG_WORDLISTS,
23
+ pastSeatNames,
24
+ readSeatContactLogs,
25
+ retireSeatContact,
26
+ retireSeatName,
27
+ seatContactKey,
28
+ seatEmailProjection,
29
+ seatEmailRefusal,
30
+ seatNameProjection,
31
+ seatNameRows,
32
+ seatPhoneRefusal,
33
+ setPreferredSeatContact,
34
+ setSeatDisplayName,
35
+ type SeatContactEntry,
36
+ type SeatLogContext,
37
+ type SeatLogSubject,
38
+ type SeatNameEntry,
39
+ } from "../index.js";
40
+
41
+ const SUBJECT: SeatLogSubject = { subject_type: "user", subject_id: "u1" };
42
+
43
+ let n = 0;
44
+ function ctx(extra: Record<string, unknown> = {}): SeatLogContext & Record<string, unknown> {
45
+ return {
46
+ actor: "u-admin",
47
+ at: "2026-11-16T15:00:00.000Z",
48
+ mintId: (kind) => `${kind === "name" ? "nm" : "ci"}-${++n}`,
49
+ ...extra,
50
+ };
51
+ }
52
+
53
+ const live = <E extends { period_end: string }>(es: E[]) => es.filter((e) => !e.period_end);
54
+
55
+ describe("name log", () => {
56
+ it("draws the flat name as a __flat__ display row and writes nothing for it", () => {
57
+ expect(seatNameRows([], "Ava Doe")).toEqual([
58
+ { entry_id: FLAT_NAME_ENTRY_ID, raw: "Ava Doe", name_type: "legal", is_display: true },
59
+ ]);
60
+ expect(seatNameRows([], " ")).toEqual([]);
61
+ });
62
+
63
+ it("the first real act seeds the log from the flat name, then adds an alias", () => {
64
+ const r = addSeatName([], SUBJECT, { raw: "Avie", name_type: "alias" }, ctx({ flatName: "Ava Doe" }));
65
+ expect(r.inserted.map((e) => [e.raw, e.name_type, e.is_display, e.is_preferred])).toEqual([
66
+ ["Ava Doe", "legal", true, true],
67
+ ["Avie", "alias", false, false],
68
+ ]);
69
+ expect(r.updated).toEqual([]);
70
+ expect(seatNameProjection(r.entries)).toBe("Ava Doe");
71
+ for (const e of r.entries) {
72
+ expect(SeatNameEntrySchema.parse(e)).toBeTruthy();
73
+ expect(e).toMatchObject({
74
+ subject_type: "user", subject_id: "u1", source: "admin_hub", method: "direct_entry",
75
+ period_start: "", period_end: "", notes: "",
76
+ });
77
+ expect(e.events?.[0]).toEqual({ act: "add", at: "2026-11-16T15:00:00.000Z", actor: "u-admin" });
78
+ }
79
+ });
80
+
81
+ it("the first name on an empty log with no flat name becomes the display name", () => {
82
+ const r = addSeatName([], SUBJECT, { raw: "Bo", name_type: "legal" }, ctx());
83
+ expect(r.inserted[0]).toMatchObject({ raw: "Bo", is_display: true, is_preferred: true });
84
+ });
85
+
86
+ it("adding a name already live is a no-op; a blank name is refused", () => {
87
+ const seeded = addSeatName([], SUBJECT, { raw: "Bo", name_type: "legal" }, ctx()).entries;
88
+ const r = addSeatName(seeded, SUBJECT, { raw: "Bo", name_type: "alias" }, ctx());
89
+ expect(r.inserted).toEqual([]);
90
+ expect(() => addSeatName([], SUBJECT, { raw: " ", name_type: "alias" }, ctx()))
91
+ .toThrow("A member keeps a name — the directory row can't go blank.");
92
+ });
93
+
94
+ it("☆ display moves both marks and keeps one display per subject", () => {
95
+ const start = addSeatName([], SUBJECT, { raw: "Avie", name_type: "alias" }, ctx({ flatName: "Ava" })).entries;
96
+ const avie = start.find((e) => e.raw === "Avie")!;
97
+ const r = setSeatDisplayName(start, SUBJECT, avie.entry_id, ctx());
98
+ expect(live(r.entries).filter((e) => e.is_display).map((e) => e.raw)).toEqual(["Avie"]);
99
+ expect(live(r.entries).filter((e) => e.is_preferred).map((e) => e.raw)).toEqual(["Avie"]);
100
+ expect(seatNameProjection(r.entries)).toBe("Avie");
101
+ const ava = r.updated.find((e) => e.raw === "Ava")!;
102
+ expect(ava.events?.at(-1)?.act).toBe("cascade");
103
+ expect(r.updated.find((e) => e.raw === "Avie")!.events?.map((e) => e.act))
104
+ .toEqual(["add", "cascade", "set_display", "cascade", "set_preferred"]);
105
+ });
106
+
107
+ it("correcting the __flat__ row seeds, inserts the corrected display name and archives the old", () => {
108
+ const r = correctSeatName([], SUBJECT, FLAT_NAME_ENTRY_ID, "Ava Doé", ctx({ flatName: "Ava Doe" }));
109
+ expect(liveSeatNames(r.entries).map((e) => [e.raw, e.is_display, e.notes])).toEqual([
110
+ ["Ava Doé", true, "Corrects “Ava Doe”"],
111
+ ]);
112
+ expect(pastSeatNames(r.entries).map((e) => [e.raw, e.period_end, e.is_display])).toEqual([
113
+ ["Ava Doe", "2026-11-16", false],
114
+ ]);
115
+ expect(seatNameProjection(r.entries)).toBe("Ava Doé");
116
+ });
117
+
118
+ it("correcting a non-display name carries no mark; never edits in place", () => {
119
+ const start = addSeatName([], SUBJECT, { raw: "Avie", name_type: "alias" }, ctx({ flatName: "Ava" })).entries;
120
+ const avie = start.find((e) => e.raw === "Avie")!;
121
+ const r = correctSeatName(start, SUBJECT, avie.entry_id, "Avy", ctx());
122
+ expect(r.inserted).toHaveLength(1);
123
+ expect(r.inserted[0]).toMatchObject({ raw: "Avy", name_type: "alias", is_display: false });
124
+ expect(r.updated.map((e) => [e.entry_id, e.raw, e.period_end])).toEqual([[avie.entry_id, "Avie", "2026-11-16"]]);
125
+ expect(start.find((e) => e.entry_id === avie.entry_id)!.period_end).toBe(""); // input untouched
126
+ });
127
+
128
+ it("correcting INTO a live name hands it the display mark and archives the wrong one", () => {
129
+ const start = addSeatName([], SUBJECT, { raw: "Avie", name_type: "alias" }, ctx({ flatName: "Ava" })).entries;
130
+ const ava = start.find((e) => e.raw === "Ava")!;
131
+ const r = correctSeatName(start, SUBJECT, ava.entry_id, "Avie", ctx());
132
+ expect(r.inserted).toEqual([]);
133
+ expect(liveSeatNames(r.entries).map((e) => [e.raw, e.is_display])).toEqual([["Avie", true]]);
134
+ });
135
+
136
+ it("the display name can't be retired; another can, and stays in the log", () => {
137
+ const start = addSeatName([], SUBJECT, { raw: "Avie", name_type: "alias" }, ctx({ flatName: "Ava" })).entries;
138
+ const ava = start.find((e) => e.raw === "Ava")!;
139
+ expect(() => retireSeatName(start, SUBJECT, ava.entry_id, ctx())).toThrow(SeatLogRefusal);
140
+ const avie = start.find((e) => e.raw === "Avie")!;
141
+ const r = retireSeatName(start, SUBJECT, avie.entry_id, ctx());
142
+ expect(r.entries).toHaveLength(2);
143
+ expect(pastSeatNames(r.entries).map((e) => e.raw)).toEqual(["Avie"]);
144
+ });
145
+
146
+ it("ignores rows of another subject", () => {
147
+ const other: SeatNameEntry = {
148
+ entry_id: "x", subject_type: "person", subject_id: "u1", name_type: "legal", raw: "P",
149
+ is_display: true, is_preferred: true, period_start: "", period_end: "",
150
+ source: "admin_hub", method: "direct_entry", notes: "",
151
+ };
152
+ const r = addSeatName([other], SUBJECT, { raw: "Bo", name_type: "legal" }, ctx());
153
+ expect(r.entries.map((e) => e.raw)).toEqual(["Bo"]);
154
+ expect(r.inserted[0].is_display).toBe(true);
155
+ });
156
+ });
157
+
158
+ describe("entry ids", () => {
159
+ it("refuses to insert over an existing entry id", () => {
160
+ const fixed = { actor: "a", mintId: () => "same" };
161
+ const es = addSeatName([], SUBJECT, { raw: "Bo", name_type: "legal" }, fixed).entries;
162
+ expect(() => addSeatName(es, SUBJECT, { raw: "Al", name_type: "alias" }, fixed))
163
+ .toThrow("entry_id_exists");
164
+ });
165
+ });
166
+
167
+ describe("contact values", () => {
168
+ it("formats and keys phones as canon does", () => {
169
+ expect(formatSeatPhone("+1 402 677 3902")).toBe("(402) 677-3902");
170
+ expect(formatSeatPhone("442079460958")).toBe("+44 (207) 946-0958");
171
+ expect(canonSeatContactValue("phone", " 4026773902 ")).toBe("(402) 677-3902");
172
+ expect(canonSeatContactValue("phone", "front desk")).toBe("front desk");
173
+ expect(canonSeatContactValue("email", " A@B.org ")).toBe("A@B.org");
174
+ expect(seatContactKey("phone", "+1 (402) 677-3902")).toBe(seatContactKey("phone", "402.677.3902"));
175
+ expect(seatContactKey("email", " A@B.org")).toBe("a@b.org");
176
+ });
177
+
178
+ it("guards in the profile's words", () => {
179
+ expect(seatPhoneRefusal("")).toBe("");
180
+ expect(seatPhoneRefusal("front desk")).toBe("That doesn't have any numbers in it — a phone entry needs digits.");
181
+ expect(seatPhoneRefusal("12345")).toBe("That's too short for a phone number — it needs at least 7 digits.");
182
+ expect(seatPhoneRefusal("1234567890123456")).toBe("That's too long for a phone number — 15 digits is the international maximum.");
183
+ expect(seatEmailRefusal("nope")).toBe("That isn't a working address yet — it needs an @ and a domain.");
184
+ expect(seatEmailRefusal("A@b.org", ["a@B.org"])).toBe("Already in the directory — two seats can't share an address.");
185
+ expect(seatEmailRefusal("a@b.org", ["c@d.org"])).toBe("");
186
+ });
187
+ });
188
+
189
+ describe("contact log", () => {
190
+ const add = (es: SeatContactEntry[], contact_type: "email" | "phone", value: string, c = ctx()) =>
191
+ addSeatContact(es, SUBJECT, { contact_type, value }, c);
192
+
193
+ it("the first of each type is preferred; phones are normalized and keyed", () => {
194
+ let es = add([], "email", "ava@x.org").entries;
195
+ es = add(es, "phone", "+1 402 677 3902").entries;
196
+ es = add(es, "email", "ava@y.org").entries;
197
+ expect(es.map((e) => [e.contact_type, e.value, e.is_preferred, e.digits])).toEqual([
198
+ ["email", "ava@x.org", true, undefined],
199
+ ["phone", "(402) 677-3902", true, "4026773902"],
200
+ ["email", "ava@y.org", false, undefined],
201
+ ]);
202
+ for (const e of es) {
203
+ expect(SeatContactEntrySchema.parse(e)).toBeTruthy();
204
+ expect(e).toMatchObject({ use: "", safety_status: "", source: "admin_hub", method: "direct_entry" });
205
+ }
206
+ expect(seatEmailProjection(es)).toBe("ava@x.org");
207
+ });
208
+
209
+ it("the same line typed another way is a duplicate; bad values are refused", () => {
210
+ const es = add([], "phone", "(402) 677-3902").entries;
211
+ expect(add(es, "phone", "+1 402.677.3902").inserted).toEqual([]);
212
+ expect(() => add([], "phone", "123")).toThrow(SeatLogRefusal);
213
+ expect(() => addSeatContact([], SUBJECT, { contact_type: "email", value: "a@b.org" },
214
+ { ...ctx(), otherSeatEmails: ["A@B.org"] })).toThrow("two seats can't share an address");
215
+ });
216
+
217
+ it("☆ prefer is one per type and moves the email projection", () => {
218
+ let es = add([], "email", "a@x.org").entries;
219
+ es = add(es, "email", "b@x.org").entries;
220
+ es = add(es, "phone", "4026773902").entries;
221
+ const b = es.find((e) => e.value === "b@x.org")!;
222
+ const r = setPreferredSeatContact(es, SUBJECT, b.entry_id, ctx());
223
+ expect(live(r.entries).filter((e) => e.is_preferred).map((e) => e.value)).toEqual(["b@x.org", "(402) 677-3902"]);
224
+ expect(seatEmailProjection(r.entries)).toBe("b@x.org");
225
+ expect(r.updated.map((e) => e.value).sort()).toEqual(["a@x.org", "b@x.org"]);
226
+ });
227
+
228
+ it("correction inserts, carries the preferred mark, archives the old, notes what it corrects", () => {
229
+ const es = add([], "email", "a@x.org").entries;
230
+ const r = correctSeatContact(es, SUBJECT, es[0].entry_id, "a@y.org", ctx());
231
+ expect(liveSeatContacts(r.entries).map((e) => [e.value, e.is_preferred, e.notes])).toEqual([
232
+ ["a@y.org", true, "Corrects “a@x.org”"],
233
+ ]);
234
+ expect(r.updated[0]).toMatchObject({ value: "a@x.org", period_end: "2026-11-16", is_preferred: false });
235
+ expect(seatEmailProjection(r.entries)).toBe("a@y.org");
236
+ });
237
+
238
+ it("re-typing the same phone in another shape is a no-op correction", () => {
239
+ const es = add([], "phone", "4026773902").entries;
240
+ const r = correctSeatContact(es, SUBJECT, es[0].entry_id, "(402) 677-3902", ctx());
241
+ expect(r.inserted).toEqual([]);
242
+ expect(r.updated).toEqual([]);
243
+ });
244
+
245
+ it("correcting INTO a live value hands it the mark and archives the wrong one", () => {
246
+ let es = add([], "phone", "4026773902").entries;
247
+ es = add(es, "phone", "4025550100").entries;
248
+ const r = correctSeatContact(es, SUBJECT, es[0].entry_id, "402-555-0100", ctx());
249
+ expect(r.inserted).toEqual([]);
250
+ expect(liveSeatContacts(r.entries).map((e) => [e.value, e.is_preferred])).toEqual([["(402) 555-0100", true]]);
251
+ });
252
+
253
+ it("a preferred entry can't be retired while another of its type is live", () => {
254
+ let es = add([], "email", "a@x.org").entries;
255
+ es = add(es, "email", "b@x.org").entries;
256
+ expect(canRetireSeatContact(es, es[0])).toBe(false);
257
+ expect(() => retireSeatContact(es, SUBJECT, es[0].entry_id, ctx())).toThrow(SeatLogRefusal);
258
+ const r = retireSeatContact(es, SUBJECT, es[1].entry_id, ctx());
259
+ expect(liveSeatContacts(r.entries).map((e) => e.value)).toEqual(["a@x.org"]);
260
+ expect(canRetireSeatContact(r.entries, r.entries[0])).toBe(true);
261
+ const gone = retireSeatContact(r.entries, SUBJECT, r.entries[0].entry_id, ctx());
262
+ expect(seatEmailProjection(gone.entries)).toBe("");
263
+ expect(gone.entries).toHaveLength(2);
264
+ });
265
+ });
266
+
267
+ describe("mintPersonId", () => {
268
+ const words = { first: ["agate", "amber"], second: ["beacon", "cairn"] };
269
+
270
+ it("mints per-<first>-<second> not already taken", () => {
271
+ const id = mintPersonId(words, ["per-agate-beacon"], () => 0);
272
+ // random() = 0 always draws the taken slug; after 200 draws the space is scanned.
273
+ expect(id).toBe("per-agate-cairn");
274
+ let i = 0;
275
+ const seq = [0, 0, 0.6, 0.6];
276
+ const minted = mintPersonId(words, ["per-agate-beacon"], () => seq[i++ % seq.length]);
277
+ expect(minted).toBe("per-amber-cairn");
278
+ expect(isPersonId(minted)).toBe(true);
279
+ });
280
+
281
+ it("refuses rather than invents when there are no wordlists", () => {
282
+ expect(mintPersonId(null)).toBeNull();
283
+ expect(mintPersonId({ first: [], second: ["x"] })).toBeNull();
284
+ });
285
+ });
286
+
287
+ describe("readSeatContactLogs", () => {
288
+ it("groups by subject, strips _id, and throws on a corrupt row", async () => {
289
+ const rows = [
290
+ { _id: "o1", ...add0("u1", "a@x.org") },
291
+ { _id: "o2", ...add0("u2", "b@x.org") },
292
+ ];
293
+ let seen: Record<string, unknown> | null = null;
294
+ const db = {
295
+ collection: (name: string) => ({
296
+ find: (f: Record<string, unknown>) => {
297
+ seen = { name, ...f };
298
+ return { toArray: async () => rows };
299
+ },
300
+ }),
301
+ };
302
+ const m = await readSeatContactLogs(db, ["u1", "u2", "u1"]);
303
+ expect(seen).toEqual({ name: "seat_contacts", subject_type: "user", subject_id: { $in: ["u1", "u2"] } });
304
+ expect(m.get("u1")?.[0]).not.toHaveProperty("_id");
305
+ expect([...m.keys()]).toEqual(["u1", "u2"]);
306
+ const bad = { collection: () => ({ find: () => ({ toArray: async () => [{ entry_id: "z" }] }) }) };
307
+ await expect(readSeatContactLogs(bad, ["u1"])).rejects.toThrow("seat-logs: stored entry z");
308
+ expect(await readSeatContactLogs(bad, [])).toEqual(new Map());
309
+ });
310
+ });
311
+
312
+ function add0(subject_id: string, value: string): SeatContactEntry {
313
+ return addSeatContact([], { subject_type: "user", subject_id }, { contact_type: "email", value }, ctx())
314
+ .inserted[0];
315
+ }
316
+
317
+ describe("vendored Person id wordlists", () => {
318
+ it("pins both lists: 45 words each, lowercase a-z, no repeats", () => {
319
+ for (const list of [PERSON_SLUG_FIRST, PERSON_SLUG_SECOND]) {
320
+ expect(list).toHaveLength(45);
321
+ expect(new Set(list).size).toBe(45);
322
+ for (const w of list) expect(w).toMatch(/^[a-z]+$/);
323
+ }
324
+ expect(PERSON_SLUG_WORDLISTS.first).toBe(PERSON_SLUG_FIRST);
325
+ expect(PERSON_SLUG_WORDLISTS.second).toBe(PERSON_SLUG_SECOND);
326
+ });
327
+
328
+ it("mintPersonId defaults to the vendored lists; mintNewPersonId too", () => {
329
+ const a = mintPersonId(undefined, [], () => 0);
330
+ expect(a).toBe(`per-${PERSON_SLUG_FIRST[0]}-${PERSON_SLUG_SECOND[0]}`);
331
+ expect(mintNewPersonId([a], () => 0.999)).toBe(`per-${PERSON_SLUG_FIRST[44]}-${PERSON_SLUG_SECOND[44]}`);
332
+ expect(isPersonId(mintNewPersonId())).toBe(true);
333
+ expect(mintPersonId(null)).toBeNull();
334
+ });
335
+ });
@@ -0,0 +1,15 @@
1
+ /**
2
+ * @htilabs/platform-common-models/seat-logs
3
+ *
4
+ * A seat's NAME log and CONTACT log (the member profile's "Names" and "Ways to
5
+ * reach them"), and the Person id minter. Entry shapes, the display /
6
+ * preferred invariants, insert-and-archive correction, phone normalization and
7
+ * the digits key, the guards, the flat-field projections, and raw-driver reads.
8
+ * Pure TypeScript, no mongoose, no driver import. Subpath only.
9
+ */
10
+
11
+ export * from "./schemas.js";
12
+ export * from "./log.js";
13
+ export * from "./personId.js";
14
+ export * from "./personSlugWordlists.js";
15
+ export * from "./reader.js";