@app-vitals/agent-admin 1.105.0 → 1.106.1
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.
- package/package.json +2 -2
- package/scripts/backfill-member-id.ts +22 -13
- package/src/account-members.ts +16 -3
- package/src/account-onboarding.ts +5 -2
- package/src/accounts.ts +5 -6
- package/src/admin-boot.ts +3 -0
- package/src/admin-ui-agent-members.smoke.test.ts +202 -0
- package/src/admin-ui.ts +36 -0
- package/src/agents-api.ts +21 -2
- package/src/agents.integration.test.ts +48 -0
- package/src/agents.ts +199 -145
- package/src/ensure-account-member.integration.test.ts +383 -0
- package/src/ensure-account-member.ts +129 -0
- package/src/ensure-account-member.unit.test.ts +78 -0
- package/src/member-id-backfill.ts +73 -0
- package/src/member-id-stamp.ts +42 -0
|
@@ -0,0 +1,383 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* admin/src/ensure-account-member.integration.test.ts
|
|
3
|
+
* ensureAccountMember, stamping on every AccountMember creation path, re-add
|
|
4
|
+
* repair of a hidden agent member, and the --verify report. Real Postgres.
|
|
5
|
+
*
|
|
6
|
+
* Requires DATABASE_URL_ADMIN_TEST; skips otherwise.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { afterEach, beforeEach, describe, expect, it } from "bun:test";
|
|
10
|
+
import type { PrismaClient } from "../prisma/client/client.ts";
|
|
11
|
+
import { AccountMemberService } from "./account-members.ts";
|
|
12
|
+
import { AccountOnboardingService } from "./account-onboarding.ts";
|
|
13
|
+
import { AccountService } from "./accounts.ts";
|
|
14
|
+
import { AgentMemberService } from "./agent-members.ts";
|
|
15
|
+
import { ensureAccountMember } from "./ensure-account-member.ts";
|
|
16
|
+
import { verifyMemberIds } from "./member-id-backfill.ts";
|
|
17
|
+
import { createAdminPrismaClient } from "./prisma-client.ts";
|
|
18
|
+
|
|
19
|
+
const TEST_DB = process.env.DATABASE_URL_ADMIN_TEST;
|
|
20
|
+
const describeOrSkip = TEST_DB ? describe : describe.skip;
|
|
21
|
+
|
|
22
|
+
const ADMIN = { platformAdmin: true, ownerOfAccountId: null };
|
|
23
|
+
|
|
24
|
+
describeOrSkip("ensureAccountMember (integration)", () => {
|
|
25
|
+
let prisma: PrismaClient;
|
|
26
|
+
let acme: string;
|
|
27
|
+
let other: string;
|
|
28
|
+
let agentId: string;
|
|
29
|
+
|
|
30
|
+
async function seedNullRows(email: string) {
|
|
31
|
+
await prisma.agentMember.create({ data: { agentId, email } });
|
|
32
|
+
await prisma.chatThreadWatch.create({
|
|
33
|
+
data: { userEmail: email, threadId: `t-${email}`, agentId },
|
|
34
|
+
});
|
|
35
|
+
await prisma.pushSubscription.create({
|
|
36
|
+
data: {
|
|
37
|
+
userEmail: email,
|
|
38
|
+
endpoint: `ep-${email}`,
|
|
39
|
+
p256dh: "p",
|
|
40
|
+
auth: "a",
|
|
41
|
+
},
|
|
42
|
+
});
|
|
43
|
+
await prisma.userNotificationPrefs.create({ data: { userEmail: email } });
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
async function memberIdsFor(email: string) {
|
|
47
|
+
const [a, b, c, d] = await Promise.all([
|
|
48
|
+
prisma.agentMember.findMany({ where: { email } }),
|
|
49
|
+
prisma.chatThreadWatch.findMany({ where: { userEmail: email } }),
|
|
50
|
+
prisma.pushSubscription.findMany({ where: { userEmail: email } }),
|
|
51
|
+
prisma.userNotificationPrefs.findMany({ where: { userEmail: email } }),
|
|
52
|
+
]);
|
|
53
|
+
return [a, b, c, d].map((rows) => rows.map((r) => r.memberId));
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
beforeEach(async () => {
|
|
57
|
+
prisma = createAdminPrismaClient(TEST_DB as string);
|
|
58
|
+
await prisma.userNotificationPrefs.deleteMany();
|
|
59
|
+
await prisma.chatThreadWatch.deleteMany();
|
|
60
|
+
await prisma.pushSubscription.deleteMany();
|
|
61
|
+
await prisma.agentMember.deleteMany();
|
|
62
|
+
await prisma.accountInvite.deleteMany();
|
|
63
|
+
await prisma.accountMember.deleteMany();
|
|
64
|
+
await prisma.agent.deleteMany();
|
|
65
|
+
await prisma.account.deleteMany();
|
|
66
|
+
acme = (await prisma.account.create({ data: { name: "Acme" } })).id;
|
|
67
|
+
other = (await prisma.account.create({ data: { name: "Other" } })).id;
|
|
68
|
+
agentId = (
|
|
69
|
+
await prisma.agent.create({
|
|
70
|
+
data: { id: "ens-agent", name: "ens-agent", accountId: acme },
|
|
71
|
+
})
|
|
72
|
+
).id;
|
|
73
|
+
});
|
|
74
|
+
|
|
75
|
+
afterEach(async () => {
|
|
76
|
+
await prisma.$disconnect();
|
|
77
|
+
});
|
|
78
|
+
|
|
79
|
+
it("creates a member-role record in the agent's account and the agent member is listed", async () => {
|
|
80
|
+
const ensured = await ensureAccountMember(prisma, {
|
|
81
|
+
email: "New@Acme.com",
|
|
82
|
+
agentAccountId: acme,
|
|
83
|
+
creator: ADMIN,
|
|
84
|
+
});
|
|
85
|
+
if (!ensured.ok) throw new Error(ensured.message);
|
|
86
|
+
expect(ensured.created).toBe(true);
|
|
87
|
+
expect(ensured.member).toMatchObject({
|
|
88
|
+
email: "new@acme.com",
|
|
89
|
+
accountId: acme,
|
|
90
|
+
role: "member",
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
const service = new AgentMemberService(prisma);
|
|
94
|
+
await service.add(agentId, "new@acme.com");
|
|
95
|
+
const listed = await service.listByAgentId(agentId);
|
|
96
|
+
expect(listed.map((m) => m.email)).toEqual(["new@acme.com"]);
|
|
97
|
+
expect(await service.exists(agentId, "new@acme.com")).toBe(true);
|
|
98
|
+
});
|
|
99
|
+
|
|
100
|
+
it("reuses an existing record unchanged, even in another account, for a caller who cannot create", async () => {
|
|
101
|
+
const owner = await prisma.accountMember.create({
|
|
102
|
+
data: { accountId: other, email: "o@x.com", role: "owner" },
|
|
103
|
+
});
|
|
104
|
+
const ensured = await ensureAccountMember(prisma, {
|
|
105
|
+
email: "o@x.com",
|
|
106
|
+
agentAccountId: acme,
|
|
107
|
+
creator: { platformAdmin: false, ownerOfAccountId: null },
|
|
108
|
+
});
|
|
109
|
+
if (!ensured.ok) throw new Error(ensured.message);
|
|
110
|
+
expect(ensured.created).toBe(false);
|
|
111
|
+
expect(ensured.member.id).toBe(owner.id);
|
|
112
|
+
const after = await prisma.accountMember.findUniqueOrThrow({
|
|
113
|
+
where: { id: owner.id },
|
|
114
|
+
});
|
|
115
|
+
expect(after).toMatchObject({ accountId: other, role: "owner" });
|
|
116
|
+
expect(await prisma.accountMember.count()).toBe(1);
|
|
117
|
+
});
|
|
118
|
+
|
|
119
|
+
it("uses the only Account when the agent has none", async () => {
|
|
120
|
+
await prisma.account.delete({ where: { id: other } });
|
|
121
|
+
const ensured = await ensureAccountMember(prisma, {
|
|
122
|
+
email: "n@x.com",
|
|
123
|
+
agentAccountId: null,
|
|
124
|
+
creator: ADMIN,
|
|
125
|
+
});
|
|
126
|
+
if (!ensured.ok) throw new Error(ensured.message);
|
|
127
|
+
expect(ensured.member.accountId).toBe(acme);
|
|
128
|
+
});
|
|
129
|
+
|
|
130
|
+
it("fails without writing when no account can be chosen", async () => {
|
|
131
|
+
const ambiguous = await ensureAccountMember(prisma, {
|
|
132
|
+
email: "n@x.com",
|
|
133
|
+
agentAccountId: null,
|
|
134
|
+
creator: ADMIN,
|
|
135
|
+
});
|
|
136
|
+
expect(ambiguous).toMatchObject({ ok: false, code: "ambiguous_account" });
|
|
137
|
+
await prisma.agent.update({
|
|
138
|
+
where: { id: agentId },
|
|
139
|
+
data: { accountId: null },
|
|
140
|
+
});
|
|
141
|
+
await prisma.account.deleteMany();
|
|
142
|
+
const none = await ensureAccountMember(prisma, {
|
|
143
|
+
email: "n@x.com",
|
|
144
|
+
agentAccountId: null,
|
|
145
|
+
creator: ADMIN,
|
|
146
|
+
});
|
|
147
|
+
expect(none).toMatchObject({ ok: false, code: "no_account" });
|
|
148
|
+
expect(await prisma.accountMember.count()).toBe(0);
|
|
149
|
+
});
|
|
150
|
+
|
|
151
|
+
it("denies member-role callers and owners of another account, writing nothing", async () => {
|
|
152
|
+
for (const creator of [
|
|
153
|
+
{ platformAdmin: false, ownerOfAccountId: null },
|
|
154
|
+
{ platformAdmin: false, ownerOfAccountId: other },
|
|
155
|
+
]) {
|
|
156
|
+
const result = await ensureAccountMember(prisma, {
|
|
157
|
+
email: "n@x.com",
|
|
158
|
+
agentAccountId: acme,
|
|
159
|
+
creator,
|
|
160
|
+
});
|
|
161
|
+
expect(result).toMatchObject({ ok: false, code: "not_permitted" });
|
|
162
|
+
}
|
|
163
|
+
expect(await prisma.accountMember.count()).toBe(0);
|
|
164
|
+
});
|
|
165
|
+
|
|
166
|
+
it("lets the owner of the target account create", async () => {
|
|
167
|
+
const result = await ensureAccountMember(prisma, {
|
|
168
|
+
email: "n@x.com",
|
|
169
|
+
agentAccountId: acme,
|
|
170
|
+
creator: { platformAdmin: false, ownerOfAccountId: acme },
|
|
171
|
+
});
|
|
172
|
+
expect(result.ok).toBe(true);
|
|
173
|
+
});
|
|
174
|
+
|
|
175
|
+
it("stamps null rows in all four tables when it creates the record", async () => {
|
|
176
|
+
await seedNullRows("late@acme.com");
|
|
177
|
+
const ensured = await ensureAccountMember(prisma, {
|
|
178
|
+
email: "late@acme.com",
|
|
179
|
+
agentAccountId: acme,
|
|
180
|
+
creator: ADMIN,
|
|
181
|
+
});
|
|
182
|
+
if (!ensured.ok) throw new Error(ensured.message);
|
|
183
|
+
expect(await memberIdsFor("late@acme.com")).toEqual([
|
|
184
|
+
[ensured.member.id],
|
|
185
|
+
[ensured.member.id],
|
|
186
|
+
[ensured.member.id],
|
|
187
|
+
[ensured.member.id],
|
|
188
|
+
]);
|
|
189
|
+
});
|
|
190
|
+
|
|
191
|
+
it("re-adding a hidden agent member repairs its null memberId", async () => {
|
|
192
|
+
await seedNullRows("hidden@acme.com");
|
|
193
|
+
const service = new AgentMemberService(prisma);
|
|
194
|
+
expect(await service.listByAgentId(agentId)).toEqual([]);
|
|
195
|
+
|
|
196
|
+
const ensured = await ensureAccountMember(prisma, {
|
|
197
|
+
email: "hidden@acme.com",
|
|
198
|
+
agentAccountId: acme,
|
|
199
|
+
creator: ADMIN,
|
|
200
|
+
});
|
|
201
|
+
expect(ensured.ok).toBe(true);
|
|
202
|
+
await service.add(agentId, "hidden@acme.com").catch(() => {});
|
|
203
|
+
expect((await service.listByAgentId(agentId)).map((m) => m.email)).toEqual([
|
|
204
|
+
"hidden@acme.com",
|
|
205
|
+
]);
|
|
206
|
+
expect(await prisma.agentMember.count()).toBe(1);
|
|
207
|
+
});
|
|
208
|
+
|
|
209
|
+
it("repairs when the record already exists but the rows were left null", async () => {
|
|
210
|
+
const rec = await prisma.accountMember.create({
|
|
211
|
+
data: { accountId: other, email: "ex@x.com", role: "member" },
|
|
212
|
+
});
|
|
213
|
+
await seedNullRows("ex@x.com");
|
|
214
|
+
await ensureAccountMember(prisma, {
|
|
215
|
+
email: "ex@x.com",
|
|
216
|
+
agentAccountId: acme,
|
|
217
|
+
});
|
|
218
|
+
expect(await memberIdsFor("ex@x.com")).toEqual([
|
|
219
|
+
[rec.id],
|
|
220
|
+
[rec.id],
|
|
221
|
+
[rec.id],
|
|
222
|
+
[rec.id],
|
|
223
|
+
]);
|
|
224
|
+
});
|
|
225
|
+
|
|
226
|
+
describe("stamping on every AccountMember creation path", () => {
|
|
227
|
+
it("AccountMemberService.add", async () => {
|
|
228
|
+
await seedNullRows("svc@x.com");
|
|
229
|
+
const m = await new AccountMemberService(prisma).add(acme, "SVC@x.com");
|
|
230
|
+
expect(await memberIdsFor("svc@x.com")).toEqual([
|
|
231
|
+
[m.id],
|
|
232
|
+
[m.id],
|
|
233
|
+
[m.id],
|
|
234
|
+
[m.id],
|
|
235
|
+
]);
|
|
236
|
+
});
|
|
237
|
+
|
|
238
|
+
it("AccountMemberService.add inside a caller transaction rolls the stamping back with it", async () => {
|
|
239
|
+
await seedNullRows("rb@x.com");
|
|
240
|
+
await prisma
|
|
241
|
+
.$transaction(async (tx) => {
|
|
242
|
+
await new AccountMemberService(prisma).add(
|
|
243
|
+
acme,
|
|
244
|
+
"rb@x.com",
|
|
245
|
+
"member",
|
|
246
|
+
tx,
|
|
247
|
+
);
|
|
248
|
+
throw new Error("abort");
|
|
249
|
+
})
|
|
250
|
+
.catch(() => {});
|
|
251
|
+
expect(await memberIdsFor("rb@x.com")).toEqual([
|
|
252
|
+
[null],
|
|
253
|
+
[null],
|
|
254
|
+
[null],
|
|
255
|
+
[null],
|
|
256
|
+
]);
|
|
257
|
+
});
|
|
258
|
+
|
|
259
|
+
it("AccountService.create", async () => {
|
|
260
|
+
await seedNullRows("boss@x.com");
|
|
261
|
+
const account = await new AccountService(prisma).create(
|
|
262
|
+
"New",
|
|
263
|
+
"boss@x.com",
|
|
264
|
+
);
|
|
265
|
+
const owner = await prisma.accountMember.findFirstOrThrow({
|
|
266
|
+
where: { accountId: account.id },
|
|
267
|
+
});
|
|
268
|
+
expect(await memberIdsFor("boss@x.com")).toEqual([
|
|
269
|
+
[owner.id],
|
|
270
|
+
[owner.id],
|
|
271
|
+
[owner.id],
|
|
272
|
+
[owner.id],
|
|
273
|
+
]);
|
|
274
|
+
});
|
|
275
|
+
|
|
276
|
+
it("AccountOnboardingService (new account and invite)", async () => {
|
|
277
|
+
const onboarding = new AccountOnboardingService(prisma, 3);
|
|
278
|
+
await seedNullRows("first@x.com");
|
|
279
|
+
await onboarding.provisionForEmail("first@x.com");
|
|
280
|
+
const first = await prisma.accountMember.findUniqueOrThrow({
|
|
281
|
+
where: { email: "first@x.com" },
|
|
282
|
+
});
|
|
283
|
+
expect(await memberIdsFor("first@x.com")).toEqual([
|
|
284
|
+
[first.id],
|
|
285
|
+
[first.id],
|
|
286
|
+
[first.id],
|
|
287
|
+
[first.id],
|
|
288
|
+
]);
|
|
289
|
+
|
|
290
|
+
await prisma.accountInvite.create({
|
|
291
|
+
data: { accountId: acme, email: "inv@x.com", invitedBy: "o@x.com" },
|
|
292
|
+
});
|
|
293
|
+
await seedNullRows("inv@x.com");
|
|
294
|
+
await onboarding.provisionForEmail("inv@x.com");
|
|
295
|
+
const invited = await prisma.accountMember.findUniqueOrThrow({
|
|
296
|
+
where: { email: "inv@x.com" },
|
|
297
|
+
});
|
|
298
|
+
expect(invited.accountId).toBe(acme);
|
|
299
|
+
expect(await memberIdsFor("inv@x.com")).toEqual([
|
|
300
|
+
[invited.id],
|
|
301
|
+
[invited.id],
|
|
302
|
+
[invited.id],
|
|
303
|
+
[invited.id],
|
|
304
|
+
]);
|
|
305
|
+
});
|
|
306
|
+
});
|
|
307
|
+
|
|
308
|
+
describe("verifyMemberIds", () => {
|
|
309
|
+
it("reports nothing wrong on a clean database", async () => {
|
|
310
|
+
const report = await verifyMemberIds(prisma);
|
|
311
|
+
expect(report.hasProblems).toBe(false);
|
|
312
|
+
});
|
|
313
|
+
|
|
314
|
+
async function runScript() {
|
|
315
|
+
const proc = Bun.spawn(
|
|
316
|
+
[
|
|
317
|
+
"bun",
|
|
318
|
+
`${import.meta.dir}/../scripts/backfill-member-id.ts`,
|
|
319
|
+
"--verify",
|
|
320
|
+
],
|
|
321
|
+
{
|
|
322
|
+
env: {
|
|
323
|
+
...process.env,
|
|
324
|
+
DATABASE_URL_SHIPWRIGHT_ADMIN: TEST_DB as string,
|
|
325
|
+
},
|
|
326
|
+
stdout: "pipe",
|
|
327
|
+
stderr: "pipe",
|
|
328
|
+
},
|
|
329
|
+
);
|
|
330
|
+
const [out, code] = await Promise.all([
|
|
331
|
+
new Response(proc.stdout).text(),
|
|
332
|
+
proc.exited,
|
|
333
|
+
]);
|
|
334
|
+
return { out, code };
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
it("the --verify script exits 0 when clean and non-zero with a report otherwise, writing nothing", async () => {
|
|
338
|
+
expect((await runScript()).code).toBe(0);
|
|
339
|
+
await seedNullRows("nul@x.com");
|
|
340
|
+
const { out, code } = await runScript();
|
|
341
|
+
expect(code).toBe(1);
|
|
342
|
+
expect(JSON.parse(out).tables.AgentMember.null.emails).toEqual([
|
|
343
|
+
"nul@x.com",
|
|
344
|
+
]);
|
|
345
|
+
expect((await prisma.agentMember.findFirstOrThrow()).memberId).toBeNull();
|
|
346
|
+
});
|
|
347
|
+
|
|
348
|
+
it("reports null and dangling memberId per table, and writes nothing", async () => {
|
|
349
|
+
await seedNullRows("nul@x.com");
|
|
350
|
+
const good = await prisma.accountMember.create({
|
|
351
|
+
data: { accountId: acme, email: "ok@x.com", role: "member" },
|
|
352
|
+
});
|
|
353
|
+
await prisma.agentMember.create({
|
|
354
|
+
data: { agentId, email: "ok@x.com", memberId: good.id },
|
|
355
|
+
});
|
|
356
|
+
// Dangling: a memberId naming no AccountMember (there is no FK).
|
|
357
|
+
await prisma.userNotificationPrefs.create({
|
|
358
|
+
data: { userEmail: "dang@x.com", memberId: "gone-id" },
|
|
359
|
+
});
|
|
360
|
+
const before = await prisma.agentMember.findMany({
|
|
361
|
+
orderBy: { id: "asc" },
|
|
362
|
+
});
|
|
363
|
+
|
|
364
|
+
const report = await verifyMemberIds(prisma);
|
|
365
|
+
expect(report.hasProblems).toBe(true);
|
|
366
|
+
expect(report.tables.AgentMember.null).toEqual({
|
|
367
|
+
count: 1,
|
|
368
|
+
emails: ["nul@x.com"],
|
|
369
|
+
});
|
|
370
|
+
expect(report.tables.ChatThreadWatch.null.count).toBe(1);
|
|
371
|
+
expect(report.tables.PushSubscription.null.emails).toEqual(["nul@x.com"]);
|
|
372
|
+
expect(report.tables.UserNotificationPrefs.null.count).toBe(1);
|
|
373
|
+
expect(report.tables.AgentMember.dangling.count).toBe(0);
|
|
374
|
+
expect(report.tables.UserNotificationPrefs.dangling).toEqual({
|
|
375
|
+
count: 1,
|
|
376
|
+
emails: ["dang@x.com"],
|
|
377
|
+
});
|
|
378
|
+
expect(
|
|
379
|
+
await prisma.agentMember.findMany({ orderBy: { id: "asc" } }),
|
|
380
|
+
).toEqual(before);
|
|
381
|
+
});
|
|
382
|
+
});
|
|
383
|
+
});
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* admin/src/ensure-account-member.ts
|
|
3
|
+
* One shared "make sure this email has an AccountMember" operation, used by the
|
|
4
|
+
* agent member add route and by member emails at agent creation.
|
|
5
|
+
*
|
|
6
|
+
* - An existing record is reused unchanged (even in another account).
|
|
7
|
+
* - Otherwise a role=member record is created in the agent's account, or in the
|
|
8
|
+
* only Account when the agent has none and exactly one exists. No other case
|
|
9
|
+
* picks an account: the operation fails with a clear message and writes nothing.
|
|
10
|
+
* - Creating a record needs a platform admin or the owner of the target account.
|
|
11
|
+
* - Null memberId rows for the email are stamped either way, so a hidden agent
|
|
12
|
+
* member becomes visible again on re-add.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import type { AccountMember } from "../prisma/client/client.ts";
|
|
16
|
+
import { normalizeEmail } from "./account-email.ts";
|
|
17
|
+
import type { CallerScope } from "./caller-scope.ts";
|
|
18
|
+
import { stampMemberId } from "./member-id-stamp.ts";
|
|
19
|
+
import type { PrismaTransactionClient } from "./prisma-tx.ts";
|
|
20
|
+
|
|
21
|
+
/** Who is asking, as far as creating account members is concerned. */
|
|
22
|
+
export interface MemberCreator {
|
|
23
|
+
platformAdmin: boolean;
|
|
24
|
+
/** Account the caller owns, or null. */
|
|
25
|
+
ownerOfAccountId: string | null;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** Creator for a caller scope: platform admins, and owners of their account. */
|
|
29
|
+
export function creatorFromScope(scope: CallerScope): MemberCreator {
|
|
30
|
+
if (scope.kind === "all")
|
|
31
|
+
return { platformAdmin: true, ownerOfAccountId: null };
|
|
32
|
+
return {
|
|
33
|
+
platformAdmin: false,
|
|
34
|
+
ownerOfAccountId: scope.role === "owner" ? scope.accountId : null,
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export type EnsureFailureCode =
|
|
39
|
+
| "no_account"
|
|
40
|
+
| "ambiguous_account"
|
|
41
|
+
| "not_permitted";
|
|
42
|
+
|
|
43
|
+
export type EnsureAccountMemberResult =
|
|
44
|
+
| { ok: true; member: AccountMember; created: boolean }
|
|
45
|
+
| { ok: false; code: EnsureFailureCode; message: string };
|
|
46
|
+
|
|
47
|
+
export type AccountChoice =
|
|
48
|
+
| { ok: true; accountId: string }
|
|
49
|
+
| { ok: false; code: "no_account" | "ambiguous_account" };
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* The account a new record goes to: the agent's own, else the only Account when
|
|
53
|
+
* exactly one exists. `accountIds` need hold at most two ids.
|
|
54
|
+
*/
|
|
55
|
+
export function chooseAccountForNewMember(
|
|
56
|
+
agentAccountId: string | null,
|
|
57
|
+
accountIds: readonly string[],
|
|
58
|
+
): AccountChoice {
|
|
59
|
+
if (agentAccountId) return { ok: true, accountId: agentAccountId };
|
|
60
|
+
if (accountIds.length === 1)
|
|
61
|
+
return { ok: true, accountId: accountIds[0] as string };
|
|
62
|
+
return {
|
|
63
|
+
ok: false,
|
|
64
|
+
code: accountIds.length === 0 ? "no_account" : "ambiguous_account",
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export function canCreateAccountMember(
|
|
69
|
+
creator: MemberCreator | undefined,
|
|
70
|
+
targetAccountId: string,
|
|
71
|
+
): boolean {
|
|
72
|
+
if (!creator) return false;
|
|
73
|
+
return creator.platformAdmin || creator.ownerOfAccountId === targetAccountId;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
const FAILURE_MESSAGES: Record<"no_account" | "ambiguous_account", string> = {
|
|
77
|
+
no_account:
|
|
78
|
+
"No account exists to add this person to. Create an account for them first, or assign the agent to an account.",
|
|
79
|
+
ambiguous_account:
|
|
80
|
+
"This agent has no account and more than one account exists, so it is unclear where to add this person. Assign the agent to an account or add the person to an account first.",
|
|
81
|
+
};
|
|
82
|
+
|
|
83
|
+
export async function ensureAccountMember(
|
|
84
|
+
client: PrismaTransactionClient,
|
|
85
|
+
input: {
|
|
86
|
+
email: string;
|
|
87
|
+
/** The agent's accountId; null when it has none. */
|
|
88
|
+
agentAccountId: string | null;
|
|
89
|
+
creator?: MemberCreator;
|
|
90
|
+
},
|
|
91
|
+
): Promise<EnsureAccountMemberResult> {
|
|
92
|
+
const email = normalizeEmail(input.email);
|
|
93
|
+
const existing = await client.accountMember.findUnique({ where: { email } });
|
|
94
|
+
if (existing) {
|
|
95
|
+
await stampMemberId(client, email, existing.id);
|
|
96
|
+
return { ok: true, member: existing, created: false };
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
const accountIds = input.agentAccountId
|
|
100
|
+
? []
|
|
101
|
+
: (await client.account.findMany({ select: { id: true }, take: 2 })).map(
|
|
102
|
+
(a) => a.id,
|
|
103
|
+
);
|
|
104
|
+
const choice = chooseAccountForNewMember(input.agentAccountId, accountIds);
|
|
105
|
+
if (!choice.ok) {
|
|
106
|
+
return {
|
|
107
|
+
ok: false,
|
|
108
|
+
code: choice.code,
|
|
109
|
+
message: FAILURE_MESSAGES[choice.code],
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
if (!canCreateAccountMember(input.creator, choice.accountId)) {
|
|
113
|
+
return {
|
|
114
|
+
ok: false,
|
|
115
|
+
code: "not_permitted",
|
|
116
|
+
message: `${email} has no account membership yet. Only a platform admin or an owner of the account can add someone new; ask one of them to add ${email} first.`,
|
|
117
|
+
};
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
// upsert is a single INSERT ... ON CONFLICT, so a concurrent creator of the
|
|
121
|
+
// same email cannot abort the surrounding transaction.
|
|
122
|
+
const member = await client.accountMember.upsert({
|
|
123
|
+
where: { email },
|
|
124
|
+
create: { accountId: choice.accountId, email, role: "member" },
|
|
125
|
+
update: {},
|
|
126
|
+
});
|
|
127
|
+
await stampMemberId(client, email, member.id);
|
|
128
|
+
return { ok: true, member, created: true };
|
|
129
|
+
}
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import { describe, expect, it } from "bun:test";
|
|
2
|
+
import {
|
|
3
|
+
canCreateAccountMember,
|
|
4
|
+
chooseAccountForNewMember,
|
|
5
|
+
creatorFromScope,
|
|
6
|
+
} from "./ensure-account-member.ts";
|
|
7
|
+
|
|
8
|
+
describe("chooseAccountForNewMember", () => {
|
|
9
|
+
it("uses the agent's own account, whatever else exists", () => {
|
|
10
|
+
expect(chooseAccountForNewMember("a1", ["a1", "a2"])).toEqual({
|
|
11
|
+
ok: true,
|
|
12
|
+
accountId: "a1",
|
|
13
|
+
});
|
|
14
|
+
});
|
|
15
|
+
|
|
16
|
+
it("uses the only Account when the agent has none", () => {
|
|
17
|
+
expect(chooseAccountForNewMember(null, ["only"])).toEqual({
|
|
18
|
+
ok: true,
|
|
19
|
+
accountId: "only",
|
|
20
|
+
});
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
it("fails when the agent has none and no account exists", () => {
|
|
24
|
+
expect(chooseAccountForNewMember(null, [])).toEqual({
|
|
25
|
+
ok: false,
|
|
26
|
+
code: "no_account",
|
|
27
|
+
});
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
it("fails when the agent has none and several accounts exist", () => {
|
|
31
|
+
expect(chooseAccountForNewMember(null, ["a", "b"])).toEqual({
|
|
32
|
+
ok: false,
|
|
33
|
+
code: "ambiguous_account",
|
|
34
|
+
});
|
|
35
|
+
});
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
describe("canCreateAccountMember", () => {
|
|
39
|
+
it("allows a platform admin for any account", () => {
|
|
40
|
+
expect(
|
|
41
|
+
canCreateAccountMember(
|
|
42
|
+
{ platformAdmin: true, ownerOfAccountId: null },
|
|
43
|
+
"a1",
|
|
44
|
+
),
|
|
45
|
+
).toBe(true);
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
it("allows the owner of the target account only", () => {
|
|
49
|
+
const owner = { platformAdmin: false, ownerOfAccountId: "a1" };
|
|
50
|
+
expect(canCreateAccountMember(owner, "a1")).toBe(true);
|
|
51
|
+
expect(canCreateAccountMember(owner, "a2")).toBe(false);
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
it("denies a member-role caller and an unknown caller", () => {
|
|
55
|
+
expect(
|
|
56
|
+
canCreateAccountMember(
|
|
57
|
+
{ platformAdmin: false, ownerOfAccountId: null },
|
|
58
|
+
"a1",
|
|
59
|
+
),
|
|
60
|
+
).toBe(false);
|
|
61
|
+
expect(canCreateAccountMember(undefined, "a1")).toBe(false);
|
|
62
|
+
});
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
describe("creatorFromScope", () => {
|
|
66
|
+
it("maps scopes to creators", () => {
|
|
67
|
+
expect(creatorFromScope({ kind: "all" })).toEqual({
|
|
68
|
+
platformAdmin: true,
|
|
69
|
+
ownerOfAccountId: null,
|
|
70
|
+
});
|
|
71
|
+
const scoped = (role?: "owner" | "member" | null) =>
|
|
72
|
+
creatorFromScope({ kind: "scoped", accountId: "a1", agentIds: [], role });
|
|
73
|
+
expect(scoped("owner").ownerOfAccountId).toBe("a1");
|
|
74
|
+
expect(scoped("member").ownerOfAccountId).toBeNull();
|
|
75
|
+
expect(scoped(undefined).ownerOfAccountId).toBeNull();
|
|
76
|
+
expect(scoped("owner").platformAdmin).toBe(false);
|
|
77
|
+
});
|
|
78
|
+
});
|
|
@@ -178,3 +178,76 @@ export async function runMemberIdBackfill(
|
|
|
178
178
|
),
|
|
179
179
|
};
|
|
180
180
|
}
|
|
181
|
+
|
|
182
|
+
export interface MemberIdProblems {
|
|
183
|
+
count: number;
|
|
184
|
+
/** Distinct emails of the affected rows, sorted. */
|
|
185
|
+
emails: string[];
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
export interface MemberIdVerifyReport {
|
|
189
|
+
tables: Record<
|
|
190
|
+
BackfillTable,
|
|
191
|
+
{ null: MemberIdProblems; dangling: MemberIdProblems }
|
|
192
|
+
>;
|
|
193
|
+
/** True when any table has a null or dangling memberId. */
|
|
194
|
+
hasProblems: boolean;
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/**
|
|
198
|
+
* Read-only check (--verify): per table, the rows whose memberId is null and
|
|
199
|
+
* the rows whose memberId names no AccountMember, each with a count and the
|
|
200
|
+
* distinct emails. Writes nothing.
|
|
201
|
+
*/
|
|
202
|
+
export async function verifyMemberIds(
|
|
203
|
+
prisma: PrismaClient,
|
|
204
|
+
): Promise<MemberIdVerifyReport> {
|
|
205
|
+
const known = new Set(
|
|
206
|
+
(await prisma.accountMember.findMany({ select: { id: true } })).map(
|
|
207
|
+
(m) => m.id,
|
|
208
|
+
),
|
|
209
|
+
);
|
|
210
|
+
const rowsByTable: Record<
|
|
211
|
+
BackfillTable,
|
|
212
|
+
() => Promise<{ email: string; memberId: string | null }[]>
|
|
213
|
+
> = {
|
|
214
|
+
UserNotificationPrefs: async () =>
|
|
215
|
+
(
|
|
216
|
+
await prisma.userNotificationPrefs.findMany({
|
|
217
|
+
select: { userEmail: true, memberId: true },
|
|
218
|
+
})
|
|
219
|
+
).map((r) => ({ email: r.userEmail, memberId: r.memberId })),
|
|
220
|
+
ChatThreadWatch: async () =>
|
|
221
|
+
(
|
|
222
|
+
await prisma.chatThreadWatch.findMany({
|
|
223
|
+
select: { userEmail: true, memberId: true },
|
|
224
|
+
})
|
|
225
|
+
).map((r) => ({ email: r.userEmail, memberId: r.memberId })),
|
|
226
|
+
PushSubscription: async () =>
|
|
227
|
+
(
|
|
228
|
+
await prisma.pushSubscription.findMany({
|
|
229
|
+
select: { userEmail: true, memberId: true },
|
|
230
|
+
})
|
|
231
|
+
).map((r) => ({ email: r.userEmail, memberId: r.memberId })),
|
|
232
|
+
AgentMember: async () =>
|
|
233
|
+
prisma.agentMember.findMany({ select: { email: true, memberId: true } }),
|
|
234
|
+
};
|
|
235
|
+
|
|
236
|
+
const summarize = (rows: { email: string }[]): MemberIdProblems => ({
|
|
237
|
+
count: rows.length,
|
|
238
|
+
emails: [...new Set(rows.map((r) => normalizeEmail(r.email)))].sort(),
|
|
239
|
+
});
|
|
240
|
+
|
|
241
|
+
const tables = {} as MemberIdVerifyReport["tables"];
|
|
242
|
+
let hasProblems = false;
|
|
243
|
+
for (const table of BACKFILL_TABLES) {
|
|
244
|
+
const rows = await rowsByTable[table]();
|
|
245
|
+
const nullRows = summarize(rows.filter((r) => r.memberId === null));
|
|
246
|
+
const dangling = summarize(
|
|
247
|
+
rows.filter((r) => r.memberId !== null && !known.has(r.memberId)),
|
|
248
|
+
);
|
|
249
|
+
if (nullRows.count > 0 || dangling.count > 0) hasProblems = true;
|
|
250
|
+
tables[table] = { null: nullRows, dangling };
|
|
251
|
+
}
|
|
252
|
+
return { tables, hasProblems };
|
|
253
|
+
}
|