@krak-stack/auth 0.2.12 → 0.2.14

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.
@@ -4,18 +4,19 @@ import { useNavigate, useRouter } from "@tanstack/react-router";
4
4
  import { Cause, Effect, Schema } from "effect";
5
5
  import { Atom, AsyncResult } from "effect/unstable/reactivity";
6
6
  import { Building2, Pencil, Trash2, UserCog } from "lucide-react";
7
- import { useState } from "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
- import * as messages from "@/paraglide/messages";
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 { normalizeOrganizationRoles } from "../roles.js";
14
15
  import { AdminOrganizationForm } from "./admin-organization-form.js";
15
16
  import { authClientApi, authHttpClient } from "./auth-client-api.js";
16
17
  import { useKrakstackAuth } from "./auth-provider.js";
17
18
  import { assetUrl, organizationBranding } from "./utils.js";
18
- import { notifyAuthChange } from "./auth-atoms.js";
19
+ import { authSessionAtom, notifyAuthChange } from "./auth-atoms.js";
19
20
  const defaultMessages = {
20
21
  en: {
21
22
  admin_column_created: "Created",
@@ -31,6 +32,17 @@ const defaultMessages = {
31
32
  organization_delete_error: "Unable to delete organization.",
32
33
  organization_delete_title: "Delete organization",
33
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",
34
46
  },
35
47
  fr: {
36
48
  admin_column_created: "Créé",
@@ -46,11 +58,37 @@ const defaultMessages = {
46
58
  organization_delete_error: "Impossible de supprimer l'organisation.",
47
59
  organization_delete_title: "Supprimer l'organisation",
48
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",
49
72
  },
50
73
  };
51
- const labels = (locale) => ({
74
+ export const adminOrganizationsMessages = (locale, overrides) => ({
52
75
  ...defaultMessages[locale],
76
+ ...overrides,
53
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(", ");
54
92
  const organizationDisplay = (organization, locale, baseUrl) => {
55
93
  const branding = organizationBranding(organization, locale);
56
94
  return {
@@ -100,14 +138,28 @@ const organizationsAtom = Atom.family((baseUrl) => Atom.family((key) => {
100
138
  serializationKey: `organizations:${reloadKey}:${JSON.stringify(query)}`,
101
139
  });
102
140
  }));
103
- 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, }) {
104
150
  const auth = useKrakstackAuth();
105
151
  const locale = auth?.locale ?? "en";
106
- const m = labels(locale);
152
+ const m = adminOrganizationsMessages(locale, messageOverrides);
107
153
  const baseUrl = auth?.baseUrl;
108
154
  const projectId = auth?.projectId;
109
155
  const navigate = useNavigate();
110
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
+ });
111
163
  const [impersonateAtom] = useState(() => authClientApi(baseUrl).runtime.fn(({ userId, organizationId, }) => Effect.gen(function* () {
112
164
  const client = yield* authHttpClient(baseUrl);
113
165
  yield* client.auth.adminImpersonateUser({ payload: { userId } });
@@ -124,15 +176,43 @@ export function AdminOrganizationsTable({ onSearchChange, reloadKey = 0, search,
124
176
  })));
125
177
  const impersonate = useAtomSet(impersonateAtom);
126
178
  const impersonateResult = useAtomValue(impersonateAtom);
127
- const [refreshKey, setRefreshKey] = useState(0);
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);
128
195
  const [editingOrganization, setEditingOrganization] = useState(null);
129
196
  const [deletingOrganization, setDeletingOrganization] = useState(null);
130
- const [localSearch, setLocalSearch] = useState({
131
- page: 0,
132
- pageSize: 10,
133
- });
134
- const tableSearch = search ?? localSearch;
135
- 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]);
136
216
  const organizations = AsyncResult.match(result, {
137
217
  onInitial: () => [],
138
218
  onFailure: () => [],
@@ -153,12 +233,15 @@ export function AdminOrganizationsTable({ onSearchChange, reloadKey = 0, search,
153
233
  onFailure: () => false,
154
234
  onSuccess: () => false,
155
235
  });
156
- return (_jsxs("div", { className: "flex flex-col gap-4", children: [error ? _jsx(ErrorMessage, { text: error }) : null, AsyncResult.isFailure(impersonateResult) ? (_jsx(ErrorMessage, { text: messages.organization_impersonate_member_error({}, { locale }) })) : null, _jsx(DataTable, { columnDefs: organizationColumns(m, locale, baseUrl, impersonate, impersonateResult.waiting), 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: {
157
237
  columnVisibility: true,
158
238
  export: { baseName: "organizations" },
159
239
  gallery: false,
160
240
  pagination: { mode: "server", rowCount: total },
161
- refresh: () => setRefreshKey((current) => current + 1),
241
+ refresh: () => setTableRequest((current) => ({
242
+ ...current,
243
+ refreshKey: current.refreshKey + 1,
244
+ })),
162
245
  rowActions: {
163
246
  items: [
164
247
  {
@@ -175,20 +258,32 @@ export function AdminOrganizationsTable({ onSearchChange, reloadKey = 0, search,
175
258
  },
176
259
  ],
177
260
  },
178
- }, initialState: tableSearch, onStateChange: ({ page, pageSize, globalFilter, sort }) => {
179
- 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
+ }));
180
272
  if (onSearchChange) {
181
273
  onSearchChange(nextSearch);
182
274
  }
183
- else {
184
- setLocalSearch(nextSearch);
185
- }
186
- }, 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: () => {
187
279
  setDeletingOrganization(null);
188
- setRefreshKey((current) => current + 1);
280
+ setTableRequest((current) => ({
281
+ ...current,
282
+ refreshKey: current.refreshKey + 1,
283
+ }));
189
284
  } })) : null] }));
190
285
  }
191
- const organizationColumns = (m, locale, baseUrl, impersonate, isImpersonating) => [
286
+ const organizationColumns = (m, locale, baseUrl, impersonate, impersonateAsOrganization, actorUserId, isImpersonating) => [
192
287
  {
193
288
  field: "name",
194
289
  headerName: m.admin_column_organization,
@@ -206,14 +301,14 @@ const organizationColumns = (m, locale, baseUrl, impersonate, isImpersonating) =
206
301
  display: "icon",
207
302
  getItems: (row) => (row.memberPreviews ?? []).map((member) => ({
208
303
  value: member.id,
209
- label: member.name,
304
+ label: `${memberRoleLabel(member.role, m)} — ${member.name}`,
210
305
  imageSrc: assetUrl(member.image, baseUrl),
211
306
  })),
212
307
  getTotalCount: (row) => row.memberCount ?? 0,
213
308
  actionsLabel: m.admin_column_members,
214
309
  itemActions: [
215
310
  {
216
- name: messages.organization_impersonate_member({}, { locale }),
311
+ name: m.organization_impersonate_member,
217
312
  icon: _jsx(UserCog, { className: "size-4" }),
218
313
  disabled: () => isImpersonating,
219
314
  onClick: ({ item, row }) => {
@@ -221,9 +316,30 @@ const organizationColumns = (m, locale, baseUrl, impersonate, isImpersonating) =
221
316
  impersonate({ userId: item.value, organizationId: row.id });
222
317
  },
223
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
+ },
224
333
  ],
225
334
  },
226
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 })),
342
+ },
227
343
  {
228
344
  field: "projects",
229
345
  headerName: m.admin_column_projects,
@@ -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();
@@ -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;