@krak-stack/auth 0.2.11 → 0.2.13

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.
@@ -1,18 +1,22 @@
1
1
  import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
2
  import { useAtomSet, useAtomSubscribe, useAtomValue } from "@effect/atom-react";
3
+ import { useNavigate, useRouter } from "@tanstack/react-router";
3
4
  import { Cause, Effect, Schema } from "effect";
4
5
  import { Atom, AsyncResult } from "effect/unstable/reactivity";
5
- import { Building2, Pencil, Trash2 } from "lucide-react";
6
- import { useState } from "react";
6
+ import { Building2, Pencil, Trash2, UserCog } from "lucide-react";
7
+ import { useEffect, useState } from "react";
7
8
  import { DataTable, DataTableListSummary, } from "@krak-stack/registry/data-table";
8
- import { SortParamsFromString, } from "@krak-stack/registry/query";
9
+ import { Query, SortParamsFromString, } from "@krak-stack/registry/query";
9
10
  import { ErrorMessage } from "@krak-stack/registry/effect-form";
10
11
  import { AppBrand } from "@krak-stack/registry/app-brand";
12
+ import { Badge } from "@/components/ui/badge";
11
13
  import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, } from "@/components/ui/alert-dialog";
14
+ import { normalizeOrganizationRoles } from "../roles.js";
12
15
  import { AdminOrganizationForm } from "./admin-organization-form.js";
13
16
  import { authClientApi, authHttpClient } from "./auth-client-api.js";
14
17
  import { useKrakstackAuth } from "./auth-provider.js";
15
18
  import { assetUrl, organizationBranding } from "./utils.js";
19
+ import { authSessionAtom, notifyAuthChange } from "./auth-atoms.js";
16
20
  const defaultMessages = {
17
21
  en: {
18
22
  admin_column_created: "Created",
@@ -28,6 +32,17 @@ const defaultMessages = {
28
32
  organization_delete_error: "Unable to delete organization.",
29
33
  organization_delete_title: "Delete organization",
30
34
  organization_fetch_error: "Unable to load organizations.",
35
+ organization_impersonate_member: "Impersonate",
36
+ organization_impersonate_member_as_organization: "Impersonate (as organization)",
37
+ organization_impersonate_member_as_organization_error: "Unable to impersonate the member as this organization.",
38
+ organization_impersonate_member_error: "Unable to impersonate the member and activate this organization.",
39
+ organization_role_admin: "Admin",
40
+ organization_role_member: "Member",
41
+ organization_role_owner: "Owner",
42
+ organization_role_support: "Support",
43
+ organization_type: "Type",
44
+ organization_type_personal: "Personal",
45
+ organization_type_standard: "Organization",
31
46
  },
32
47
  fr: {
33
48
  admin_column_created: "Créé",
@@ -43,11 +58,37 @@ const defaultMessages = {
43
58
  organization_delete_error: "Impossible de supprimer l'organisation.",
44
59
  organization_delete_title: "Supprimer l'organisation",
45
60
  organization_fetch_error: "Impossible de charger les organisations.",
61
+ organization_impersonate_member: "Emprunter l’identité",
62
+ organization_impersonate_member_as_organization: "Emprunter l’identité (en tant qu’organisation)",
63
+ organization_impersonate_member_as_organization_error: "Impossible d’emprunter l’identité du membre en tant que cette organisation.",
64
+ organization_impersonate_member_error: "Impossible d’emprunter l’identité du membre et d’activer cette organisation.",
65
+ organization_role_admin: "Admin",
66
+ organization_role_member: "Membre",
67
+ organization_role_owner: "Propriétaire",
68
+ organization_role_support: "Support",
69
+ organization_type: "Type",
70
+ organization_type_personal: "Personnelle",
71
+ organization_type_standard: "Organisation",
46
72
  },
47
73
  };
48
- const labels = (locale) => ({
74
+ export const adminOrganizationsMessages = (locale, overrides) => ({
49
75
  ...defaultMessages[locale],
76
+ ...overrides,
50
77
  });
78
+ const memberRoleLabel = (role, m) => normalizeOrganizationRoles(role)
79
+ .map((item) => {
80
+ switch (item) {
81
+ case "owner":
82
+ return m.organization_role_owner;
83
+ case "admin":
84
+ return m.organization_role_admin;
85
+ case "support":
86
+ return m.organization_role_support;
87
+ case "member":
88
+ return m.organization_role_member;
89
+ }
90
+ })
91
+ .join(", ");
51
92
  const organizationDisplay = (organization, locale, baseUrl) => {
52
93
  const branding = organizationBranding(organization, locale);
53
94
  return {
@@ -97,21 +138,81 @@ const organizationsAtom = Atom.family((baseUrl) => Atom.family((key) => {
97
138
  serializationKey: `organizations:${reloadKey}:${JSON.stringify(query)}`,
98
139
  });
99
140
  }));
100
- export function AdminOrganizationsTable({ onSearchChange, reloadKey = 0, search, }) {
141
+ const makeAdminOrganizationsTableAtoms = (initial) => {
142
+ const requestAtom = Atom.make(initial);
143
+ const resultAtom = Atom.optimistic(Atom.make((get) => {
144
+ const request = get(requestAtom);
145
+ return get.result(organizationsAtom(request.baseUrl)(adminOrganizationsFamilyKey(request.search, request.projectId, request.reloadKey + request.refreshKey)), { suspendOnWaiting: true });
146
+ }));
147
+ return { requestAtom, resultAtom };
148
+ };
149
+ export function AdminOrganizationsTable({ messages: messageOverrides, onSearchChange, reloadKey = 0, search, }) {
101
150
  const auth = useKrakstackAuth();
102
151
  const locale = auth?.locale ?? "en";
103
- const m = labels(locale);
152
+ const m = adminOrganizationsMessages(locale, messageOverrides);
104
153
  const baseUrl = auth?.baseUrl;
105
154
  const projectId = auth?.projectId;
106
- const [refreshKey, setRefreshKey] = useState(0);
155
+ const navigate = useNavigate();
156
+ const router = useRouter();
157
+ const sessionResult = useAtomValue(authSessionAtom(baseUrl));
158
+ const actorUserId = AsyncResult.match(sessionResult, {
159
+ onInitial: () => null,
160
+ onFailure: () => null,
161
+ onSuccess: ({ value }) => value?.user.id ?? null,
162
+ });
163
+ const [impersonateAtom] = useState(() => authClientApi(baseUrl).runtime.fn(({ userId, organizationId, }) => Effect.gen(function* () {
164
+ const client = yield* authHttpClient(baseUrl);
165
+ yield* client.auth.adminImpersonateUser({ payload: { userId } });
166
+ yield* client.auth
167
+ .organizationSetActive({ payload: { organizationId } })
168
+ .pipe(Effect.tapError(() => client.auth.adminStopImpersonating({ payload: {} })), Effect.ensuring(Effect.sync(notifyAuthChange)));
169
+ yield* Effect.tryPromise({
170
+ try: async () => {
171
+ await navigate({ to: "/" });
172
+ await router.invalidate();
173
+ },
174
+ catch: (cause) => cause instanceof Error ? cause : new Error(String(cause)),
175
+ });
176
+ })));
177
+ const impersonate = useAtomSet(impersonateAtom);
178
+ const impersonateResult = useAtomValue(impersonateAtom);
179
+ const [impersonateAsOrganizationAtom] = useState(() => authClientApi(baseUrl).runtime.fn(({ actorUserId, organizationId, targetUserId, }) => Effect.gen(function* () {
180
+ const client = yield* authHttpClient(baseUrl);
181
+ yield* client.auth.organizationImpersonateUser({
182
+ payload: { actorUserId, organizationId, targetUserId },
183
+ });
184
+ notifyAuthChange();
185
+ yield* Effect.tryPromise({
186
+ try: async () => {
187
+ await navigate({ to: "/" });
188
+ await router.invalidate();
189
+ },
190
+ catch: (cause) => cause instanceof Error ? cause : new Error(String(cause)),
191
+ });
192
+ })));
193
+ const impersonateAsOrganization = useAtomSet(impersonateAsOrganizationAtom);
194
+ const impersonateAsOrganizationResult = useAtomValue(impersonateAsOrganizationAtom);
107
195
  const [editingOrganization, setEditingOrganization] = useState(null);
108
196
  const [deletingOrganization, setDeletingOrganization] = useState(null);
109
- const [localSearch, setLocalSearch] = useState({
110
- page: 0,
111
- pageSize: 10,
112
- });
113
- const tableSearch = search ?? localSearch;
114
- const result = useAtomValue(organizationsAtom(baseUrl)(adminOrganizationsFamilyKey(tableSearch, projectId, reloadKey + refreshKey)));
197
+ const [tableAtoms] = useState(() => makeAdminOrganizationsTableAtoms({
198
+ baseUrl,
199
+ projectId,
200
+ reloadKey,
201
+ refreshKey: 0,
202
+ search: search ?? Schema.decodeUnknownSync(Query)({}),
203
+ }));
204
+ const setTableRequest = useAtomSet(tableAtoms.requestAtom);
205
+ const tableRequest = useAtomValue(tableAtoms.requestAtom);
206
+ const result = useAtomValue(tableAtoms.resultAtom);
207
+ useEffect(() => {
208
+ setTableRequest((current) => ({
209
+ ...current,
210
+ baseUrl,
211
+ projectId,
212
+ reloadKey,
213
+ search: search ?? current.search,
214
+ }));
215
+ }, [baseUrl, projectId, reloadKey, search, setTableRequest]);
115
216
  const organizations = AsyncResult.match(result, {
116
217
  onInitial: () => [],
117
218
  onFailure: () => [],
@@ -132,12 +233,15 @@ export function AdminOrganizationsTable({ onSearchChange, reloadKey = 0, search,
132
233
  onFailure: () => false,
133
234
  onSuccess: () => false,
134
235
  });
135
- return (_jsxs("div", { className: "flex flex-col gap-4", children: [error ? _jsx(ErrorMessage, { text: error }) : null, _jsx(DataTable, { columnDefs: organizationColumns(m, locale, baseUrl), rowData: organizations, features: {
236
+ return (_jsxs("div", { className: "flex flex-col gap-4", children: [error ? _jsx(ErrorMessage, { text: error }) : null, AsyncResult.isFailure(impersonateResult) ? (_jsx(ErrorMessage, { text: m.organization_impersonate_member_error })) : null, AsyncResult.isFailure(impersonateAsOrganizationResult) ? (_jsx(ErrorMessage, { text: m.organization_impersonate_member_as_organization_error })) : null, _jsx(DataTable, { columnDefs: organizationColumns(m, locale, baseUrl, impersonate, impersonateAsOrganization, actorUserId, impersonateResult.waiting || impersonateAsOrganizationResult.waiting), rowData: organizations, features: {
136
237
  columnVisibility: true,
137
238
  export: { baseName: "organizations" },
138
239
  gallery: false,
139
240
  pagination: { mode: "server", rowCount: total },
140
- refresh: () => setRefreshKey((current) => current + 1),
241
+ refresh: () => setTableRequest((current) => ({
242
+ ...current,
243
+ refreshKey: current.refreshKey + 1,
244
+ })),
141
245
  rowActions: {
142
246
  items: [
143
247
  {
@@ -154,20 +258,32 @@ export function AdminOrganizationsTable({ onSearchChange, reloadKey = 0, search,
154
258
  },
155
259
  ],
156
260
  },
157
- }, initialState: tableSearch, onStateChange: ({ page, pageSize, globalFilter, sort }) => {
158
- const nextSearch = { page, pageSize, globalFilter, sort };
261
+ }, state: tableRequest.search, onStateChange: ({ page, pageSize, globalFilter, sort }) => {
262
+ const nextSearch = Schema.decodeUnknownSync(Query)({
263
+ page,
264
+ pageSize,
265
+ globalFilter,
266
+ sort,
267
+ });
268
+ setTableRequest((current) => ({
269
+ ...current,
270
+ search: nextSearch,
271
+ }));
159
272
  if (onSearchChange) {
160
273
  onSearchChange(nextSearch);
161
274
  }
162
- else {
163
- setLocalSearch(nextSearch);
164
- }
165
- }, status: { loading: isLoading } }), editingOrganization ? (_jsx(AdminOrganizationForm, { organization: editingOrganization, onClose: () => setEditingOrganization(null), onSaved: () => setRefreshKey((current) => current + 1) })) : null, deletingOrganization ? (_jsx(DeleteOrganizationDialog, { labels: m, organization: deletingOrganization, baseUrl: baseUrl, onClose: () => setDeletingOrganization(null), onDeleted: () => {
275
+ }, status: { loading: isLoading } }), editingOrganization ? (_jsx(AdminOrganizationForm, { organization: editingOrganization, onClose: () => setEditingOrganization(null), onSaved: () => setTableRequest((current) => ({
276
+ ...current,
277
+ refreshKey: current.refreshKey + 1,
278
+ })) })) : null, deletingOrganization ? (_jsx(DeleteOrganizationDialog, { labels: m, organization: deletingOrganization, baseUrl: baseUrl, onClose: () => setDeletingOrganization(null), onDeleted: () => {
166
279
  setDeletingOrganization(null);
167
- setRefreshKey((current) => current + 1);
280
+ setTableRequest((current) => ({
281
+ ...current,
282
+ refreshKey: current.refreshKey + 1,
283
+ }));
168
284
  } })) : null] }));
169
285
  }
170
- const organizationColumns = (m, locale, baseUrl) => [
286
+ const organizationColumns = (m, locale, baseUrl, impersonate, impersonateAsOrganization, actorUserId, isImpersonating) => [
171
287
  {
172
288
  field: "name",
173
289
  headerName: m.admin_column_organization,
@@ -179,7 +295,50 @@ const organizationColumns = (m, locale, baseUrl) => [
179
295
  {
180
296
  field: "memberCount",
181
297
  headerName: m.admin_column_members,
182
- cellRenderer: ({ data }) => (_jsx(OrganizationMembers, { baseUrl: baseUrl, members: data.memberPreviews ?? [], total: data.memberCount ?? 0 })),
298
+ type: "list",
299
+ typeOptions: {
300
+ emptyLabel: "0",
301
+ display: "icon",
302
+ getItems: (row) => (row.memberPreviews ?? []).map((member) => ({
303
+ value: member.id,
304
+ label: `${memberRoleLabel(member.role, m)} — ${member.name}`,
305
+ imageSrc: assetUrl(member.image, baseUrl),
306
+ })),
307
+ getTotalCount: (row) => row.memberCount ?? 0,
308
+ actionsLabel: m.admin_column_members,
309
+ itemActions: [
310
+ {
311
+ name: m.organization_impersonate_member,
312
+ icon: _jsx(UserCog, { className: "size-4" }),
313
+ disabled: () => isImpersonating,
314
+ onClick: ({ item, row }) => {
315
+ if (item.value)
316
+ impersonate({ userId: item.value, organizationId: row.id });
317
+ },
318
+ },
319
+ {
320
+ name: m.organization_impersonate_member_as_organization,
321
+ icon: _jsx(Building2, { className: "size-4" }),
322
+ disabled: () => isImpersonating || !actorUserId,
323
+ onClick: ({ item, row }) => {
324
+ if (item.value && actorUserId) {
325
+ impersonateAsOrganization({
326
+ actorUserId,
327
+ organizationId: row.id,
328
+ targetUserId: item.value,
329
+ });
330
+ }
331
+ },
332
+ },
333
+ ],
334
+ },
335
+ },
336
+ {
337
+ field: "userId",
338
+ headerName: m.organization_type,
339
+ cellRenderer: ({ data }) => (_jsx(Badge, { variant: data.userId ? "secondary" : "outline", children: data.userId
340
+ ? m.organization_type_personal
341
+ : m.organization_type_standard })),
183
342
  },
184
343
  {
185
344
  field: "projects",
@@ -191,7 +350,7 @@ const organizationColumns = (m, locale, baseUrl) => [
191
350
  value: project.id,
192
351
  icon: logo ? (_jsx("img", { alt: "", className: "size-full object-cover", src: logo })) : (initials(project.name)),
193
352
  };
194
- }), variant: "icon" })),
353
+ }), display: "icon" })),
195
354
  },
196
355
  {
197
356
  field: "createdAt",
@@ -205,16 +364,6 @@ const initials = (name) => name
205
364
  .map((part) => part[0])
206
365
  .join("")
207
366
  .toUpperCase();
208
- function OrganizationMembers({ baseUrl, members, total, }) {
209
- return (_jsx(DataTableListSummary, { emptyLabel: "0", items: members.map((member) => {
210
- const image = assetUrl(member.image, baseUrl);
211
- return {
212
- label: member.name,
213
- value: member.id,
214
- icon: image ? (_jsx("img", { alt: "", className: "size-full object-cover", src: image })) : (initials(member.name)),
215
- };
216
- }), totalCount: total, variant: "icon" }));
217
- }
218
367
  function DeleteOrganizationDialog({ baseUrl, labels: m, organization, onClose, onDeleted, }) {
219
368
  const [deleteOrganizationAtom] = useState(() => authClientApi(baseUrl).runtime.fn((id) => Effect.flatMap(authHttpClient(baseUrl), (http) => http.admin.deleteOrganization({ params: { id } }))));
220
369
  const deleteOrganization = useAtomSet(deleteOrganizationAtom);
@@ -2,16 +2,16 @@ import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-run
2
2
  import { useAtomSet, useAtomValue } from "@effect/atom-react";
3
3
  import { useNavigate, useRouter } from "@tanstack/react-router";
4
4
  import { Atom, AsyncResult } from "effect/unstable/reactivity";
5
- import { Effect, Option, Schema } from "effect";
6
- import { Ban, Building2, Loader2, ShieldOff, UserCog, UserIcon, } from "lucide-react";
7
- import { useState } from "react";
5
+ import { Effect, Schema } from "effect";
6
+ import { Ban, Loader2, ShieldOff, UserCog, UserIcon } from "lucide-react";
7
+ import { useEffect, useState } from "react";
8
8
  import { DataTable, DataTableListSummary, } from "@krak-stack/registry/data-table";
9
- import { SortParamsFromString, } from "@krak-stack/registry/query";
9
+ import { Query, SortParamsFromString, } from "@krak-stack/registry/query";
10
10
  import { ErrorMessage } from "@krak-stack/registry/effect-form";
11
11
  import { AppBrand } from "@krak-stack/registry/app-brand";
12
12
  import { Badge } from "@/components/ui/badge";
13
13
  import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, } from "@/components/ui/alert-dialog";
14
- import { authSessionAtom, notifyAuthChange } from "./auth-atoms.js";
14
+ import { notifyAuthChange } from "./auth-atoms.js";
15
15
  import { authClientApi, authHttpClient } from "./auth-client-api.js";
16
16
  import { useKrakstackAuth } from "./auth-provider.js";
17
17
  import { assetUrl } from "./utils.js";
@@ -19,7 +19,6 @@ const defaultMessages = {
19
19
  en: {
20
20
  admin_action_ban: "Ban",
21
21
  admin_action_impersonate: "Impersonate",
22
- admin_action_impersonate_organization: "Impersonate as organization",
23
22
  admin_action_unban: "Unban",
24
23
  admin_ban_description: "Are you sure you want to ban {name} ({email})? They will not be able to sign in.",
25
24
  admin_ban_title: "Ban user",
@@ -36,8 +35,6 @@ const defaultMessages = {
36
35
  admin_error_access_required: "Admin access is required.",
37
36
  admin_error_ban: "Unable to ban user.",
38
37
  admin_error_impersonate: "Unable to impersonate user.",
39
- admin_error_impersonate_organization: "Unable to impersonate user as organization.",
40
- admin_error_organization_required: "Select an active organization first.",
41
38
  admin_error_unban: "Unable to unban user.",
42
39
  admin_status_active: "Active",
43
40
  admin_status_banned: "Banned",
@@ -49,7 +46,6 @@ const defaultMessages = {
49
46
  fr: {
50
47
  admin_action_ban: "Bannir",
51
48
  admin_action_impersonate: "Emprunter l'identité",
52
- admin_action_impersonate_organization: "Emprunter l'identité pour l'organisation",
53
49
  admin_action_unban: "Débannir",
54
50
  admin_ban_description: "Êtes-vous sûr de vouloir bannir {name} ({email}) ? Il ne pourra plus se connecter.",
55
51
  admin_ban_title: "Bannir l'utilisateur",
@@ -66,8 +62,6 @@ const defaultMessages = {
66
62
  admin_error_access_required: "Accès administrateur requis.",
67
63
  admin_error_ban: "Impossible de bannir l'utilisateur.",
68
64
  admin_error_impersonate: "Impossible d'emprunter l'identité de l'utilisateur.",
69
- admin_error_impersonate_organization: "Impossible d'emprunter l'identité pour l'organisation.",
70
- admin_error_organization_required: "Sélectionnez d'abord une organisation active.",
71
65
  admin_error_unban: "Impossible de débannir l'utilisateur.",
72
66
  admin_status_active: "Actif",
73
67
  admin_status_banned: "Banni",
@@ -126,9 +120,13 @@ const usersAtom = Atom.family((baseUrl) => Atom.family((key) => {
126
120
  serializationKey: `admin-users:${reloadKey}:${JSON.stringify(query)}`,
127
121
  });
128
122
  }));
129
- const activeOrganizationId = (session) => {
130
- const value = session?.session?.activeOrganizationId;
131
- return Option.getOrNull(Schema.decodeUnknownOption(Schema.NonEmptyString)(value));
123
+ const makeAdminUsersTableAtoms = (initial) => {
124
+ const requestAtom = Atom.make(initial);
125
+ const resultAtom = Atom.optimistic(Atom.make((get) => {
126
+ const request = get(requestAtom);
127
+ return get.result(usersAtom(request.baseUrl)(adminUsersFamilyKey(request.search, request.projectId, request.reloadKey + request.refreshKey)), { suspendOnWaiting: true });
128
+ }));
129
+ return { requestAtom, resultAtom };
132
130
  };
133
131
  export function AdminUsersTable({ onSearchChange, reloadKey = 0, search, }) {
134
132
  const navigate = useNavigate();
@@ -136,22 +134,27 @@ export function AdminUsersTable({ onSearchChange, reloadKey = 0, search, }) {
136
134
  const auth = useKrakstackAuth();
137
135
  const m = labels(auth?.locale ?? "en");
138
136
  const baseUrl = auth?.baseUrl;
139
- const sessionAtom = authSessionAtom(baseUrl);
140
- const sessionResult = useAtomValue(sessionAtom);
141
- const session = AsyncResult.match(sessionResult, {
142
- onInitial: () => null,
143
- onFailure: () => null,
144
- onSuccess: ({ value }) => value,
145
- });
146
137
  const projectId = auth?.projectId;
147
138
  const [impersonateError, setImpersonateError] = useState("");
148
- const [refreshKey, setRefreshKey] = useState(0);
149
- const [localSearch, setLocalSearch] = useState({
150
- page: 0,
151
- pageSize: 10,
152
- });
153
- const tableSearch = search ?? localSearch;
154
- const result = useAtomValue(usersAtom(baseUrl)(adminUsersFamilyKey(tableSearch, projectId, reloadKey + refreshKey)));
139
+ const [tableAtoms] = useState(() => makeAdminUsersTableAtoms({
140
+ baseUrl,
141
+ projectId,
142
+ reloadKey,
143
+ refreshKey: 0,
144
+ search: search ?? Schema.decodeUnknownSync(Query)({}),
145
+ }));
146
+ const setTableRequest = useAtomSet(tableAtoms.requestAtom);
147
+ const tableRequest = useAtomValue(tableAtoms.requestAtom);
148
+ const result = useAtomValue(tableAtoms.resultAtom);
149
+ useEffect(() => {
150
+ setTableRequest((current) => ({
151
+ ...current,
152
+ baseUrl,
153
+ projectId,
154
+ reloadKey,
155
+ search: search ?? current.search,
156
+ }));
157
+ }, [baseUrl, projectId, reloadKey, search, setTableRequest]);
155
158
  const [banningUser, setBanningUser] = useState(null);
156
159
  const [unbanningUser, setUnbanningUser] = useState(null);
157
160
  const [impersonateUserAtom] = useState(() => authClientApi(baseUrl).runtime.fn((userId) => Effect.gen(function* () {
@@ -170,29 +173,9 @@ export function AdminUsersTable({ onSearchChange, reloadKey = 0, search, }) {
170
173
  }).pipe(Effect.catch((cause) => Effect.sync(() => setImpersonateError(cause instanceof Error
171
174
  ? cause.message
172
175
  : m.admin_error_impersonate))))));
173
- const [impersonateOrganizationUserAtom] = useState(() => authClientApi(baseUrl).runtime.fn(({ actorUserId, organizationId, targetUserId, }) => Effect.gen(function* () {
174
- const client = yield* authHttpClient(baseUrl);
175
- yield* client.auth.organizationImpersonateUser({
176
- payload: { organizationId, actorUserId, targetUserId },
177
- });
178
- notifyAuthChange();
179
- yield* Effect.tryPromise({
180
- try: async () => {
181
- await navigate({ to: "/" });
182
- await router.invalidate();
183
- },
184
- catch: (cause) => cause instanceof Error
185
- ? cause
186
- : new Error(m.admin_error_impersonate_organization),
187
- });
188
- }).pipe(Effect.catch((cause) => Effect.sync(() => setImpersonateError(cause instanceof Error
189
- ? cause.message
190
- : m.admin_error_impersonate_organization))))));
191
176
  const impersonateUser = useAtomSet(impersonateUserAtom);
192
177
  const impersonateUserResult = useAtomValue(impersonateUserAtom);
193
- const impersonateOrganizationUser = useAtomSet(impersonateOrganizationUserAtom);
194
- const impersonateOrganizationUserResult = useAtomValue(impersonateOrganizationUserAtom);
195
- const isImpersonating = impersonateUserResult.waiting || impersonateOrganizationUserResult.waiting;
178
+ const isImpersonating = impersonateUserResult.waiting;
196
179
  const users = AsyncResult.match(result, {
197
180
  onInitial: () => [],
198
181
  onFailure: () => [],
@@ -218,7 +201,10 @@ export function AdminUsersTable({ onSearchChange, reloadKey = 0, search, }) {
218
201
  export: { baseName: "users" },
219
202
  gallery: false,
220
203
  pagination: { mode: "server", rowCount: total },
221
- refresh: () => setRefreshKey((current) => current + 1),
204
+ refresh: () => setTableRequest((current) => ({
205
+ ...current,
206
+ refreshKey: current.refreshKey + 1,
207
+ })),
222
208
  rowActions: {
223
209
  items: [
224
210
  {
@@ -230,28 +216,6 @@ export function AdminUsersTable({ onSearchChange, reloadKey = 0, search, }) {
230
216
  },
231
217
  visible: (user) => !user.banned,
232
218
  },
233
- {
234
- name: m.admin_action_impersonate_organization,
235
- icon: isImpersonating ? (_jsx(Loader2, { className: "size-4 animate-spin" })) : (_jsx(Building2, { className: "size-4" })),
236
- onClick: (user) => {
237
- setImpersonateError("");
238
- if (!session?.user?.id) {
239
- setImpersonateError(m.admin_error_access_required);
240
- return;
241
- }
242
- const organizationId = activeOrganizationId(session);
243
- if (!organizationId) {
244
- setImpersonateError(m.admin_error_organization_required);
245
- return;
246
- }
247
- impersonateOrganizationUser({
248
- organizationId,
249
- actorUserId: session.user.id,
250
- targetUserId: user.id,
251
- });
252
- },
253
- visible: (user) => !user.banned,
254
- },
255
219
  {
256
220
  name: m.admin_action_ban,
257
221
  icon: _jsx(Ban, { className: "size-4" }),
@@ -267,15 +231,27 @@ export function AdminUsersTable({ onSearchChange, reloadKey = 0, search, }) {
267
231
  },
268
232
  ],
269
233
  },
270
- }, initialState: tableSearch, onStateChange: ({ page, pageSize, globalFilter, sort }) => {
271
- const nextSearch = { page, pageSize, globalFilter, sort };
234
+ }, state: tableRequest.search, onStateChange: ({ page, pageSize, globalFilter, sort }) => {
235
+ const nextSearch = Schema.decodeUnknownSync(Query)({
236
+ page,
237
+ pageSize,
238
+ globalFilter,
239
+ sort,
240
+ });
241
+ setTableRequest((current) => ({
242
+ ...current,
243
+ search: nextSearch,
244
+ }));
272
245
  if (onSearchChange) {
273
246
  onSearchChange(nextSearch);
274
247
  }
275
- else {
276
- setLocalSearch(nextSearch);
277
- }
278
- }, status: { loading: isLoading } }), banningUser ? (_jsx(BanUserDialog, { labels: m, baseUrl: baseUrl, user: banningUser, onBanned: () => setRefreshKey((current) => current + 1), onClose: () => setBanningUser(null) })) : null, unbanningUser ? (_jsx(UnbanUserDialog, { labels: m, baseUrl: baseUrl, user: unbanningUser, onUnbanned: () => setRefreshKey((current) => current + 1), onClose: () => setUnbanningUser(null) })) : null] }));
248
+ }, status: { loading: isLoading } }), banningUser ? (_jsx(BanUserDialog, { labels: m, baseUrl: baseUrl, user: banningUser, onBanned: () => setTableRequest((current) => ({
249
+ ...current,
250
+ refreshKey: current.refreshKey + 1,
251
+ })), onClose: () => setBanningUser(null) })) : null, unbanningUser ? (_jsx(UnbanUserDialog, { labels: m, baseUrl: baseUrl, user: unbanningUser, onUnbanned: () => setTableRequest((current) => ({
252
+ ...current,
253
+ refreshKey: current.refreshKey + 1,
254
+ })), onClose: () => setUnbanningUser(null) })) : null] }));
279
255
  }
280
256
  export function useAdminUsersTotal(search) {
281
257
  const auth = useKrakstackAuth();
@@ -305,7 +281,7 @@ const userColumns = (m, baseUrl) => [
305
281
  value: organization.id,
306
282
  icon: logo ? (_jsx("img", { alt: "", className: "size-full object-cover", src: logo })) : (initials(organization.name)),
307
283
  };
308
- }), variant: "icon" })),
284
+ }), display: "icon" })),
309
285
  },
310
286
  {
311
287
  field: "projects",
@@ -317,7 +293,7 @@ const userColumns = (m, baseUrl) => [
317
293
  value: project.id,
318
294
  icon: logo ? (_jsx("img", { alt: "", className: "size-full object-cover", src: logo })) : (initials(project.name)),
319
295
  };
320
- }), variant: "icon" })),
296
+ }), display: "icon" })),
321
297
  },
322
298
  {
323
299
  field: "emailVerified",
@@ -0,0 +1,6 @@
1
+ export declare const AssociatedProjectsNotice: ({ baseUrl, getSummary, organizationId, viewLabel, }: {
2
+ baseUrl?: string | undefined;
3
+ getSummary: (count: number) => string;
4
+ organizationId?: string | null;
5
+ viewLabel: string;
6
+ }) => import("react").JSX.Element | null;
@@ -0,0 +1,24 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { useAtomValue } from "@effect/atom-react";
3
+ import { AsyncResult, Atom } from "effect/unstable/reactivity";
4
+ import { Badge } from "@/components/ui/badge";
5
+ import { authClientApi } from "./auth-client-api.js";
6
+ const associatedProjectsAtom = Atom.family((baseUrl) => Atom.family((organizationId) => authClientApi(baseUrl).query("authExtra", "listAssociatedProjects", {
7
+ query: organizationId ? { organizationId } : {},
8
+ timeToLive: "1 minute",
9
+ reactivityKeys: [
10
+ "associated-projects",
11
+ organizationId ? `organization:${organizationId}` : "current-user",
12
+ ],
13
+ })));
14
+ export const AssociatedProjectsNotice = ({ baseUrl, getSummary, organizationId = null, viewLabel, }) => {
15
+ const result = useAtomValue(associatedProjectsAtom(baseUrl)(organizationId));
16
+ const projects = AsyncResult.match(result, {
17
+ onInitial: () => [],
18
+ onFailure: () => [],
19
+ onSuccess: ({ value }) => Array.from(value),
20
+ });
21
+ if (projects.length <= 1)
22
+ return null;
23
+ return (_jsxs("details", { className: "border-primary/60 text-muted-foreground border-l-2 pl-3 text-sm", children: [_jsxs("summary", { className: "cursor-pointer list-none [&::-webkit-details-marker]:hidden", children: [getSummary(projects.length), " ", _jsx("span", { className: "text-foreground underline underline-offset-4", children: viewLabel })] }), _jsx("div", { className: "mt-2 flex flex-wrap gap-2", children: projects.map((project) => (_jsx(Badge, { variant: "secondary", children: project.name }, project.id))) })] }));
24
+ };
@@ -62,7 +62,7 @@ export declare const authSessionAtom: (arg: string | undefined) => Atom.Atom<Asy
62
62
  readonly createdAt: Date;
63
63
  readonly updatedAt: Date;
64
64
  };
65
- } | null, import("../auth/schema.js").AuthBadRequest>>;
65
+ } | null, import("../auth/schema.js").AuthBadRequest | import("../auth/schema.js").AuthConflict | import("../auth/schema.js").AuthExpectationFailed | import("../auth/schema.js").AuthForbidden | import("../auth/schema.js").AuthInternalServerError | import("../auth/schema.js").AuthNotFound | import("../auth/schema.js").AuthTooManyRequests | import("../auth/schema.js").AuthUnauthorized>>;
66
66
  export declare const authOrganizationsAtom: (arg: string | undefined) => Atom.Atom<AsyncResult.AsyncResult<readonly {
67
67
  readonly id: string;
68
68
  readonly name: string;
@@ -74,7 +74,7 @@ export declare const authOrganizationsAtom: (arg: string | undefined) => Atom.At
74
74
  readonly userId?: string | null | undefined;
75
75
  readonly parentId?: string | null | undefined;
76
76
  readonly createdAt: Date;
77
- }[], import("../auth/schema.js").AuthBadRequest>>;
77
+ }[], import("../auth/schema.js").AuthBadRequest | import("../auth/schema.js").AuthConflict | import("../auth/schema.js").AuthExpectationFailed | import("../auth/schema.js").AuthForbidden | import("../auth/schema.js").AuthInternalServerError | import("../auth/schema.js").AuthNotFound | import("../auth/schema.js").AuthTooManyRequests | import("../auth/schema.js").AuthUnauthorized>>;
78
78
  export declare const activeAuthOrganizationAtom: (arg: string | undefined) => (arg: string | null) => Atom.Atom<AsyncResult.AsyncResult<{
79
79
  readonly id: string;
80
80
  readonly name: string;
@@ -143,6 +143,6 @@ export declare const activeAuthOrganizationAtom: (arg: string | undefined) => (a
143
143
  readonly expiresAt: Date;
144
144
  readonly createdAt?: Date | undefined;
145
145
  }[];
146
- } | null, import("../auth/schema.js").AuthBadRequest>>;
146
+ } | null, import("../auth/schema.js").AuthBadRequest | import("../auth/schema.js").AuthConflict | import("../auth/schema.js").AuthExpectationFailed | import("../auth/schema.js").AuthForbidden | import("../auth/schema.js").AuthInternalServerError | import("../auth/schema.js").AuthNotFound | import("../auth/schema.js").AuthTooManyRequests | import("../auth/schema.js").AuthUnauthorized>>;
147
147
  export declare const getLastUsedLoginMethod: () => string | null;
148
148
  export declare const notifyAuthChange: () => void;