@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,147 @@
1
+ import {
2
+ afterEach,
3
+ beforeEach,
4
+ describe,
5
+ expect,
6
+ it,
7
+ vi,
8
+ type Mock,
9
+ } from "vitest";
10
+ import { adminClient, impersonateUser } from "../adminClient";
11
+
12
+ /**
13
+ * Pin the request-body shape the admin UI posts to `/api/admin/:resource`.
14
+ * The Hono handler in `ee/admin/routes/admin.ts` reads these exact fields
15
+ * (via ra-data-simple-prisma's `defaultHandler` / `getListHandler`), so any
16
+ * drift here silently breaks the list/update/create flows across every
17
+ * Backoffice resource view.
18
+ */
19
+ describe("adminClient", () => {
20
+ const originalFetch = globalThis.fetch;
21
+ let fetchMock: Mock;
22
+
23
+ beforeEach(() => {
24
+ fetchMock = vi.fn(async () =>
25
+ new Response(JSON.stringify({ data: [], total: 0 }), {
26
+ status: 200,
27
+ headers: { "Content-Type": "application/json" },
28
+ }),
29
+ );
30
+ globalThis.fetch = fetchMock as unknown as typeof fetch;
31
+ });
32
+
33
+ afterEach(() => {
34
+ globalThis.fetch = originalFetch;
35
+ });
36
+
37
+ describe("when calling getList", () => {
38
+ it("posts resource, method, and params under the expected body shape", async () => {
39
+ await adminClient.getList("user", {
40
+ pagination: { page: 2, perPage: 50 },
41
+ sort: { field: "createdAt", order: "DESC" },
42
+ filter: { query: "acme" },
43
+ });
44
+
45
+ expect(fetchMock).toHaveBeenCalledTimes(1);
46
+ const [url, init] = fetchMock.mock.calls[0]!;
47
+ expect(url).toBe("/api/admin/user");
48
+ expect(init.method).toBe("POST");
49
+ expect(init.credentials).toBe("include");
50
+ expect(JSON.parse(init.body as string)).toEqual({
51
+ resource: "user",
52
+ method: "getList",
53
+ params: {
54
+ pagination: { page: 2, perPage: 50 },
55
+ sort: { field: "createdAt", order: "DESC" },
56
+ filter: { query: "acme" },
57
+ },
58
+ });
59
+ });
60
+
61
+ it("defaults pagination, sort, and filter when params are partial", async () => {
62
+ await adminClient.getList("organization", {});
63
+ const body = JSON.parse(
64
+ fetchMock.mock.calls[0]![1].body as string,
65
+ );
66
+ expect(body.params.pagination).toEqual({ page: 1, perPage: 25 });
67
+ expect(body.params.sort).toEqual({ field: "id", order: "ASC" });
68
+ expect(body.params.filter).toEqual({});
69
+ });
70
+ });
71
+
72
+ describe("when calling update", () => {
73
+ it("sends id and data inside params", async () => {
74
+ await adminClient.update("user", "user_123", {
75
+ name: "Jane",
76
+ deactivatedAt: null,
77
+ });
78
+ expect(JSON.parse(fetchMock.mock.calls[0]![1].body as string)).toEqual({
79
+ resource: "user",
80
+ method: "update",
81
+ params: { id: "user_123", data: { name: "Jane", deactivatedAt: null } },
82
+ });
83
+ });
84
+ });
85
+
86
+ describe("when calling create", () => {
87
+ it("sends data inside params", async () => {
88
+ await adminClient.create("organizationFeature", {
89
+ feature: "CUSTOM_EMBEDDINGS",
90
+ organizationId: "org_1",
91
+ });
92
+ expect(JSON.parse(fetchMock.mock.calls[0]![1].body as string)).toEqual({
93
+ resource: "organizationFeature",
94
+ method: "create",
95
+ params: {
96
+ data: { feature: "CUSTOM_EMBEDDINGS", organizationId: "org_1" },
97
+ },
98
+ });
99
+ });
100
+ });
101
+
102
+ describe("when the server returns a non-2xx", () => {
103
+ it("throws an Error that includes status and body for visibility", async () => {
104
+ fetchMock.mockResolvedValueOnce(
105
+ new Response("boom", { status: 500, statusText: "Server Error" }),
106
+ );
107
+ await expect(
108
+ adminClient.getList("user", {}),
109
+ ).rejects.toThrow(/user\/getList failed \(500\): boom/);
110
+ });
111
+ });
112
+ });
113
+
114
+ describe("impersonateUser", () => {
115
+ const originalFetch = globalThis.fetch;
116
+ let fetchMock: Mock;
117
+
118
+ beforeEach(() => {
119
+ fetchMock = vi.fn(async () =>
120
+ new Response(JSON.stringify({ message: "ok" }), { status: 200 }),
121
+ );
122
+ globalThis.fetch = fetchMock as unknown as typeof fetch;
123
+ });
124
+
125
+ afterEach(() => {
126
+ globalThis.fetch = originalFetch;
127
+ });
128
+
129
+ it("posts userIdToImpersonate and reason to the dedicated impersonate endpoint", async () => {
130
+ await impersonateUser({
131
+ userIdToImpersonate: "user_xyz",
132
+ reason: "Investigating a stuck trace reported by support",
133
+ });
134
+ const [url, init] = fetchMock.mock.calls[0]!;
135
+ expect(url).toBe("/api/admin/impersonate");
136
+ expect(init.method).toBe("POST");
137
+ // Cookie-mode auth: the admin session is carried via a same-site
138
+ // cookie, so we must explicitly send credentials. Pinning this here
139
+ // catches a silent regression where a refactor drops the flag and
140
+ // BetterAuth starts rejecting the impersonation as unauthenticated.
141
+ expect(init.credentials).toBe("include");
142
+ expect(JSON.parse(init.body as string)).toEqual({
143
+ userIdToImpersonate: "user_xyz",
144
+ reason: "Investigating a stuck trace reported by support",
145
+ });
146
+ });
147
+ });
@@ -0,0 +1,42 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { dateInputToISO } from "../BackofficeTable";
3
+
4
+ /**
5
+ * Regression — CodeRabbit review on #3254 surfaced that
6
+ * `new Date("2026-04-16").toISOString()` parses as UTC midnight, which shifts
7
+ * the calendar day one step backwards for users west of UTC (the date they
8
+ * typed ends up stored as the previous day). `dateInputToISO` must preserve
9
+ * the typed calendar date in every timezone.
10
+ */
11
+ describe("dateInputToISO", () => {
12
+ describe("when given a YYYY-MM-DD date-input value", () => {
13
+ it("preserves the typed calendar day regardless of timezone", () => {
14
+ const iso = dateInputToISO("2026-04-16");
15
+ // Must be some instant within 2026-04-16 local time — parsing the
16
+ // result into any Date and reading getFullYear/Month/Date locally must
17
+ // round-trip the original.
18
+ const d = new Date(iso!);
19
+ expect(d.getFullYear()).toBe(2026);
20
+ expect(d.getMonth()).toBe(3); // April (0-indexed)
21
+ expect(d.getDate()).toBe(16);
22
+ });
23
+
24
+ it("does not drift on month boundaries", () => {
25
+ const first = dateInputToISO("2026-05-01");
26
+ const firstDate = new Date(first!);
27
+ expect(firstDate.getMonth()).toBe(4);
28
+ expect(firstDate.getDate()).toBe(1);
29
+ });
30
+ });
31
+
32
+ describe("when given an empty or malformed value", () => {
33
+ it("returns null for empty string", () => {
34
+ expect(dateInputToISO("")).toBeNull();
35
+ });
36
+
37
+ it("returns null for non-date strings", () => {
38
+ expect(dateInputToISO("not-a-date")).toBeNull();
39
+ expect(dateInputToISO("2026/04/16")).toBeNull();
40
+ });
41
+ });
42
+ });
@@ -0,0 +1,174 @@
1
+ import type { Organization, Project, Team, User } from "@prisma/client";
2
+ import { describe, expect, it } from "vitest";
3
+ import {
4
+ mapUserToBackofficeRow,
5
+ type UserWithBackofficeIncludes,
6
+ } from "../userVisibility";
7
+
8
+ /**
9
+ * Pins the Backoffice Users list's project-visibility rule: a user who has
10
+ * an OrganizationUser but NO TeamUser must still see every non-archived
11
+ * project in every team of those orgs — same rule the main app applies in
12
+ * `organization.prisma.repository.ts#getAllForUser`. Regression coverage
13
+ * for commit 605ab6ccb, where the Backoffice previously walked
14
+ * teamMemberships and rendered an empty Projects column for exactly that
15
+ * cohort.
16
+ */
17
+
18
+ function buildUser(
19
+ overrides: Partial<UserWithBackofficeIncludes> = {},
20
+ ): UserWithBackofficeIncludes {
21
+ return {
22
+ id: "user_1",
23
+ name: "Test User",
24
+ email: "test@example.com",
25
+ image: null,
26
+ emailVerified: null,
27
+ pendingSsoSetup: false,
28
+ createdAt: new Date("2026-01-01"),
29
+ updatedAt: new Date("2026-01-01"),
30
+ lastLoginAt: null,
31
+ deactivatedAt: null,
32
+ orgMemberships: [],
33
+ ...overrides,
34
+ } as UserWithBackofficeIncludes;
35
+ }
36
+
37
+ type OrgWithTeams = Organization & {
38
+ teams: (Team & { projects: Project[] })[];
39
+ };
40
+
41
+ function buildOrg(overrides: Partial<OrgWithTeams> = {}): OrgWithTeams {
42
+ return {
43
+ id: "org_1",
44
+ name: "Acme",
45
+ slug: "acme",
46
+ teams: [],
47
+ ...overrides,
48
+ } as unknown as OrgWithTeams;
49
+ }
50
+
51
+ function buildTeam(
52
+ overrides: Partial<Team & { projects: Project[] }> = {},
53
+ ): Team & { projects: Project[] } {
54
+ return {
55
+ id: "team_1",
56
+ name: "Engineering",
57
+ slug: "engineering",
58
+ organizationId: "org_1",
59
+ archivedAt: null,
60
+ projects: [],
61
+ ...overrides,
62
+ } as unknown as Team & { projects: Project[] };
63
+ }
64
+
65
+ function buildProject(overrides: Partial<Project> = {}): Project {
66
+ return {
67
+ id: "project_1",
68
+ name: "Ingest",
69
+ slug: "ingest",
70
+ teamId: "team_1",
71
+ archivedAt: null,
72
+ ...overrides,
73
+ } as unknown as Project;
74
+ }
75
+
76
+ describe("mapUserToBackofficeRow", () => {
77
+ describe("given a user with an org membership but no team membership", () => {
78
+ it("still surfaces every project in the org's teams", () => {
79
+ // No TeamUser rows anywhere — only the organization membership.
80
+ // The previous implementation walked teamMemberships and would
81
+ // return an empty projects array here; the fix has to traverse
82
+ // org → teams → projects so this user still sees the project.
83
+ const project = buildProject({ id: "p_visible", name: "Visible" });
84
+ const team = buildTeam({ projects: [project] });
85
+ const org = buildOrg({ teams: [team] });
86
+
87
+ const row = mapUserToBackofficeRow(
88
+ buildUser({ orgMemberships: [{ organization: org }] }),
89
+ );
90
+
91
+ expect(row.organizations).toEqual([{ id: org.id, name: org.name }]);
92
+ expect(row.projects).toEqual([
93
+ { id: project.id, name: project.name, slug: project.slug },
94
+ ]);
95
+ });
96
+ });
97
+
98
+ describe("given a user with overlapping memberships across orgs", () => {
99
+ it("dedupes orgs and projects so each chip appears once", () => {
100
+ const shared = buildProject({ id: "p_shared", name: "Shared" });
101
+ const orgA = buildOrg({
102
+ id: "org_a",
103
+ name: "A",
104
+ teams: [buildTeam({ id: "team_a", projects: [shared] })],
105
+ });
106
+ const orgB = buildOrg({
107
+ id: "org_b",
108
+ name: "B",
109
+ teams: [
110
+ buildTeam({
111
+ id: "team_b",
112
+ organizationId: "org_b",
113
+ projects: [shared], // same project id showing up via a second membership
114
+ }),
115
+ ],
116
+ });
117
+
118
+ const row = mapUserToBackofficeRow(
119
+ buildUser({
120
+ orgMemberships: [
121
+ { organization: orgA },
122
+ { organization: orgB },
123
+ { organization: orgA }, // duplicate membership row — must not double-count
124
+ ],
125
+ }),
126
+ );
127
+
128
+ expect(row.organizations.map((o) => o.id)).toEqual(["org_a", "org_b"]);
129
+ expect(row.projects.map((p) => p.id)).toEqual(["p_shared"]);
130
+ });
131
+ });
132
+
133
+ describe("given a user with no memberships", () => {
134
+ it("returns empty organization and project lists", () => {
135
+ const row = mapUserToBackofficeRow(buildUser());
136
+ expect(row.organizations).toEqual([]);
137
+ expect(row.projects).toEqual([]);
138
+ });
139
+ });
140
+
141
+ describe("given a team with an empty projects relation", () => {
142
+ it("does not blow up and returns no projects for that team", () => {
143
+ const org = buildOrg({
144
+ teams: [buildTeam({ projects: [] })],
145
+ });
146
+
147
+ const row = mapUserToBackofficeRow(
148
+ buildUser({ orgMemberships: [{ organization: org }] }),
149
+ );
150
+
151
+ expect(row.projects).toEqual([]);
152
+ expect(row.organizations).toHaveLength(1);
153
+ });
154
+ });
155
+
156
+ describe("given an org that archives a project via the Prisma where clause", () => {
157
+ it("only receives non-archived projects (enforced upstream by the include)", () => {
158
+ // The include filters `archivedAt: null` at the Prisma level, so by
159
+ // the time this mapper runs an archived project should never be in
160
+ // the input. Assert the mapper faithfully reflects whatever Prisma
161
+ // gave it — i.e., it does not re-introduce archived rows.
162
+ const alive = buildProject({ id: "p_alive", archivedAt: null });
163
+ const org = buildOrg({
164
+ teams: [buildTeam({ projects: [alive] })],
165
+ });
166
+
167
+ const row = mapUserToBackofficeRow(
168
+ buildUser({ orgMemberships: [{ organization: org }] }),
169
+ );
170
+
171
+ expect(row.projects.map((p) => p.id)).toEqual(["p_alive"]);
172
+ });
173
+ });
174
+ });
@@ -0,0 +1,114 @@
1
+ /**
2
+ * Thin typed wrapper around the Hono `/api/admin/:resource` endpoints.
3
+ *
4
+ * The backend (see `ee/admin/routes/admin.ts`) is the same
5
+ * `ra-data-simple-prisma` handler that used to back the react-admin UI:
6
+ * every call is a POST with `{ resource, method, params }`. We keep using it
7
+ * untouched so all business logic (user deactivate/reactivate side effects,
8
+ * org ssoDomain normalization, subscription list join, search logic, audit
9
+ * logs) remains unchanged — only the UI is rewritten.
10
+ */
11
+
12
+ export type ResourceName =
13
+ | "user"
14
+ | "organization"
15
+ | "project"
16
+ | "subscription"
17
+ | "organizationFeature";
18
+
19
+ export type SortOrder = "ASC" | "DESC";
20
+
21
+ export interface ListParams {
22
+ pagination?: { page: number; perPage: number };
23
+ sort?: { field: string; order: SortOrder };
24
+ filter?: Record<string, unknown>;
25
+ }
26
+
27
+ export interface ListResult<T> {
28
+ data: T[];
29
+ total: number;
30
+ }
31
+
32
+ export interface DataResult<T> {
33
+ data: T;
34
+ }
35
+
36
+ async function adminFetch<T>(
37
+ resource: ResourceName,
38
+ method: string,
39
+ params: Record<string, unknown>,
40
+ ): Promise<T> {
41
+ const res = await fetch(`/api/admin/${resource}`, {
42
+ method: "POST",
43
+ headers: { "Content-Type": "application/json" },
44
+ body: JSON.stringify({ resource, method, params }),
45
+ credentials: "include",
46
+ });
47
+
48
+ if (!res.ok) {
49
+ const text = await res.text().catch(() => res.statusText);
50
+ throw new Error(
51
+ `Admin ${resource}/${method} failed (${res.status}): ${text}`,
52
+ );
53
+ }
54
+
55
+ return (await res.json()) as T;
56
+ }
57
+
58
+ export const adminClient = {
59
+ getList<T>(resource: ResourceName, params: ListParams): Promise<ListResult<T>> {
60
+ const {
61
+ pagination = { page: 1, perPage: 25 },
62
+ sort = { field: "id", order: "ASC" as const },
63
+ filter = {},
64
+ } = params;
65
+ return adminFetch<ListResult<T>>(resource, "getList", {
66
+ pagination,
67
+ sort,
68
+ filter,
69
+ });
70
+ },
71
+
72
+ getOne<T>(resource: ResourceName, id: string): Promise<DataResult<T>> {
73
+ return adminFetch<DataResult<T>>(resource, "getOne", { id });
74
+ },
75
+
76
+ update<T>(
77
+ resource: ResourceName,
78
+ id: string,
79
+ data: Record<string, unknown>,
80
+ ): Promise<DataResult<T>> {
81
+ return adminFetch<DataResult<T>>(resource, "update", { id, data });
82
+ },
83
+
84
+ create<T>(
85
+ resource: ResourceName,
86
+ data: Record<string, unknown>,
87
+ ): Promise<DataResult<T>> {
88
+ return adminFetch<DataResult<T>>(resource, "create", { data });
89
+ },
90
+ };
91
+
92
+ /**
93
+ * Impersonation is a separate endpoint (`/api/admin/impersonate`) that takes
94
+ * a non-resource body. Exposed here so the Users table can reuse it without
95
+ * duplicating fetch plumbing.
96
+ */
97
+ export async function impersonateUser({
98
+ userIdToImpersonate,
99
+ reason,
100
+ }: {
101
+ userIdToImpersonate: string;
102
+ reason: string;
103
+ }): Promise<void> {
104
+ const res = await fetch(`/api/admin/impersonate`, {
105
+ method: "POST",
106
+ headers: { "Content-Type": "application/json" },
107
+ body: JSON.stringify({ userIdToImpersonate, reason }),
108
+ credentials: "include",
109
+ });
110
+ if (!res.ok) {
111
+ const text = await res.text().catch(() => res.statusText);
112
+ throw new Error(`Impersonation failed (${res.status}): ${text}`);
113
+ }
114
+ }