@langwatch/server 3.1.0-beta.3 → 3.1.0-beta.5

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 (119) hide show
  1. package/langwatch/ee/admin/ImpersonationBanner.tsx +61 -0
  2. package/langwatch/ee/admin/ImpersonationSwitchBackMenuItem.tsx +30 -0
  3. package/langwatch/ee/admin/__tests__/ImpersonationBanner.integration.test.tsx +82 -0
  4. package/langwatch/ee/admin/__tests__/impersonation.service.unit.test.ts +231 -0
  5. package/langwatch/ee/admin/backoffice/BackofficeTable.tsx +200 -0
  6. package/langwatch/ee/admin/backoffice/__tests__/adminClient.unit.test.ts +147 -0
  7. package/langwatch/ee/admin/backoffice/__tests__/dateInputToISO.unit.test.ts +42 -0
  8. package/langwatch/ee/admin/backoffice/__tests__/userVisibility.unit.test.ts +174 -0
  9. package/langwatch/ee/admin/backoffice/adminClient.ts +114 -0
  10. package/langwatch/ee/admin/backoffice/resources/OrganizationFeaturesView.tsx +373 -0
  11. package/langwatch/ee/admin/backoffice/resources/OrganizationsView.tsx +677 -0
  12. package/langwatch/ee/admin/backoffice/resources/ProjectsView.tsx +647 -0
  13. package/langwatch/ee/admin/backoffice/resources/SubscriptionsView.tsx +628 -0
  14. package/langwatch/ee/admin/backoffice/resources/UsersView.tsx +556 -0
  15. package/langwatch/ee/admin/backoffice/useAdminResource.ts +104 -0
  16. package/langwatch/ee/admin/backoffice/userVisibility.ts +105 -0
  17. package/langwatch/ee/admin/impersonation.service.ts +170 -0
  18. package/langwatch/ee/admin/isAdmin.ts +9 -0
  19. package/langwatch/ee/admin/routes/admin.ts +531 -0
  20. package/langwatch/ee/admin/safeSelects.ts +64 -0
  21. package/langwatch/ee/billing/__tests__/customerService.unit.test.ts +183 -0
  22. package/langwatch/ee/billing/__tests__/growthSeatEvent.unit.test.ts +213 -0
  23. package/langwatch/ee/billing/__tests__/licensePurchaseHandler.unit.test.ts +250 -0
  24. package/langwatch/ee/billing/__tests__/notification.service.unit.test.ts +768 -0
  25. package/langwatch/ee/billing/__tests__/planLimits.unit.test.ts +19 -0
  26. package/langwatch/ee/billing/__tests__/planProvider.unit.test.ts +440 -0
  27. package/langwatch/ee/billing/__tests__/planTypes.unit.test.ts +32 -0
  28. package/langwatch/ee/billing/__tests__/pricing.unit.test.ts +54 -0
  29. package/langwatch/ee/billing/__tests__/seatEventSubscription.unit.test.ts +717 -0
  30. package/langwatch/ee/billing/__tests__/stripe.integration.test.ts +344 -0
  31. package/langwatch/ee/billing/__tests__/stripePrices.types.unit.test.ts +27 -0
  32. package/langwatch/ee/billing/__tests__/stripePricesLoader.unit.test.ts +72 -0
  33. package/langwatch/ee/billing/__tests__/subscription.service.unit.test.ts +730 -0
  34. package/langwatch/ee/billing/__tests__/subscriptionItemCalculator.unit.test.ts +176 -0
  35. package/langwatch/ee/billing/__tests__/usage-limit.service.unit.test.ts +706 -0
  36. package/langwatch/ee/billing/__tests__/usageReportingService.integration.test.ts +421 -0
  37. package/langwatch/ee/billing/__tests__/usageReportingService.unit.test.ts +515 -0
  38. package/langwatch/ee/billing/__tests__/webhookService.unit.test.ts +958 -0
  39. package/langwatch/ee/billing/currencyRouter.ts +18 -0
  40. package/langwatch/ee/billing/errors.ts +129 -0
  41. package/langwatch/ee/billing/index.ts +67 -0
  42. package/langwatch/ee/billing/middleware.ts +17 -0
  43. package/langwatch/ee/billing/notifications/notification.service.ts +651 -0
  44. package/langwatch/ee/billing/notifications/repositories/notification.repository.ts +51 -0
  45. package/langwatch/ee/billing/notifications/types.ts +9 -0
  46. package/langwatch/ee/billing/notifications/usage-limit.service.ts +622 -0
  47. package/langwatch/ee/billing/nurturing/hooks/activityTracking.ts +90 -0
  48. package/langwatch/ee/billing/nurturing/hooks/activityTracking.unit.test.ts +237 -0
  49. package/langwatch/ee/billing/nurturing/hooks/featureAdoption.ts +120 -0
  50. package/langwatch/ee/billing/nurturing/hooks/featureAdoption.unit.test.ts +324 -0
  51. package/langwatch/ee/billing/nurturing/hooks/index.ts +17 -0
  52. package/langwatch/ee/billing/nurturing/hooks/productInterest.ts +68 -0
  53. package/langwatch/ee/billing/nurturing/hooks/productInterest.unit.test.ts +138 -0
  54. package/langwatch/ee/billing/nurturing/hooks/promptCreation.integration.test.ts +288 -0
  55. package/langwatch/ee/billing/nurturing/hooks/promptCreation.ts +131 -0
  56. package/langwatch/ee/billing/nurturing/hooks/promptCreation.unit.test.ts +134 -0
  57. package/langwatch/ee/billing/nurturing/hooks/signupIdentification.ts +101 -0
  58. package/langwatch/ee/billing/nurturing/hooks/signupIdentification.unit.test.ts +317 -0
  59. package/langwatch/ee/billing/nurturing/hooks/subscriptionSync.ts +49 -0
  60. package/langwatch/ee/billing/nurturing/hooks/subscriptionSync.unit.test.ts +170 -0
  61. package/langwatch/ee/billing/nurturing/hooks/userSync.ts +143 -0
  62. package/langwatch/ee/billing/nurturing/hooks/userSync.unit.test.ts +307 -0
  63. package/langwatch/ee/billing/nurturing/nurturing.service.ts +179 -0
  64. package/langwatch/ee/billing/nurturing/nurturing.service.unit.test.ts +266 -0
  65. package/langwatch/ee/billing/nurturing/nurturing.service.wiring.unit.test.ts +109 -0
  66. package/langwatch/ee/billing/nurturing/types.ts +125 -0
  67. package/langwatch/ee/billing/planLimits.ts +190 -0
  68. package/langwatch/ee/billing/planProvider.ts +119 -0
  69. package/langwatch/ee/billing/planTypes.ts +53 -0
  70. package/langwatch/ee/billing/pricing.ts +57 -0
  71. package/langwatch/ee/billing/services/billableEventsQuery.ts +248 -0
  72. package/langwatch/ee/billing/services/customerService.ts +90 -0
  73. package/langwatch/ee/billing/services/licensePurchaseHandler.ts +73 -0
  74. package/langwatch/ee/billing/services/seatEventSubscription.ts +351 -0
  75. package/langwatch/ee/billing/services/seatSyncService.ts +34 -0
  76. package/langwatch/ee/billing/services/subscription.repository.ts +203 -0
  77. package/langwatch/ee/billing/services/subscription.service.ts +549 -0
  78. package/langwatch/ee/billing/services/subscriptionItemCalculator.ts +249 -0
  79. package/langwatch/ee/billing/services/usageReportingService.ts +301 -0
  80. package/langwatch/ee/billing/services/webhookService.ts +858 -0
  81. package/langwatch/ee/billing/stripe/stripeCatalog.json +1781 -0
  82. package/langwatch/ee/billing/stripe/stripeClient.ts +13 -0
  83. package/langwatch/ee/billing/stripe/stripePriceCatalog.ts +70 -0
  84. package/langwatch/ee/billing/stripe/stripePrices.types.ts +118 -0
  85. package/langwatch/ee/billing/subscriptionRouter.ts +202 -0
  86. package/langwatch/ee/billing/types.ts +102 -0
  87. package/langwatch/ee/billing/utils/currency.ts +99 -0
  88. package/langwatch/ee/billing/utils/growthSeatEvent.ts +137 -0
  89. package/langwatch/ee/licensing/__tests__/constants.unit.test.ts +56 -0
  90. package/langwatch/ee/licensing/__tests__/defaults.unit.test.ts +192 -0
  91. package/langwatch/ee/licensing/__tests__/fixtures/testKeys.ts +86 -0
  92. package/langwatch/ee/licensing/__tests__/fixtures/testLicenses.ts +92 -0
  93. package/langwatch/ee/licensing/__tests__/licenseGenerationService.unit.test.ts +232 -0
  94. package/langwatch/ee/licensing/__tests__/licenseHandler.integration.test.ts +419 -0
  95. package/langwatch/ee/licensing/__tests__/planMapping.unit.test.ts +195 -0
  96. package/langwatch/ee/licensing/__tests__/planTemplates.unit.test.ts +193 -0
  97. package/langwatch/ee/licensing/__tests__/signing.unit.test.ts +164 -0
  98. package/langwatch/ee/licensing/__tests__/validation.unit.test.ts +281 -0
  99. package/langwatch/ee/licensing/client.ts +29 -0
  100. package/langwatch/ee/licensing/constants.ts +195 -0
  101. package/langwatch/ee/licensing/defaults.ts +55 -0
  102. package/langwatch/ee/licensing/errors.ts +11 -0
  103. package/langwatch/ee/licensing/index.ts +52 -0
  104. package/langwatch/ee/licensing/licenseGenerationService.ts +87 -0
  105. package/langwatch/ee/licensing/licenseHandler.ts +308 -0
  106. package/langwatch/ee/licensing/planInfo.ts +46 -0
  107. package/langwatch/ee/licensing/planMapping.ts +37 -0
  108. package/langwatch/ee/licensing/planTemplates.ts +109 -0
  109. package/langwatch/ee/licensing/server.ts +43 -0
  110. package/langwatch/ee/licensing/signing.ts +43 -0
  111. package/langwatch/ee/licensing/types.ts +156 -0
  112. package/langwatch/ee/licensing/validation.ts +107 -0
  113. package/langwatch/ee/managed-providers/ManagedModelProviderAlert.tsx +29 -0
  114. package/langwatch/ee/managed-providers/managedBedrockConfig.ts +226 -0
  115. package/langwatch/ee/saas/ExtraFooterComponents.tsx +169 -0
  116. package/langwatch/package.json +1 -1
  117. package/langwatch_nlp/uv.lock +179 -5
  118. package/package.json +1 -1
  119. package/packages/server/dist/cli.cjs +192 -142
@@ -0,0 +1,556 @@
1
+ import {
2
+ Badge,
3
+ Box,
4
+ Button,
5
+ Field,
6
+ HStack,
7
+ Input,
8
+ Link as ChakraLink,
9
+ Spacer,
10
+ Table,
11
+ Text,
12
+ Textarea,
13
+ VStack,
14
+ Wrap,
15
+ } from "@chakra-ui/react";
16
+ import { MoreVertical, Pencil, UserCheck } from "lucide-react";
17
+ import { useEffect, useState } from "react";
18
+ import { useDebounce } from "use-debounce";
19
+ import NextLink from "~/utils/compat/next-link";
20
+ import { Dialog } from "~/components/ui/dialog";
21
+ import { Drawer } from "~/components/ui/drawer";
22
+ import { Menu } from "~/components/ui/menu";
23
+ import { Switch } from "~/components/ui/switch";
24
+ import { toaster } from "~/components/ui/toaster";
25
+ import {
26
+ BackofficeTable,
27
+ EmptyCell,
28
+ formatDate,
29
+ formatDateTime,
30
+ } from "../BackofficeTable";
31
+ import { impersonateUser } from "../adminClient";
32
+ import {
33
+ useAdminList,
34
+ useAdminUpdate,
35
+ } from "../useAdminResource";
36
+
37
+ interface OrgRef {
38
+ id: string;
39
+ name: string;
40
+ }
41
+ interface ProjectRef {
42
+ id: string;
43
+ name: string;
44
+ slug: string;
45
+ }
46
+
47
+ interface AdminUser {
48
+ id: string;
49
+ name: string | null;
50
+ email: string | null;
51
+ image: string | null;
52
+ emailVerified: boolean;
53
+ pendingSsoSetup: boolean | null;
54
+ createdAt: string;
55
+ lastLoginAt: string | null;
56
+ deactivatedAt: string | null;
57
+ /**
58
+ * Deduped `{id, name}` list the server maps from orgMemberships — lets the
59
+ * table render each org as its own clickable chip without re-parsing a
60
+ * joined string.
61
+ */
62
+ organizations: OrgRef[];
63
+ /** Same treatment for projects (through org.teams → team.projects). */
64
+ projects: ProjectRef[];
65
+ }
66
+
67
+ const PAGE_SIZE = 25;
68
+
69
+ export default function UsersView() {
70
+ const [page, setPage] = useState(1);
71
+ const [search, setSearch] = useState("");
72
+ const [debouncedSearch] = useDebounce(search, 300);
73
+ const [editing, setEditing] = useState<AdminUser | null>(null);
74
+ // Impersonation is driven by a dialog opened from the row-action menu so
75
+ // there's exactly one Dialog instance at a time — avoids the "mount a
76
+ // Dialog per row" smell from the previous ImpersonateButton component.
77
+ const [impersonating, setImpersonating] = useState<AdminUser | null>(null);
78
+
79
+ const list = useAdminList<AdminUser>("user", {
80
+ pagination: { page, perPage: PAGE_SIZE },
81
+ sort: { field: "createdAt", order: "DESC" },
82
+ filter: debouncedSearch ? { query: debouncedSearch } : {},
83
+ });
84
+
85
+ return (
86
+ <>
87
+ <BackofficeTable
88
+ title="Users"
89
+ searchValue={search}
90
+ onSearchChange={(v) => {
91
+ setSearch(v);
92
+ setPage(1);
93
+ }}
94
+ searchPlaceholder="Search by ID, name, email, org, or project"
95
+ isLoading={list.isLoading}
96
+ isFetching={list.isFetching}
97
+ error={list.error}
98
+ pagination={{
99
+ page,
100
+ perPage: PAGE_SIZE,
101
+ total: list.data?.total ?? 0,
102
+ onPageChange: setPage,
103
+ }}
104
+ >
105
+ <Table.Root variant="line" size="md" width="full">
106
+ <Table.Header>
107
+ <Table.Row>
108
+ <Table.ColumnHeader>ID</Table.ColumnHeader>
109
+ <Table.ColumnHeader>Name</Table.ColumnHeader>
110
+ <Table.ColumnHeader>Email</Table.ColumnHeader>
111
+ <Table.ColumnHeader>Organizations</Table.ColumnHeader>
112
+ <Table.ColumnHeader>Projects</Table.ColumnHeader>
113
+ <Table.ColumnHeader>Created</Table.ColumnHeader>
114
+ <Table.ColumnHeader>Last login</Table.ColumnHeader>
115
+ <Table.ColumnHeader>Status</Table.ColumnHeader>
116
+ <Table.ColumnHeader width="60px" textAlign="right" />
117
+ </Table.Row>
118
+ </Table.Header>
119
+ <Table.Body>
120
+ {list.data?.data.length === 0 && (
121
+ <Table.Row>
122
+ <Table.Cell colSpan={9}>
123
+ <Text color="fg.muted" textAlign="center" paddingY={6}>
124
+ No users match your search.
125
+ </Text>
126
+ </Table.Cell>
127
+ </Table.Row>
128
+ )}
129
+ {list.data?.data.map((user) => (
130
+ <Table.Row key={user.id}>
131
+ <Table.Cell
132
+ fontFamily="mono"
133
+ fontSize="xs"
134
+ color="fg.muted"
135
+ maxW="110px"
136
+ overflow="hidden"
137
+ textOverflow="ellipsis"
138
+ whiteSpace="nowrap"
139
+ title={user.id}
140
+ >
141
+ {user.id}
142
+ </Table.Cell>
143
+ <Table.Cell>{user.name ?? <EmptyCell />}</Table.Cell>
144
+ <Table.Cell>{user.email ?? <EmptyCell />}</Table.Cell>
145
+ <Table.Cell>
146
+ <RefChipList
147
+ refs={user.organizations}
148
+ resource="organizations"
149
+ />
150
+ </Table.Cell>
151
+ <Table.Cell>
152
+ <RefChipList refs={user.projects} resource="projects" />
153
+ </Table.Cell>
154
+ <Table.Cell>{formatDate(user.createdAt)}</Table.Cell>
155
+ <Table.Cell>{formatDateTime(user.lastLoginAt)}</Table.Cell>
156
+ <Table.Cell>
157
+ {user.deactivatedAt ? (
158
+ <Badge colorPalette="red" size="sm">
159
+ Deactivated
160
+ </Badge>
161
+ ) : user.pendingSsoSetup ? (
162
+ <Badge colorPalette="yellow" size="sm">
163
+ Pending SSO
164
+ </Badge>
165
+ ) : user.emailVerified ? (
166
+ <Badge colorPalette="green" size="sm">
167
+ Active
168
+ </Badge>
169
+ ) : (
170
+ <Badge colorPalette="gray" size="sm">
171
+ Unverified
172
+ </Badge>
173
+ )}
174
+ </Table.Cell>
175
+ <Table.Cell textAlign="right">
176
+ <Box
177
+ width="full"
178
+ height="full"
179
+ display="flex"
180
+ justifyContent="end"
181
+ >
182
+ <Menu.Root>
183
+ <Menu.Trigger>
184
+ <MoreVertical size={16} />
185
+ </Menu.Trigger>
186
+ <Menu.Content>
187
+ <Menu.Item
188
+ value="edit"
189
+ onClick={() => setEditing(user)}
190
+ >
191
+ <Pencil size={16} />
192
+ Edit
193
+ </Menu.Item>
194
+ {!user.deactivatedAt && (
195
+ <Menu.Item
196
+ value="impersonate"
197
+ onClick={() => setImpersonating(user)}
198
+ >
199
+ <UserCheck size={16} />
200
+ Impersonate
201
+ </Menu.Item>
202
+ )}
203
+ </Menu.Content>
204
+ </Menu.Root>
205
+ </Box>
206
+ </Table.Cell>
207
+ </Table.Row>
208
+ ))}
209
+ </Table.Body>
210
+ </Table.Root>
211
+ </BackofficeTable>
212
+
213
+ <UserEditDrawer user={editing} onClose={() => setEditing(null)} />
214
+ <ImpersonateDialog
215
+ user={impersonating}
216
+ onClose={() => setImpersonating(null)}
217
+ />
218
+ </>
219
+ );
220
+ }
221
+
222
+ function ImpersonateDialog({
223
+ user,
224
+ onClose,
225
+ }: {
226
+ user: AdminUser | null;
227
+ onClose: () => void;
228
+ }) {
229
+ const [reason, setReason] = useState("");
230
+ const [loading, setLoading] = useState(false);
231
+
232
+ // Re-seed the reason on every new target user — prevents leaking one
233
+ // reason across multiple impersonation attempts.
234
+ useEffect(() => {
235
+ if (user) setReason("");
236
+ }, [user]);
237
+
238
+ const submit = async () => {
239
+ if (!user) return;
240
+ const trimmed = reason.trim();
241
+ if (!trimmed) {
242
+ toaster.create({
243
+ title: "Reason is required",
244
+ description: "Saved to the audit log alongside the impersonation.",
245
+ type: "error",
246
+ duration: 3000,
247
+ meta: { closable: true },
248
+ });
249
+ return;
250
+ }
251
+ setLoading(true);
252
+ try {
253
+ await impersonateUser({
254
+ userIdToImpersonate: user.id,
255
+ reason: trimmed,
256
+ });
257
+ window.location.href = "/";
258
+ } catch (err) {
259
+ toaster.create({
260
+ title: "Impersonation failed",
261
+ description: err instanceof Error ? err.message : String(err),
262
+ type: "error",
263
+ duration: 5000,
264
+ meta: { closable: true },
265
+ });
266
+ setLoading(false);
267
+ }
268
+ };
269
+
270
+ return (
271
+ <Dialog.Root
272
+ open={!!user}
273
+ onOpenChange={({ open }) => {
274
+ if (!open && !loading) onClose();
275
+ }}
276
+ >
277
+ <Dialog.Content>
278
+ <Dialog.Header>
279
+ <Dialog.Title>Impersonate user</Dialog.Title>
280
+ </Dialog.Header>
281
+ <Dialog.CloseTrigger disabled={loading} />
282
+ <Dialog.Body>
283
+ <VStack gap={3} align="stretch">
284
+ <Text fontSize="sm" color="fg.muted">
285
+ You will sign in as{" "}
286
+ <Text as="span" fontWeight="semibold" color="fg">
287
+ {user?.name ?? user?.email ?? user?.id}
288
+ </Text>
289
+ . The reason below is saved to the audit log.
290
+ </Text>
291
+ <Field.Root required>
292
+ <Field.Label>Reason</Field.Label>
293
+ <Textarea
294
+ rows={3}
295
+ value={reason}
296
+ onChange={(e) => setReason(e.target.value)}
297
+ placeholder="e.g. Debugging a stuck trace reported by support ticket #…"
298
+ disabled={loading}
299
+ />
300
+ </Field.Root>
301
+ </VStack>
302
+ </Dialog.Body>
303
+ <Dialog.Footer>
304
+ <HStack width="full">
305
+ <Spacer />
306
+ <Button variant="ghost" onClick={onClose} disabled={loading}>
307
+ Cancel
308
+ </Button>
309
+ <Button onClick={submit} loading={loading} colorPalette="orange">
310
+ Impersonate
311
+ </Button>
312
+ </HStack>
313
+ </Dialog.Footer>
314
+ </Dialog.Content>
315
+ </Dialog.Root>
316
+ );
317
+ }
318
+
319
+ function UserEditDrawer({
320
+ user,
321
+ onClose,
322
+ }: {
323
+ user: AdminUser | null;
324
+ onClose: () => void;
325
+ }) {
326
+ const update = useAdminUpdate<AdminUser>("user");
327
+ const [name, setName] = useState("");
328
+ const [email, setEmail] = useState("");
329
+ const [image, setImage] = useState("");
330
+ const [emailVerified, setEmailVerified] = useState(false);
331
+ const [pendingSsoSetup, setPendingSsoSetup] = useState(false);
332
+ const [deactivate, setDeactivate] = useState(false);
333
+
334
+ // Re-seed the form every time the drawer opens on a different user.
335
+ useEffect(() => {
336
+ if (!user) return;
337
+ setName(user.name ?? "");
338
+ setEmail(user.email ?? "");
339
+ setImage(user.image ?? "");
340
+ setEmailVerified(!!user.emailVerified);
341
+ setPendingSsoSetup(!!user.pendingSsoSetup);
342
+ setDeactivate(!!user.deactivatedAt);
343
+ }, [user]);
344
+
345
+ const handleSave = () => {
346
+ if (!user) return;
347
+ const data: Record<string, unknown> = {};
348
+ if (name !== (user.name ?? "")) data.name = name;
349
+ if (email !== (user.email ?? "")) data.email = email;
350
+ if (image !== (user.image ?? "")) data.image = image || null;
351
+ if (emailVerified !== !!user.emailVerified) {
352
+ data.emailVerified = emailVerified;
353
+ }
354
+ if (pendingSsoSetup !== !!user.pendingSsoSetup) {
355
+ data.pendingSsoSetup = pendingSsoSetup;
356
+ }
357
+ const currentlyDeactivated = !!user.deactivatedAt;
358
+ if (deactivate !== currentlyDeactivated) {
359
+ data.deactivatedAt = deactivate ? new Date().toISOString() : null;
360
+ }
361
+ if (Object.keys(data).length === 0) {
362
+ onClose();
363
+ return;
364
+ }
365
+ update.mutate(
366
+ { id: user.id, data },
367
+ {
368
+ onSuccess: () => {
369
+ toaster.create({
370
+ title: "User updated",
371
+ type: "success",
372
+ duration: 3000,
373
+ meta: { closable: true },
374
+ });
375
+ onClose();
376
+ },
377
+ onError: (err) =>
378
+ toaster.create({
379
+ title: "Update failed",
380
+ description: err.message,
381
+ type: "error",
382
+ duration: 5000,
383
+ meta: { closable: true },
384
+ }),
385
+ },
386
+ );
387
+ };
388
+
389
+ return (
390
+ <Drawer.Root
391
+ open={!!user}
392
+ onOpenChange={({ open }) => {
393
+ if (!open) onClose();
394
+ }}
395
+ size="md"
396
+ >
397
+ <Drawer.Content>
398
+ <Drawer.Header>
399
+ <Drawer.Title>Edit User</Drawer.Title>
400
+ </Drawer.Header>
401
+ <Drawer.CloseTrigger />
402
+ <Drawer.Body>
403
+ {user && (
404
+ <VStack gap={4} align="stretch">
405
+ <Field.Root>
406
+ <Field.Label>Name</Field.Label>
407
+ <Input
408
+ value={name}
409
+ onChange={(e) => setName(e.target.value)}
410
+ />
411
+ </Field.Root>
412
+ <Field.Root>
413
+ <Field.Label>Email</Field.Label>
414
+ <Input
415
+ type="email"
416
+ value={email}
417
+ onChange={(e) => setEmail(e.target.value)}
418
+ />
419
+ </Field.Root>
420
+ <Field.Root>
421
+ <Field.Label>Avatar URL</Field.Label>
422
+ <Input
423
+ type="url"
424
+ value={image}
425
+ onChange={(e) => setImage(e.target.value)}
426
+ placeholder="https://…"
427
+ />
428
+ </Field.Root>
429
+ <ToggleRow
430
+ label="Email verified"
431
+ hint="Flip manually after an out-of-band verification."
432
+ checked={emailVerified}
433
+ onChange={setEmailVerified}
434
+ />
435
+ <ToggleRow
436
+ label="Pending SSO setup"
437
+ hint="Allows first-time SSO provider linking."
438
+ checked={pendingSsoSetup}
439
+ onChange={setPendingSsoSetup}
440
+ />
441
+ <ToggleRow
442
+ label="Deactivated"
443
+ hint="Revokes sessions + blocks new logins until reactivated."
444
+ checked={deactivate}
445
+ onChange={setDeactivate}
446
+ />
447
+ <VStack align="start" gap={0} pt={2}>
448
+ <Text fontSize="xs" color="fg.muted">
449
+ User ID: {user.id}
450
+ </Text>
451
+ <Text fontSize="xs" color="fg.muted">
452
+ Created: {formatDateTime(user.createdAt)}
453
+ </Text>
454
+ <Text fontSize="xs" color="fg.muted">
455
+ Last login: {formatDateTime(user.lastLoginAt)}
456
+ </Text>
457
+ </VStack>
458
+ </VStack>
459
+ )}
460
+ </Drawer.Body>
461
+ <Drawer.Footer>
462
+ <HStack width="full">
463
+ <Spacer />
464
+ <Button variant="ghost" onClick={onClose}>
465
+ Cancel
466
+ </Button>
467
+ <Button loading={update.isPending} onClick={handleSave}>
468
+ Save
469
+ </Button>
470
+ </HStack>
471
+ </Drawer.Footer>
472
+ </Drawer.Content>
473
+ </Drawer.Root>
474
+ );
475
+ }
476
+
477
+ /**
478
+ * Renders a wrapped list of clickable chips for the Users table's
479
+ * Organizations / Projects columns. Each chip deep-links to the matching
480
+ * Backoffice list page with the row's id pre-loaded into the `q` search
481
+ * param so the user lands on a single-row, filtered view — same one-click
482
+ * drill-down the old react-admin `ReferenceField` used to give us.
483
+ */
484
+ function RefChipList({
485
+ refs,
486
+ resource,
487
+ }: {
488
+ refs: { id: string; name: string }[] | string | null | undefined;
489
+ resource: "organizations" | "projects";
490
+ }) {
491
+ // Defend against legacy shape: prior server versions returned a
492
+ // comma-joined string for these columns, and a cold dev server + cached
493
+ // response can still deliver that on first hit. Render it as plain text
494
+ // instead of crashing with `.map is not a function`.
495
+ if (typeof refs === "string") {
496
+ return refs ? <Text fontSize="xs">{refs}</Text> : <EmptyCell />;
497
+ }
498
+ if (!Array.isArray(refs) || refs.length === 0) return <EmptyCell />;
499
+ return (
500
+ <Wrap gap={1}>
501
+ {refs.map((ref) => (
502
+ <ChakraLink
503
+ key={ref.id}
504
+ asChild
505
+ fontSize="xs"
506
+ color="fg"
507
+ _hover={{ textDecoration: "underline" }}
508
+ >
509
+ <NextLink href={`/ops/backoffice/${resource}?q=${ref.id}`}>
510
+ <Box
511
+ as="span"
512
+ paddingX={2}
513
+ paddingY={0.5}
514
+ borderRadius="md"
515
+ borderWidth="1px"
516
+ borderColor="border.emphasized"
517
+ background="bg.subtle"
518
+ >
519
+ {ref.name}
520
+ </Box>
521
+ </NextLink>
522
+ </ChakraLink>
523
+ ))}
524
+ </Wrap>
525
+ );
526
+ }
527
+
528
+ function ToggleRow({
529
+ label,
530
+ hint,
531
+ checked,
532
+ onChange,
533
+ }: {
534
+ label: string;
535
+ hint: string;
536
+ checked: boolean;
537
+ onChange: (v: boolean) => void;
538
+ }) {
539
+ return (
540
+ <Field.Root>
541
+ <HStack width="full">
542
+ <VStack align="start" gap={0}>
543
+ <Field.Label>{label}</Field.Label>
544
+ <Text fontSize="xs" color="fg.muted">
545
+ {hint}
546
+ </Text>
547
+ </VStack>
548
+ <Spacer />
549
+ <Switch
550
+ checked={checked}
551
+ onCheckedChange={(e) => onChange(e.checked)}
552
+ />
553
+ </HStack>
554
+ </Field.Root>
555
+ );
556
+ }
@@ -0,0 +1,104 @@
1
+ import {
2
+ useMutation,
3
+ useQuery,
4
+ useQueryClient,
5
+ type UseMutationOptions,
6
+ type UseQueryOptions,
7
+ } from "@tanstack/react-query";
8
+ import {
9
+ adminClient,
10
+ type DataResult,
11
+ type ListParams,
12
+ type ListResult,
13
+ type ResourceName,
14
+ type SortOrder,
15
+ } from "./adminClient";
16
+
17
+ /**
18
+ * React-Query hooks around the admin REST endpoints. Kept small and local —
19
+ * this is the only file that knows the query-key shape so invalidation after
20
+ * mutations stays consistent.
21
+ */
22
+
23
+ const rootKey = (resource: ResourceName) => ["backoffice", resource] as const;
24
+ const listKey = (resource: ResourceName, params: ListParams) =>
25
+ [...rootKey(resource), "list", params] as const;
26
+ const oneKey = (resource: ResourceName, id: string) =>
27
+ [...rootKey(resource), "one", id] as const;
28
+
29
+ export function useAdminList<T>(
30
+ resource: ResourceName,
31
+ params: ListParams,
32
+ options?: Omit<
33
+ UseQueryOptions<ListResult<T>, Error, ListResult<T>>,
34
+ "queryKey" | "queryFn"
35
+ >,
36
+ ) {
37
+ return useQuery<ListResult<T>, Error>({
38
+ queryKey: listKey(resource, params),
39
+ queryFn: () => adminClient.getList<T>(resource, params),
40
+ keepPreviousData: true,
41
+ ...options,
42
+ });
43
+ }
44
+
45
+ export function useAdminOne<T>(
46
+ resource: ResourceName,
47
+ id: string | null,
48
+ options?: Omit<
49
+ UseQueryOptions<DataResult<T>, Error, DataResult<T>>,
50
+ "queryKey" | "queryFn" | "enabled"
51
+ > & { enabled?: boolean },
52
+ ) {
53
+ return useQuery<DataResult<T>, Error>({
54
+ queryKey: oneKey(resource, id ?? ""),
55
+ queryFn: () => adminClient.getOne<T>(resource, id!),
56
+ enabled: !!id && (options?.enabled ?? true),
57
+ ...options,
58
+ });
59
+ }
60
+
61
+ export function useAdminUpdate<T>(
62
+ resource: ResourceName,
63
+ options?: UseMutationOptions<
64
+ DataResult<T>,
65
+ Error,
66
+ { id: string; data: Record<string, unknown> }
67
+ >,
68
+ ) {
69
+ const qc = useQueryClient();
70
+ return useMutation<
71
+ DataResult<T>,
72
+ Error,
73
+ { id: string; data: Record<string, unknown> }
74
+ >({
75
+ mutationFn: ({ id, data }) => adminClient.update<T>(resource, id, data),
76
+ ...options,
77
+ onSuccess: async (res, vars, ctx) => {
78
+ await qc.invalidateQueries({ queryKey: rootKey(resource) });
79
+ options?.onSuccess?.(res, vars, ctx);
80
+ },
81
+ });
82
+ }
83
+
84
+ export function useAdminCreate<T>(
85
+ resource: ResourceName,
86
+ options?: UseMutationOptions<
87
+ DataResult<T>,
88
+ Error,
89
+ Record<string, unknown>
90
+ >,
91
+ ) {
92
+ const qc = useQueryClient();
93
+ return useMutation<DataResult<T>, Error, Record<string, unknown>>({
94
+ mutationFn: (data) => adminClient.create<T>(resource, data),
95
+ ...options,
96
+ onSuccess: async (res, vars, ctx) => {
97
+ await qc.invalidateQueries({ queryKey: rootKey(resource) });
98
+ options?.onSuccess?.(res, vars, ctx);
99
+ },
100
+ });
101
+ }
102
+
103
+ /** Re-exported for convenience in resource views. */
104
+ export type { ListParams, ListResult, SortOrder };