@langwatch/server 3.1.0-beta.4 → 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 (118) 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/package.json +1 -1
  118. package/packages/server/dist/cli.cjs +1 -1
@@ -0,0 +1,628 @@
1
+ import {
2
+ Badge,
3
+ Box,
4
+ Button,
5
+ Field,
6
+ Heading,
7
+ HStack,
8
+ Input,
9
+ NativeSelect,
10
+ SimpleGrid,
11
+ Spacer,
12
+ Table,
13
+ Text,
14
+ VStack,
15
+ } from "@chakra-ui/react";
16
+ import { PlanTypes, SubscriptionStatus } from "@prisma/client";
17
+ import { MoreVertical, Pencil } from "lucide-react";
18
+ import { useEffect, useMemo, useState } from "react";
19
+ import { useDebounce } from "use-debounce";
20
+ import { Drawer } from "~/components/ui/drawer";
21
+ import { Menu } from "~/components/ui/menu";
22
+ import { toaster } from "~/components/ui/toaster";
23
+ import {
24
+ BackofficeTable,
25
+ EmptyCell,
26
+ dateInputToISO,
27
+ formatDate,
28
+ } from "../BackofficeTable";
29
+ import {
30
+ useAdminCreate,
31
+ useAdminList,
32
+ useAdminUpdate,
33
+ } from "../useAdminResource";
34
+
35
+ interface AdminSubscription {
36
+ id: string;
37
+ organizationId: string;
38
+ plan: PlanTypes;
39
+ status: SubscriptionStatus;
40
+ stripeSubscriptionId: string | null;
41
+ startDate: string | null;
42
+ endDate: string | null;
43
+ lastPaymentFailedDate: string | null;
44
+ maxMembers: number | null;
45
+ maxMembersLite: number | null;
46
+ maxTeams: number | null;
47
+ maxProjects: number | null;
48
+ maxWorkflows: number | null;
49
+ maxPrompts: number | null;
50
+ maxAgents: number | null;
51
+ maxScenarios: number | null;
52
+ maxEvaluators: number | null;
53
+ maxExperiments: number | null;
54
+ maxOnlineEvaluations: number | null;
55
+ maxMessagesPerMonth: number | null;
56
+ maxRetentionDays: number | null;
57
+ maxDatasets: number | null;
58
+ maxDashboards: number | null;
59
+ maxCustomGraphs: number | null;
60
+ maxAutomations: number | null;
61
+ organization?: { id: string; name: string; slug: string };
62
+ createdAt: string;
63
+ }
64
+
65
+ const PAGE_SIZE = 25;
66
+
67
+ const statusColor: Record<SubscriptionStatus, string> = {
68
+ ACTIVE: "green",
69
+ PENDING: "yellow",
70
+ FAILED: "red",
71
+ CANCELLED: "gray",
72
+ };
73
+
74
+ /**
75
+ * Every numeric limit the server stores on a subscription, rendered as its own
76
+ * form field. Kept as a table so adding/removing a limit is a one-line change.
77
+ */
78
+ const LIMIT_FIELDS: Array<{
79
+ key: keyof AdminSubscription;
80
+ label: string;
81
+ group: "Members" | "Resources" | "Evaluation" | "Observability" | "Analytics";
82
+ }> = [
83
+ { key: "maxMembers", label: "Max members", group: "Members" },
84
+ { key: "maxMembersLite", label: "Max lite members", group: "Members" },
85
+ { key: "maxTeams", label: "Max teams", group: "Members" },
86
+
87
+ { key: "maxProjects", label: "Max projects", group: "Resources" },
88
+ { key: "maxWorkflows", label: "Max workflows", group: "Resources" },
89
+ { key: "maxPrompts", label: "Max prompts", group: "Resources" },
90
+ { key: "maxAgents", label: "Max agents", group: "Resources" },
91
+ { key: "maxScenarios", label: "Max scenarios", group: "Resources" },
92
+
93
+ { key: "maxEvaluators", label: "Max evaluators", group: "Evaluation" },
94
+ { key: "maxExperiments", label: "Max experiments", group: "Evaluation" },
95
+ {
96
+ key: "maxOnlineEvaluations",
97
+ label: "Max online evaluations",
98
+ group: "Evaluation",
99
+ },
100
+ {
101
+ key: "maxMessagesPerMonth",
102
+ label: "Max traces per month",
103
+ group: "Observability",
104
+ },
105
+ {
106
+ key: "maxRetentionDays",
107
+ label: "Max retention days",
108
+ group: "Observability",
109
+ },
110
+ { key: "maxDatasets", label: "Max datasets", group: "Observability" },
111
+
112
+ { key: "maxDashboards", label: "Max dashboards", group: "Analytics" },
113
+ { key: "maxCustomGraphs", label: "Max custom graphs", group: "Analytics" },
114
+ { key: "maxAutomations", label: "Max automations", group: "Analytics" },
115
+ ];
116
+
117
+ export default function SubscriptionsView() {
118
+ const [page, setPage] = useState(1);
119
+ const [search, setSearch] = useState("");
120
+ const [debouncedSearch] = useDebounce(search, 300);
121
+ const [editing, setEditing] = useState<AdminSubscription | null>(null);
122
+ const [creating, setCreating] = useState(false);
123
+
124
+ const list = useAdminList<AdminSubscription>("subscription", {
125
+ pagination: { page, perPage: PAGE_SIZE },
126
+ sort: { field: "createdAt", order: "DESC" },
127
+ filter: debouncedSearch ? { query: debouncedSearch } : {},
128
+ });
129
+
130
+ return (
131
+ <>
132
+ <BackofficeTable
133
+ title="Subscriptions"
134
+ searchValue={search}
135
+ onSearchChange={(v) => {
136
+ setSearch(v);
137
+ setPage(1);
138
+ }}
139
+ searchPlaceholder="Search by ID, Stripe ID, org, plan, or status"
140
+ isLoading={list.isLoading}
141
+ isFetching={list.isFetching}
142
+ error={list.error}
143
+ pagination={{
144
+ page,
145
+ perPage: PAGE_SIZE,
146
+ total: list.data?.total ?? 0,
147
+ onPageChange: setPage,
148
+ }}
149
+ onCreate={() => setCreating(true)}
150
+ createLabel="New subscription"
151
+ >
152
+ <Table.Root variant="line" size="md" width="full">
153
+ <Table.Header>
154
+ <Table.Row>
155
+ <Table.ColumnHeader>Organization</Table.ColumnHeader>
156
+ <Table.ColumnHeader>Plan</Table.ColumnHeader>
157
+ <Table.ColumnHeader>Status</Table.ColumnHeader>
158
+ <Table.ColumnHeader>Stripe ID</Table.ColumnHeader>
159
+ <Table.ColumnHeader>Start</Table.ColumnHeader>
160
+ <Table.ColumnHeader>End</Table.ColumnHeader>
161
+ <Table.ColumnHeader width="60px" textAlign="right" />
162
+ </Table.Row>
163
+ </Table.Header>
164
+ <Table.Body>
165
+ {list.data?.data.length === 0 && (
166
+ <Table.Row>
167
+ <Table.Cell colSpan={7}>
168
+ <Text color="fg.muted" textAlign="center" paddingY={6}>
169
+ No subscriptions match your search.
170
+ </Text>
171
+ </Table.Cell>
172
+ </Table.Row>
173
+ )}
174
+ {list.data?.data.map((sub) => (
175
+ <Table.Row key={sub.id}>
176
+ <Table.Cell>
177
+ {sub.organization?.name ?? (
178
+ <Text fontSize="xs" color="fg.muted">
179
+ {sub.organizationId}
180
+ </Text>
181
+ )}
182
+ </Table.Cell>
183
+ <Table.Cell>
184
+ <Badge size="sm" variant="subtle">
185
+ {sub.plan}
186
+ </Badge>
187
+ </Table.Cell>
188
+ <Table.Cell>
189
+ <Badge size="sm" colorPalette={statusColor[sub.status]}>
190
+ {sub.status}
191
+ </Badge>
192
+ </Table.Cell>
193
+ <Table.Cell>
194
+ {sub.stripeSubscriptionId ?? <EmptyCell />}
195
+ </Table.Cell>
196
+ <Table.Cell>{formatDate(sub.startDate)}</Table.Cell>
197
+ <Table.Cell>{formatDate(sub.endDate)}</Table.Cell>
198
+ <Table.Cell textAlign="right">
199
+ <Box
200
+ width="full"
201
+ height="full"
202
+ display="flex"
203
+ justifyContent="end"
204
+ >
205
+ <Menu.Root>
206
+ <Menu.Trigger>
207
+ <MoreVertical size={16} />
208
+ </Menu.Trigger>
209
+ <Menu.Content>
210
+ <Menu.Item
211
+ value="edit"
212
+ onClick={() => setEditing(sub)}
213
+ >
214
+ <Pencil size={16} />
215
+ Edit
216
+ </Menu.Item>
217
+ </Menu.Content>
218
+ </Menu.Root>
219
+ </Box>
220
+ </Table.Cell>
221
+ </Table.Row>
222
+ ))}
223
+ </Table.Body>
224
+ </Table.Root>
225
+ </BackofficeTable>
226
+
227
+ <SubscriptionDrawer
228
+ mode="edit"
229
+ subscription={editing}
230
+ onClose={() => setEditing(null)}
231
+ />
232
+ <SubscriptionDrawer
233
+ mode="create"
234
+ subscription={creating ? null : undefined}
235
+ onClose={() => setCreating(false)}
236
+ />
237
+ </>
238
+ );
239
+ }
240
+
241
+ type LimitKey =
242
+ | "maxMembers"
243
+ | "maxMembersLite"
244
+ | "maxTeams"
245
+ | "maxProjects"
246
+ | "maxWorkflows"
247
+ | "maxPrompts"
248
+ | "maxAgents"
249
+ | "maxScenarios"
250
+ | "maxEvaluators"
251
+ | "maxExperiments"
252
+ | "maxOnlineEvaluations"
253
+ | "maxMessagesPerMonth"
254
+ | "maxRetentionDays"
255
+ | "maxDatasets"
256
+ | "maxDashboards"
257
+ | "maxCustomGraphs"
258
+ | "maxAutomations";
259
+
260
+ type FormState = {
261
+ organizationId: string;
262
+ plan: PlanTypes;
263
+ status: SubscriptionStatus;
264
+ stripeSubscriptionId: string;
265
+ startDate: string;
266
+ endDate: string;
267
+ } & Record<LimitKey, string>;
268
+
269
+ const EMPTY_LIMITS: Record<LimitKey, string> = LIMIT_FIELDS.reduce(
270
+ (acc, f) => {
271
+ acc[f.key as LimitKey] = "";
272
+ return acc;
273
+ },
274
+ {} as Record<LimitKey, string>,
275
+ );
276
+
277
+ const EMPTY_FORM: FormState = {
278
+ organizationId: "",
279
+ plan: "FREE",
280
+ status: "PENDING",
281
+ stripeSubscriptionId: "",
282
+ startDate: "",
283
+ endDate: "",
284
+ ...EMPTY_LIMITS,
285
+ };
286
+
287
+ function toDateInputValue(value: string | null | undefined): string {
288
+ if (!value) return "";
289
+ const d = new Date(value);
290
+ if (Number.isNaN(d.getTime())) return "";
291
+ return d.toISOString().slice(0, 10);
292
+ }
293
+
294
+ function numOrNull(raw: string): number | null {
295
+ if (raw === "") return null;
296
+ const n = Number(raw);
297
+ return Number.isFinite(n) ? n : null;
298
+ }
299
+
300
+ function SubscriptionDrawer({
301
+ mode,
302
+ subscription,
303
+ onClose,
304
+ }: {
305
+ mode: "create" | "edit";
306
+ subscription: AdminSubscription | null | undefined;
307
+ onClose: () => void;
308
+ }) {
309
+ const update = useAdminUpdate<AdminSubscription>("subscription");
310
+ const create = useAdminCreate<AdminSubscription>("subscription");
311
+ const mutation = mode === "edit" ? update : create;
312
+
313
+ const [form, setForm] = useState<FormState>(EMPTY_FORM);
314
+ const isOpen =
315
+ mode === "edit" ? !!subscription : subscription !== undefined;
316
+
317
+ useEffect(() => {
318
+ if (!isOpen) return;
319
+ if (mode === "edit" && subscription) {
320
+ const limitValues = LIMIT_FIELDS.reduce(
321
+ (acc, f) => {
322
+ const raw = subscription[f.key];
323
+ acc[f.key as LimitKey] =
324
+ typeof raw === "number" ? raw.toString() : "";
325
+ return acc;
326
+ },
327
+ {} as Record<LimitKey, string>,
328
+ );
329
+ setForm({
330
+ organizationId: subscription.organizationId,
331
+ plan: subscription.plan,
332
+ status: subscription.status,
333
+ stripeSubscriptionId: subscription.stripeSubscriptionId ?? "",
334
+ startDate: toDateInputValue(subscription.startDate),
335
+ endDate: toDateInputValue(subscription.endDate),
336
+ ...limitValues,
337
+ });
338
+ } else if (mode === "create") {
339
+ setForm(EMPTY_FORM);
340
+ }
341
+ }, [isOpen, mode, subscription]);
342
+
343
+ const setField = <K extends keyof FormState>(key: K, value: FormState[K]) =>
344
+ setForm((prev) => ({ ...prev, [key]: value }));
345
+
346
+ const title = mode === "edit" ? "Edit Subscription" : "New Subscription";
347
+
348
+ const handleSave = () => {
349
+ if (!form.organizationId) {
350
+ toaster.create({
351
+ title: "Organization is required",
352
+ type: "error",
353
+ duration: 3000,
354
+ meta: { closable: true },
355
+ });
356
+ return;
357
+ }
358
+ const payload: Record<string, unknown> = {
359
+ organizationId: form.organizationId,
360
+ plan: form.plan,
361
+ status: form.status,
362
+ stripeSubscriptionId: form.stripeSubscriptionId || null,
363
+ startDate: dateInputToISO(form.startDate),
364
+ endDate: dateInputToISO(form.endDate),
365
+ };
366
+ for (const f of LIMIT_FIELDS) {
367
+ payload[f.key] = numOrNull(form[f.key as LimitKey]);
368
+ }
369
+
370
+ const onSuccess = () => {
371
+ toaster.create({
372
+ title: mode === "edit" ? "Subscription updated" : "Subscription created",
373
+ type: "success",
374
+ duration: 3000,
375
+ meta: { closable: true },
376
+ });
377
+ onClose();
378
+ };
379
+ const onError = (err: Error) =>
380
+ toaster.create({
381
+ title: mode === "edit" ? "Update failed" : "Create failed",
382
+ description: err.message,
383
+ type: "error",
384
+ duration: 5000,
385
+ meta: { closable: true },
386
+ });
387
+
388
+ if (mode === "edit" && subscription) {
389
+ update.mutate({ id: subscription.id, data: payload }, { onSuccess, onError });
390
+ } else {
391
+ create.mutate(payload, { onSuccess, onError });
392
+ }
393
+ };
394
+
395
+ // Group limit fields by the "group" tag so the form renders tight sections.
396
+ const groupedLimits = useMemo(() => {
397
+ const map = new Map<string, typeof LIMIT_FIELDS>();
398
+ for (const f of LIMIT_FIELDS) {
399
+ const bucket = map.get(f.group) ?? [];
400
+ bucket.push(f);
401
+ map.set(f.group, bucket);
402
+ }
403
+ return Array.from(map.entries());
404
+ }, []);
405
+
406
+ return (
407
+ <Drawer.Root
408
+ open={isOpen}
409
+ onOpenChange={({ open }) => {
410
+ if (!open) onClose();
411
+ }}
412
+ size="lg"
413
+ >
414
+ <Drawer.Content>
415
+ <Drawer.Header>
416
+ <Drawer.Title>{title}</Drawer.Title>
417
+ </Drawer.Header>
418
+ <Drawer.CloseTrigger />
419
+ <Drawer.Body>
420
+ <VStack gap={4} align="stretch">
421
+ <SectionHeading>Subscription</SectionHeading>
422
+ <OrganizationPicker
423
+ value={form.organizationId}
424
+ onChange={(id) => setField("organizationId", id)}
425
+ currentName={subscription?.organization?.name}
426
+ />
427
+ <HStack gap={3} align="start">
428
+ <Field.Root>
429
+ <Field.Label>Plan</Field.Label>
430
+ <EnumSelect
431
+ value={form.plan}
432
+ options={Object.values(PlanTypes)}
433
+ onChange={(v) => setField("plan", v as PlanTypes)}
434
+ />
435
+ </Field.Root>
436
+ <Field.Root>
437
+ <Field.Label>Status</Field.Label>
438
+ <EnumSelect
439
+ value={form.status}
440
+ options={Object.values(SubscriptionStatus)}
441
+ onChange={(v) =>
442
+ setField("status", v as SubscriptionStatus)
443
+ }
444
+ />
445
+ </Field.Root>
446
+ </HStack>
447
+ <Field.Root>
448
+ <Field.Label>Stripe subscription ID</Field.Label>
449
+ <Input
450
+ value={form.stripeSubscriptionId}
451
+ onChange={(e) =>
452
+ setField("stripeSubscriptionId", e.target.value)
453
+ }
454
+ />
455
+ </Field.Root>
456
+ <HStack gap={3}>
457
+ <Field.Root>
458
+ <Field.Label>Start date</Field.Label>
459
+ <Input
460
+ type="date"
461
+ value={form.startDate}
462
+ onChange={(e) => setField("startDate", e.target.value)}
463
+ />
464
+ </Field.Root>
465
+ <Field.Root>
466
+ <Field.Label>End date</Field.Label>
467
+ <Input
468
+ type="date"
469
+ value={form.endDate}
470
+ onChange={(e) => setField("endDate", e.target.value)}
471
+ />
472
+ </Field.Root>
473
+ </HStack>
474
+
475
+ {groupedLimits.map(([group, fields]) => (
476
+ <VStack key={group} gap={3} align="stretch">
477
+ <SectionHeading>{group} limits</SectionHeading>
478
+ <SimpleGrid columns={2} gap={3}>
479
+ {fields.map((f) => (
480
+ <Field.Root key={f.key}>
481
+ <Field.Label>{f.label}</Field.Label>
482
+ <Input
483
+ type="number"
484
+ value={form[f.key as LimitKey]}
485
+ onChange={(e) =>
486
+ setField(f.key as LimitKey, e.target.value)
487
+ }
488
+ placeholder="—"
489
+ />
490
+ </Field.Root>
491
+ ))}
492
+ </SimpleGrid>
493
+ </VStack>
494
+ ))}
495
+
496
+ {mode === "edit" && subscription && (
497
+ <VStack align="start" gap={0} pt={2}>
498
+ <Text fontSize="xs" color="fg.muted">
499
+ Subscription ID: {subscription.id}
500
+ </Text>
501
+ {subscription.lastPaymentFailedDate && (
502
+ <Text fontSize="xs" color="red.500">
503
+ Last payment failed:{" "}
504
+ {formatDate(subscription.lastPaymentFailedDate)}
505
+ </Text>
506
+ )}
507
+ </VStack>
508
+ )}
509
+ </VStack>
510
+ </Drawer.Body>
511
+ <Drawer.Footer>
512
+ <HStack width="full">
513
+ <Spacer />
514
+ <Button variant="ghost" onClick={onClose}>
515
+ Cancel
516
+ </Button>
517
+ <Button loading={mutation.isPending} onClick={handleSave}>
518
+ {mode === "edit" ? "Save" : "Create"}
519
+ </Button>
520
+ </HStack>
521
+ </Drawer.Footer>
522
+ </Drawer.Content>
523
+ </Drawer.Root>
524
+ );
525
+ }
526
+
527
+ function SectionHeading({ children }: { children: React.ReactNode }) {
528
+ return (
529
+ <Heading
530
+ as="h3"
531
+ size="xs"
532
+ color="fg.muted"
533
+ textTransform="uppercase"
534
+ letterSpacing="wider"
535
+ pt={2}
536
+ >
537
+ {children}
538
+ </Heading>
539
+ );
540
+ }
541
+
542
+ function EnumSelect({
543
+ value,
544
+ options,
545
+ onChange,
546
+ }: {
547
+ value: string;
548
+ options: readonly string[];
549
+ onChange: (value: string) => void;
550
+ }) {
551
+ return (
552
+ <NativeSelect.Root size="sm" width="full">
553
+ <NativeSelect.Field
554
+ value={value}
555
+ onChange={(e) => onChange(e.target.value)}
556
+ >
557
+ {options.map((opt) => (
558
+ <option key={opt} value={opt}>
559
+ {opt}
560
+ </option>
561
+ ))}
562
+ </NativeSelect.Field>
563
+ <NativeSelect.Indicator />
564
+ </NativeSelect.Root>
565
+ );
566
+ }
567
+
568
+ interface OrgOption {
569
+ id: string;
570
+ name: string;
571
+ slug: string;
572
+ }
573
+
574
+ /**
575
+ * Simple organization picker — fetches the first page by query (or first 50
576
+ * if empty) and lets the operator pick. Mirrors react-admin's AutocompleteInput
577
+ * behaviour for the Subscription form.
578
+ */
579
+ function OrganizationPicker({
580
+ value,
581
+ onChange,
582
+ currentName,
583
+ }: {
584
+ value: string;
585
+ onChange: (id: string) => void;
586
+ currentName?: string;
587
+ }) {
588
+ const [query, setQuery] = useState("");
589
+ const [debouncedQuery] = useDebounce(query, 250);
590
+
591
+ const list = useAdminList<OrgOption>("organization", {
592
+ pagination: { page: 1, perPage: 50 },
593
+ sort: { field: "name", order: "ASC" },
594
+ filter: debouncedQuery ? { query: debouncedQuery } : {},
595
+ });
596
+
597
+ const options = useMemo(() => list.data?.data ?? [], [list.data]);
598
+
599
+ return (
600
+ <Field.Root required>
601
+ <Field.Label>Organization</Field.Label>
602
+ {value && !query && currentName && (
603
+ <Text fontSize="xs" color="fg.muted">
604
+ Currently: {currentName}
605
+ </Text>
606
+ )}
607
+ <Input
608
+ placeholder="Type to search organizations"
609
+ value={query}
610
+ onChange={(e) => setQuery(e.target.value)}
611
+ />
612
+ <NativeSelect.Root size="sm" width="full" mt={1}>
613
+ <NativeSelect.Field
614
+ value={value}
615
+ onChange={(e) => onChange(e.target.value)}
616
+ >
617
+ <option value="">Select organization…</option>
618
+ {options.map((org) => (
619
+ <option key={org.id} value={org.id}>
620
+ {org.name} ({org.slug})
621
+ </option>
622
+ ))}
623
+ </NativeSelect.Field>
624
+ <NativeSelect.Indicator />
625
+ </NativeSelect.Root>
626
+ </Field.Root>
627
+ );
628
+ }