@nexys/user-management-web 0.0.26

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 (77) hide show
  1. package/README.md +61 -0
  2. package/components.json +21 -0
  3. package/package.json +66 -0
  4. package/src/components/audit/audit-log-table.test.tsx +91 -0
  5. package/src/components/audit/audit-log-table.tsx +226 -0
  6. package/src/components/auth/accept-invitation-card.tsx +100 -0
  7. package/src/components/auth/forgot-password-form.tsx +92 -0
  8. package/src/components/auth/reset-password-form.tsx +143 -0
  9. package/src/components/auth/sign-in-form.test.tsx +140 -0
  10. package/src/components/auth/sign-in-form.tsx +509 -0
  11. package/src/components/auth/sign-up-form.tsx +123 -0
  12. package/src/components/layout/app-shell.tsx +189 -0
  13. package/src/components/layout/auth-shell.tsx +28 -0
  14. package/src/components/layout/theme-toggle.tsx +55 -0
  15. package/src/components/layout/user-menu.tsx +84 -0
  16. package/src/components/primitives/empty-state.tsx +40 -0
  17. package/src/components/primitives/page-header.tsx +27 -0
  18. package/src/components/primitives/spinner.tsx +28 -0
  19. package/src/components/profile/api-tokens-card.tsx +235 -0
  20. package/src/components/profile/change-password-form.tsx +158 -0
  21. package/src/components/profile/passkeys-card.tsx +180 -0
  22. package/src/components/profile/profile-card.tsx +33 -0
  23. package/src/components/profile/two-factor-card.tsx +226 -0
  24. package/src/components/projects/project-consents.tsx +572 -0
  25. package/src/components/projects/project-create-dialog.tsx +209 -0
  26. package/src/components/projects/project-detail-tabs.tsx +63 -0
  27. package/src/components/projects/project-email-templates.tsx +282 -0
  28. package/src/components/projects/project-notices.tsx +458 -0
  29. package/src/components/projects/project-settings.tsx +1133 -0
  30. package/src/components/projects/project-tenants.tsx +107 -0
  31. package/src/components/projects/projects-table.test.tsx +95 -0
  32. package/src/components/projects/projects-table.tsx +240 -0
  33. package/src/components/roles/role-badge.tsx +91 -0
  34. package/src/components/roles/role-select.tsx +76 -0
  35. package/src/components/tenants/tenant-create-dialog.tsx +163 -0
  36. package/src/components/tenants/tenant-detail-tabs.tsx +51 -0
  37. package/src/components/tenants/tenant-members.tsx +578 -0
  38. package/src/components/tenants/tenant-roles.test.tsx +91 -0
  39. package/src/components/tenants/tenant-roles.tsx +414 -0
  40. package/src/components/tenants/tenant-settings.tsx +385 -0
  41. package/src/components/tenants/tenants-table.test.tsx +71 -0
  42. package/src/components/tenants/tenants-table.tsx +245 -0
  43. package/src/components/ui/alert.tsx +52 -0
  44. package/src/components/ui/avatar.tsx +46 -0
  45. package/src/components/ui/badge.tsx +32 -0
  46. package/src/components/ui/button.tsx +64 -0
  47. package/src/components/ui/card.tsx +65 -0
  48. package/src/components/ui/dialog.tsx +99 -0
  49. package/src/components/ui/dropdown-menu.tsx +97 -0
  50. package/src/components/ui/field.tsx +44 -0
  51. package/src/components/ui/input.tsx +23 -0
  52. package/src/components/ui/label.tsx +19 -0
  53. package/src/components/ui/select.tsx +87 -0
  54. package/src/components/ui/separator.tsx +22 -0
  55. package/src/components/ui/skeleton.tsx +13 -0
  56. package/src/components/ui/switch.tsx +29 -0
  57. package/src/components/ui/table.tsx +87 -0
  58. package/src/components/ui/tabs.tsx +51 -0
  59. package/src/components/ui/textarea.tsx +22 -0
  60. package/src/components/ui/tooltip.tsx +27 -0
  61. package/src/components/users/user-create-dialog.tsx +267 -0
  62. package/src/components/users/user-delete-dialog.tsx +88 -0
  63. package/src/components/users/user-detail.tsx +843 -0
  64. package/src/components/users/users-table.test.tsx +97 -0
  65. package/src/components/users/users-table.tsx +382 -0
  66. package/src/context/auth-context.tsx +124 -0
  67. package/src/context/theme-context.test.tsx +78 -0
  68. package/src/context/theme-context.tsx +110 -0
  69. package/src/hooks/use-call.ts +64 -0
  70. package/src/index.ts +159 -0
  71. package/src/lib/error-message.ts +16 -0
  72. package/src/lib/utils.test.ts +61 -0
  73. package/src/lib/utils.ts +79 -0
  74. package/src/lib/webauthn.ts +36 -0
  75. package/src/styles.css +107 -0
  76. package/src/test-setup.ts +5 -0
  77. package/tailwind.preset.cjs +15 -0
@@ -0,0 +1,578 @@
1
+ import {
2
+ type Invitation,
3
+ type Member,
4
+ type RoleRow,
5
+ type TenantRole,
6
+ } from "@nexys/user-management-client";
7
+ import {
8
+ AlertCircle,
9
+ Mail,
10
+ Plus,
11
+ Trash2,
12
+ UserPlus,
13
+ Users,
14
+ X,
15
+ } from "lucide-react";
16
+ import { useMemo, useRef, useState, type FormEvent } from "react";
17
+
18
+ import { useUmClient } from "../../context/auth-context.js";
19
+ import { useCall } from "../../hooks/use-call.js";
20
+ import { errorMessage } from "../../lib/error-message.js";
21
+ import { formatRelative, initialsOf } from "../../lib/utils.js";
22
+ import { EmptyState } from "../primitives/empty-state.js";
23
+ import { TenantRoleBadge } from "../roles/role-badge.js";
24
+ import { TenantRoleSelect } from "../roles/role-select.js";
25
+ import { Alert, AlertDescription } from "../ui/alert.js";
26
+ import { Avatar, AvatarFallback } from "../ui/avatar.js";
27
+ import { Badge } from "../ui/badge.js";
28
+ import { Button } from "../ui/button.js";
29
+ import {
30
+ DropdownMenu,
31
+ DropdownMenuContent,
32
+ DropdownMenuItem,
33
+ DropdownMenuLabel,
34
+ DropdownMenuTrigger,
35
+ } from "../ui/dropdown-menu.js";
36
+ import {
37
+ Card,
38
+ CardContent,
39
+ CardDescription,
40
+ CardHeader,
41
+ CardTitle,
42
+ } from "../ui/card.js";
43
+ import { Field } from "../ui/field.js";
44
+ import { Input } from "../ui/input.js";
45
+ import {
46
+ Select,
47
+ SelectContent,
48
+ SelectItem,
49
+ SelectTrigger,
50
+ SelectValue,
51
+ } from "../ui/select.js";
52
+ import { Skeleton } from "../ui/skeleton.js";
53
+ import {
54
+ Table,
55
+ TableBody,
56
+ TableCell,
57
+ TableHead,
58
+ TableHeader,
59
+ TableRow,
60
+ } from "../ui/table.js";
61
+
62
+ export interface TenantMembersProps {
63
+ organizationId: string;
64
+ /** Allow current user to edit member roles and invites. */
65
+ canManage?: boolean;
66
+ /**
67
+ * Pick existing users from a dropdown instead of typing an email.
68
+ * Needs the system-wide user list, so superadmin/useradmin only.
69
+ */
70
+ userPicker?: boolean;
71
+ }
72
+
73
+ export const TenantMembers = ({
74
+ organizationId,
75
+ canManage = true,
76
+ userPicker = false,
77
+ }: TenantMembersProps) => {
78
+ const client = useUmClient();
79
+ const { data, error, loading, refresh } = useCall("getFullTenant", { organizationId });
80
+ const [busy, setBusy] = useState<string | null>(null);
81
+ const [actionError, setActionError] = useState<string | null>(null);
82
+
83
+ const runAction = async <O, E>(
84
+ key: string,
85
+ op: () => Promise<{ ok: true; data: O } | { ok: false; error: E }>
86
+ ) => {
87
+ setBusy(key);
88
+ setActionError(null);
89
+ const res = await op();
90
+ setBusy(null);
91
+ if (res.ok) {
92
+ await refresh();
93
+ } else {
94
+ setActionError(errorMessage(res.error as never, "Action failed."));
95
+ }
96
+ };
97
+
98
+ const setRole = (m: Member, role: TenantRole) =>
99
+ runAction(`role-${m.id}`, () =>
100
+ client.updateMemberRole({ memberId: m.id, role, organizationId })
101
+ );
102
+ const remove = (m: Member) =>
103
+ runAction(`remove-${m.id}`, () =>
104
+ client.removeMember({ memberId: m.id, organizationId })
105
+ );
106
+ const assignRole = (m: Member, roleId: string) =>
107
+ runAction(`assign-${m.id}`, () =>
108
+ client.assignMemberRole({ orgId: organizationId, memberId: m.id, roleId })
109
+ );
110
+ const unassignRole = (m: Member, roleId: string) =>
111
+ runAction(`unassign-${m.id}-${roleId}`, () =>
112
+ client.removeMemberRole({ orgId: organizationId, memberId: m.id, roleId })
113
+ );
114
+
115
+ // Custom-role definitions are fetched lazily (first menu open) —
116
+ // regular members never hit the admin-only roles endpoint.
117
+ const [allRoles, setAllRoles] = useState<RoleRow[] | null>(null);
118
+ const rolesRequested = useRef(false);
119
+ const loadRoles = async () => {
120
+ if (rolesRequested.current) return;
121
+ rolesRequested.current = true;
122
+ const res = await client.listTenantRoles({ orgId: organizationId });
123
+ if (res.ok) setAllRoles(res.data.roles);
124
+ else rolesRequested.current = false;
125
+ };
126
+
127
+ return (
128
+ <Card>
129
+ <CardHeader className="space-y-0">
130
+ <div className="flex items-center justify-between gap-3">
131
+ <div>
132
+ <CardTitle className="flex items-center gap-2">
133
+ <Users className="size-4 text-muted-foreground" />
134
+ Members
135
+ </CardTitle>
136
+ <CardDescription>
137
+ {data
138
+ ? `${data.members.length} member${data.members.length === 1 ? "" : "s"} in this tenant`
139
+ : "Manage members and tenant-level roles."}
140
+ </CardDescription>
141
+ </div>
142
+ </div>
143
+ </CardHeader>
144
+ <CardContent className="grid gap-5">
145
+ {error ? (
146
+ <Alert variant="destructive">
147
+ <AlertCircle />
148
+ <AlertDescription>{errorMessage(error)}</AlertDescription>
149
+ </Alert>
150
+ ) : null}
151
+ {actionError ? (
152
+ <Alert variant="destructive">
153
+ <AlertCircle />
154
+ <AlertDescription>{actionError}</AlertDescription>
155
+ </Alert>
156
+ ) : null}
157
+
158
+ {canManage && data ? (
159
+ <>
160
+ {userPicker ? (
161
+ <PickUserRow
162
+ organizationId={organizationId}
163
+ memberUserIds={data.members.map((m) => m.userId)}
164
+ onChanged={refresh}
165
+ />
166
+ ) : null}
167
+ <AddOrInviteRow organizationId={organizationId} onChanged={refresh} />
168
+ </>
169
+ ) : null}
170
+
171
+ <div className="overflow-hidden rounded-lg border">
172
+ <Table>
173
+ <TableHeader>
174
+ <TableRow>
175
+ <TableHead>Member</TableHead>
176
+ <TableHead>Role</TableHead>
177
+ <TableHead>Custom roles</TableHead>
178
+ <TableHead>Joined</TableHead>
179
+ {canManage && <TableHead className="text-right">Actions</TableHead>}
180
+ </TableRow>
181
+ </TableHeader>
182
+ <TableBody>
183
+ {loading ? (
184
+ Array.from({ length: 3 }).map((_, i) => (
185
+ <TableRow key={`sk-${i}`}>
186
+ <TableCell><Skeleton className="h-5 w-40" /></TableCell>
187
+ <TableCell><Skeleton className="h-5 w-20" /></TableCell>
188
+ <TableCell><Skeleton className="h-5 w-28" /></TableCell>
189
+ <TableCell><Skeleton className="h-5 w-24" /></TableCell>
190
+ {canManage && (
191
+ <TableCell className="text-right"><Skeleton className="ml-auto h-8 w-8 rounded" /></TableCell>
192
+ )}
193
+ </TableRow>
194
+ ))
195
+ ) : !data || data.members.length === 0 ? (
196
+ <TableRow>
197
+ <TableCell colSpan={canManage ? 5 : 4} className="p-0">
198
+ <EmptyState
199
+ icon={Users}
200
+ title="No members yet"
201
+ description="Invite teammates to get started."
202
+ className="border-0 rounded-none bg-transparent"
203
+ />
204
+ </TableCell>
205
+ </TableRow>
206
+ ) : (
207
+ data.members.map((m) => (
208
+ <TableRow key={m.id}>
209
+ <TableCell>
210
+ <div className="flex items-center gap-3">
211
+ <Avatar>
212
+ <AvatarFallback>
213
+ {initialsOf(m.user?.name, m.user?.email ?? m.userId)}
214
+ </AvatarFallback>
215
+ </Avatar>
216
+ <div className="grid leading-tight">
217
+ <span className="text-sm font-medium">
218
+ {m.user?.name || m.user?.email || m.userId}
219
+ </span>
220
+ <span className="text-xs text-muted-foreground">
221
+ {m.user?.email}
222
+ </span>
223
+ </div>
224
+ </div>
225
+ </TableCell>
226
+ <TableCell>
227
+ {canManage ? (
228
+ <TenantRoleSelect
229
+ value={m.role}
230
+ onChange={(next) => setRole(m, next)}
231
+ disabled={busy === `role-${m.id}`}
232
+ />
233
+ ) : (
234
+ <TenantRoleBadge role={m.role} />
235
+ )}
236
+ </TableCell>
237
+ <TableCell>
238
+ <MemberCustomRoles
239
+ member={m}
240
+ canManage={canManage}
241
+ allRoles={allRoles}
242
+ onOpenAssign={loadRoles}
243
+ onAssign={(roleId) => assignRole(m, roleId)}
244
+ onUnassign={(roleId) => unassignRole(m, roleId)}
245
+ busy={busy?.startsWith(`assign-${m.id}`) || busy?.startsWith(`unassign-${m.id}`) || false}
246
+ />
247
+ </TableCell>
248
+ <TableCell
249
+ title={m.createdAt}
250
+ className="text-sm text-muted-foreground"
251
+ >
252
+ {formatRelative(m.createdAt)}
253
+ </TableCell>
254
+ {canManage && (
255
+ <TableCell className="text-right">
256
+ <Button
257
+ variant="ghost"
258
+ size="icon"
259
+ onClick={() => remove(m)}
260
+ loading={busy === `remove-${m.id}`}
261
+ aria-label="Remove member"
262
+ >
263
+ <Trash2 className="text-destructive" />
264
+ </Button>
265
+ </TableCell>
266
+ )}
267
+ </TableRow>
268
+ ))
269
+ )}
270
+ </TableBody>
271
+ </Table>
272
+ </div>
273
+
274
+ {data ? (
275
+ <PendingInvitations invitations={data.invitations ?? []} />
276
+ ) : null}
277
+ </CardContent>
278
+ </Card>
279
+ );
280
+ };
281
+
282
+ /**
283
+ * Badges for a member's assigned custom roles, with an assign menu and
284
+ * per-badge remove when the viewer can manage the tenant.
285
+ */
286
+ const MemberCustomRoles = ({
287
+ member,
288
+ canManage,
289
+ allRoles,
290
+ onOpenAssign,
291
+ onAssign,
292
+ onUnassign,
293
+ busy,
294
+ }: {
295
+ member: Member;
296
+ canManage: boolean;
297
+ allRoles: RoleRow[] | null;
298
+ onOpenAssign: () => void;
299
+ onAssign: (roleId: string) => void;
300
+ onUnassign: (roleId: string) => void;
301
+ busy: boolean;
302
+ }) => {
303
+ const assigned = member.roles ?? [];
304
+ const assignedIds = new Set(assigned.map((r) => r.id));
305
+ const available = (allRoles ?? []).filter((r) => !assignedIds.has(r.id));
306
+
307
+ return (
308
+ <div className="flex flex-wrap items-center gap-1">
309
+ {assigned.length === 0 && !canManage ? (
310
+ <span className="text-sm text-muted-foreground">{"—"}</span>
311
+ ) : (
312
+ assigned.map((r) => (
313
+ <Badge key={r.id} variant="secondary" className="gap-1 font-mono text-xs">
314
+ {r.name}
315
+ {canManage && (
316
+ <button
317
+ type="button"
318
+ onClick={() => onUnassign(r.id)}
319
+ disabled={busy}
320
+ aria-label={`Remove role ${r.name}`}
321
+ className="rounded-full opacity-60 transition-opacity hover:opacity-100 disabled:pointer-events-none"
322
+ >
323
+ <X className="size-3" />
324
+ </button>
325
+ )}
326
+ </Badge>
327
+ ))
328
+ )}
329
+ {canManage && (
330
+ <DropdownMenu>
331
+ <DropdownMenuTrigger asChild>
332
+ <Button
333
+ variant="ghost"
334
+ size="icon"
335
+ className="size-6"
336
+ onClick={onOpenAssign}
337
+ disabled={busy}
338
+ aria-label="Assign role"
339
+ >
340
+ <Plus className="size-3.5" />
341
+ </Button>
342
+ </DropdownMenuTrigger>
343
+ <DropdownMenuContent align="start">
344
+ <DropdownMenuLabel>Assign role</DropdownMenuLabel>
345
+ {allRoles === null ? (
346
+ <DropdownMenuItem disabled>Loading roles…</DropdownMenuItem>
347
+ ) : available.length === 0 ? (
348
+ <DropdownMenuItem disabled>
349
+ {allRoles.length === 0
350
+ ? "No roles defined — create one in the Roles tab"
351
+ : "All roles assigned"}
352
+ </DropdownMenuItem>
353
+ ) : (
354
+ available.map((r) => (
355
+ <DropdownMenuItem key={r.id} onSelect={() => onAssign(r.id)}>
356
+ {r.name}
357
+ </DropdownMenuItem>
358
+ ))
359
+ )}
360
+ </DropdownMenuContent>
361
+ </DropdownMenu>
362
+ )}
363
+ </div>
364
+ );
365
+ };
366
+
367
+ const AddOrInviteRow = ({
368
+ organizationId,
369
+ onChanged,
370
+ }: {
371
+ organizationId: string;
372
+ onChanged: () => void;
373
+ }) => {
374
+ const client = useUmClient();
375
+ const [email, setEmail] = useState("");
376
+ const [role, setRole] = useState<TenantRole>("member");
377
+ const [busy, setBusy] = useState<"add" | "invite" | null>(null);
378
+ const [error, setError] = useState<string | null>(null);
379
+
380
+ // "Add" assigns an existing user directly; "Invite" emails a join
381
+ // link for people without an account yet.
382
+ const run = async (kind: "add" | "invite") => {
383
+ setBusy(kind);
384
+ setError(null);
385
+ const input = { email: email.trim(), role, organizationId };
386
+ const res =
387
+ kind === "add"
388
+ ? await client.addMember(input)
389
+ : await client.inviteMember(input);
390
+ setBusy(null);
391
+ if (res.ok) {
392
+ setEmail("");
393
+ onChanged();
394
+ } else {
395
+ setError(
396
+ errorMessage(
397
+ res.error as never,
398
+ kind === "add" ? "Couldn't add member." : "Couldn't send invitation."
399
+ )
400
+ );
401
+ }
402
+ };
403
+
404
+ const submit = (e: FormEvent) => {
405
+ e.preventDefault();
406
+ void run("add");
407
+ };
408
+
409
+ return (
410
+ <form
411
+ onSubmit={submit}
412
+ className="grid items-end gap-3 rounded-lg border border-dashed bg-muted/30 p-4 sm:grid-cols-[1fr_auto_auto_auto]"
413
+ >
414
+ <Field label="Invite someone" htmlFor="invite-email">
415
+ <div className="relative">
416
+ <Mail className="pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-muted-foreground" />
417
+ <Input
418
+ id="invite-email"
419
+ type="email"
420
+ required
421
+ value={email}
422
+ onChange={(e) => setEmail(e.target.value)}
423
+ className="pl-9"
424
+ placeholder="teammate@example.com"
425
+ />
426
+ </div>
427
+ </Field>
428
+ <Field label="Role" htmlFor="invite-role">
429
+ <TenantRoleSelect value={role} onChange={setRole} />
430
+ </Field>
431
+ <Button type="submit" loading={busy === "add"} disabled={!email.trim() || busy !== null}>
432
+ <UserPlus />
433
+ Add member
434
+ </Button>
435
+ <Button
436
+ type="button"
437
+ variant="outline"
438
+ loading={busy === "invite"}
439
+ disabled={!email.trim() || busy !== null}
440
+ onClick={() => void run("invite")}
441
+ >
442
+ <Mail />
443
+ Send invite
444
+ </Button>
445
+ {error ? (
446
+ <div className="sm:col-span-4">
447
+ <Alert variant="destructive">
448
+ <AlertCircle />
449
+ <AlertDescription>{error}</AlertDescription>
450
+ </Alert>
451
+ </div>
452
+ ) : null}
453
+ </form>
454
+ );
455
+ };
456
+
457
+ /**
458
+ * Superadmin variant of the add row: pick any existing user from a
459
+ * dropdown and add them directly — no invitation round-trip.
460
+ */
461
+ const PickUserRow = ({
462
+ organizationId,
463
+ memberUserIds,
464
+ onChanged,
465
+ }: {
466
+ organizationId: string;
467
+ memberUserIds: string[];
468
+ onChanged: () => void;
469
+ }) => {
470
+ const client = useUmClient();
471
+ const users = useCall("adminListUsers", { limit: 500 });
472
+ const [userId, setUserId] = useState("");
473
+ const [role, setRole] = useState<TenantRole>("member");
474
+ const [loading, setLoading] = useState(false);
475
+ const [error, setError] = useState<string | null>(null);
476
+
477
+ const candidates = useMemo(() => {
478
+ const members = new Set(memberUserIds);
479
+ return (users.data?.rows ?? []).filter(
480
+ (u) => !members.has(u.id) && u.type !== "service"
481
+ );
482
+ }, [users.data, memberUserIds]);
483
+
484
+ const submit = async (e: FormEvent) => {
485
+ e.preventDefault();
486
+ if (!userId) return;
487
+ setLoading(true);
488
+ setError(null);
489
+ const res = await client.addMember({ organizationId, userId, role });
490
+ setLoading(false);
491
+ if (res.ok) {
492
+ setUserId("");
493
+ setRole("member");
494
+ onChanged();
495
+ } else {
496
+ setError(errorMessage(res.error, "Couldn't add member."));
497
+ }
498
+ };
499
+
500
+ return (
501
+ <form
502
+ onSubmit={submit}
503
+ className="grid items-end gap-3 rounded-lg border border-dashed bg-muted/30 p-4 sm:grid-cols-[1fr_auto_auto]"
504
+ >
505
+ <Field label="Add an existing user" htmlFor="pick-user">
506
+ <Select value={userId} onValueChange={setUserId}>
507
+ <SelectTrigger id="pick-user" className="h-9">
508
+ <SelectValue
509
+ placeholder={users.loading ? "Loading users…" : "Pick a user…"}
510
+ />
511
+ </SelectTrigger>
512
+ <SelectContent>
513
+ {candidates.map((u) => (
514
+ <SelectItem key={u.id} value={u.id}>
515
+ {u.name ? `${u.name} (${u.email})` : u.email}
516
+ </SelectItem>
517
+ ))}
518
+ </SelectContent>
519
+ </Select>
520
+ </Field>
521
+ <Field label="Role" htmlFor="pick-user-role">
522
+ <TenantRoleSelect value={role} onChange={setRole} />
523
+ </Field>
524
+ <Button type="submit" loading={loading} disabled={!userId || loading}>
525
+ <UserPlus />
526
+ Add member
527
+ </Button>
528
+ {error ? (
529
+ <div className="sm:col-span-3">
530
+ <Alert variant="destructive">
531
+ <AlertCircle />
532
+ <AlertDescription>{error}</AlertDescription>
533
+ </Alert>
534
+ </div>
535
+ ) : null}
536
+ </form>
537
+ );
538
+ };
539
+
540
+ const PendingInvitations = ({ invitations }: { invitations: Invitation[] }) => {
541
+ const open = invitations.filter(
542
+ (i) => i.status === "pending" || i.status === "expired"
543
+ );
544
+ if (open.length === 0) return null;
545
+ return (
546
+ <div className="grid gap-2">
547
+ <p className="text-sm font-medium text-muted-foreground">
548
+ Pending invitations
549
+ </p>
550
+ <div className="overflow-hidden rounded-lg border">
551
+ <Table>
552
+ <TableBody>
553
+ {open.map((i) => (
554
+ <TableRow key={i.id}>
555
+ <TableCell>
556
+ <div className="flex items-center gap-2">
557
+ <Mail className="size-4 text-muted-foreground" />
558
+ <span className="text-sm">{i.email}</span>
559
+ </div>
560
+ </TableCell>
561
+ <TableCell>
562
+ <TenantRoleBadge role={i.role} />
563
+ </TableCell>
564
+ <TableCell className="text-right text-xs text-muted-foreground">
565
+ {i.status === "expired"
566
+ ? "Expired"
567
+ : i.expiresAt
568
+ ? `Expires ${formatRelative(i.expiresAt)}`
569
+ : "Pending"}
570
+ </TableCell>
571
+ </TableRow>
572
+ ))}
573
+ </TableBody>
574
+ </Table>
575
+ </div>
576
+ </div>
577
+ );
578
+ };
@@ -0,0 +1,91 @@
1
+ /// <reference lib="dom" />
2
+ import { afterEach, describe, expect, test } from "bun:test";
3
+
4
+ import { fireEvent, render, screen, waitFor } from "@testing-library/react";
5
+
6
+ import { mockRpc, reply } from "@nexys/user-management-client/testing";
7
+
8
+ import { AuthProvider } from "../../context/auth-context.js";
9
+ import { TenantRoles } from "./tenant-roles.js";
10
+
11
+ const ROLES = [
12
+ {
13
+ id: "r1",
14
+ name: "billing-admin",
15
+ description: "Manages billing",
16
+ permissions: ["invoices:read", "invoices:write"],
17
+ createdAt: "2026-01-01T00:00:00Z",
18
+ updatedAt: "2026-01-01T00:00:00Z",
19
+ },
20
+ ];
21
+
22
+ afterEach(() => {
23
+ document.body.innerHTML = "";
24
+ });
25
+
26
+ describe("<TenantRoles />", () => {
27
+ test("renders roles with their permission badges", async () => {
28
+ const rpc = mockRpc((p, input) => {
29
+ if (p === "me") {
30
+ return reply({ code: "unauth" }, 401);
31
+ }
32
+ if (p === "listTenantRoles") {
33
+ return reply({ roles: ROLES });
34
+ }
35
+ return reply({ error: "not_found" }, 404);
36
+ });
37
+ const client = rpc.client;
38
+
39
+ render(
40
+ <AuthProvider client={client} refreshIntervalMs={0}>
41
+ <TenantRoles organizationId="org-1" />
42
+ </AuthProvider>
43
+ );
44
+
45
+ await waitFor(() => {
46
+ expect(screen.getByText("billing-admin")).toBeTruthy();
47
+ });
48
+ expect(screen.getByText("invoices:read")).toBeTruthy();
49
+ expect(screen.getByText("invoices:write")).toBeTruthy();
50
+ expect(screen.getByText("Manages billing")).toBeTruthy();
51
+ });
52
+
53
+ test("creates a role with comma-separated permissions parsed to a list", async () => {
54
+ let createdBody: unknown = null;
55
+ const rpc = mockRpc((p, input) => {
56
+ if (p === "me") {
57
+ return reply({ code: "unauth" }, 401);
58
+ }
59
+ if (p === "createTenantRole") {
60
+ createdBody = input;
61
+ return reply({ ...ROLES[0], id: "r2", name: "support" }, 201);
62
+ }
63
+ if (p === "listTenantRoles") {
64
+ return reply({ roles: [] });
65
+ }
66
+ return reply({ error: "not_found" }, 404);
67
+ });
68
+ const client = rpc.client;
69
+
70
+ render(
71
+ <AuthProvider client={client} refreshIntervalMs={0}>
72
+ <TenantRoles organizationId="org-1" canManage />
73
+ </AuthProvider>
74
+ );
75
+
76
+ fireEvent.change(screen.getByLabelText(/role name/i), {
77
+ target: { value: "support" },
78
+ });
79
+ fireEvent.change(screen.getByLabelText(/permissions/i), {
80
+ target: { value: "tickets:read, tickets:write" },
81
+ });
82
+ fireEvent.click(screen.getByRole("button", { name: /add role/i }));
83
+
84
+ await waitFor(() => expect(createdBody).not.toBeNull());
85
+ expect(createdBody).toEqual({
86
+ orgId: "org-1",
87
+ name: "support",
88
+ permissions: ["tickets:read", "tickets:write"],
89
+ });
90
+ });
91
+ });