@krak-stack/auth 0.1.71 → 0.2.0
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.
- package/README.md +4 -3
- package/dist/access.d.ts +4 -4
- package/dist/access.js +10 -4
- package/dist/admin/api.group.d.ts +17 -17
- package/dist/admin/api.group.js +2 -2
- package/dist/admin/schema.d.ts +18 -18
- package/dist/admin/schema.js +3 -3
- package/dist/api.d.ts +2093 -631
- package/dist/api.js +7 -7
- package/dist/auth/api.group.d.ts +793 -0
- package/dist/auth/api.group.js +241 -0
- package/dist/auth/schema.d.ts +800 -0
- package/dist/auth/schema.js +625 -0
- package/dist/components/admin-organization-form.d.ts +1 -1
- package/dist/components/admin-organization-form.js +16 -18
- package/dist/components/admin-organizations.js +52 -45
- package/dist/components/admin-users.js +115 -137
- package/dist/components/api-key-edit-form.d.ts +4 -3
- package/dist/components/api-key-edit-form.js +32 -27
- package/dist/components/api-key-permissions.d.ts +1 -1
- package/dist/components/api-key-rate-limit.d.ts +1 -1
- package/dist/components/api-key-referrers.d.ts +3 -2
- package/dist/components/api-key-referrers.js +2 -3
- package/dist/components/api-key.d.ts +0 -9
- package/dist/components/api-key.js +0 -39
- package/dist/components/auth-atoms.d.ts +178 -0
- package/dist/components/auth-atoms.js +46 -0
- package/dist/components/auth-client-api.d.ts +2474 -142
- package/dist/components/auth-client-api.js +14 -10
- package/dist/components/auth-forms.d.ts +1 -3
- package/dist/components/auth-forms.js +168 -195
- package/dist/components/auth-provider.d.ts +3 -7
- package/dist/components/auth-provider.js +56 -30
- package/dist/components/has-permission.js +1 -1
- package/dist/components/index.d.ts +19 -20
- package/dist/components/index.js +13 -13
- package/dist/components/member-required.d.ts +1 -3
- package/dist/components/member-required.js +102 -78
- package/dist/components/organization-switcher.d.ts +4 -6
- package/dist/components/organization-switcher.js +469 -323
- package/dist/components/project-access-matrix.d.ts +1 -1
- package/dist/components/project-access-matrix.js +9 -13
- package/dist/components/user-button.d.ts +5 -3
- package/dist/components/user-button.js +264 -314
- package/dist/components/utils.d.ts +3 -1
- package/dist/components/utils.js +4 -11
- package/dist/extra/api.group.d.ts +3 -3
- package/dist/extra/api.group.js +6 -6
- package/dist/extra/schema.js +1 -1
- package/dist/index.d.ts +11 -12
- package/dist/index.js +11 -12
- package/dist/query.d.ts +2 -2
- package/dist/roles.d.ts +5 -4
- package/dist/roles.js +11 -7
- package/dist/schema.d.ts +1 -1
- package/dist/schema.js +26 -19
- package/dist/server/actor.d.ts +20 -22
- package/dist/server/actor.js +14 -17
- package/dist/server/api.group.js +2 -2
- package/dist/server/index.d.ts +14 -14
- package/dist/server/index.js +8 -8
- package/dist/server/middleware.d.ts +1 -1
- package/dist/server/middleware.js +1 -1
- package/dist/server/schema.js +1 -1
- package/dist/service.d.ts +2043 -191
- package/dist/service.js +23 -16
- package/package.json +8 -7
- package/dist/better-auth/api.group.d.ts +0 -62
- package/dist/better-auth/api.group.js +0 -39
- package/dist/better-auth/schema.d.ts +0 -72
- package/dist/better-auth/schema.js +0 -110
- package/dist/components/auth-client.d.ts +0 -50
- package/dist/components/auth-client.js +0 -46
|
@@ -2,12 +2,12 @@ import { createElement as _createElement } from "react";
|
|
|
2
2
|
import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
3
3
|
import { useAtomRefresh, useAtomSet, useAtomValue } from "@effect/atom-react";
|
|
4
4
|
import { FormBuilder, FormReact } from "@lucas-barake/effect-form-react";
|
|
5
|
-
import { Effect, Option, Schema } from "effect";
|
|
5
|
+
import { Effect, Option, Predicate, Schema } from "effect";
|
|
6
6
|
import { AsyncResult, Atom } from "effect/unstable/reactivity";
|
|
7
7
|
import { ArrowLeft, Building2, Check, ChevronsUpDown, Copy, KeyRound, LogOut, Mail, PencilIcon, Plus, Trash2, UserIcon, UserPlus, Users, X, } from "lucide-react";
|
|
8
8
|
import { createContext, useContext, useEffect, useEffectEvent, useRef, useState, } from "react";
|
|
9
9
|
import { DataTable, DataTableRelationshipCell, } from "@krak-stack/registry/data-table";
|
|
10
|
-
import { ErrorMessage, ImageField, SelectField, SubmitButton, SubmitError, TextAreaField, TextField, } from "@krak-stack/registry/effect-form";
|
|
10
|
+
import { ErrorMessage, CheckboxField, ImageField, SelectField, SubmitButton, SubmitError, TextAreaField, TextField, } from "@krak-stack/registry/effect-form";
|
|
11
11
|
import { EditingLocaleSwitcher } from "@krak-stack/registry/editing-locale-switcher";
|
|
12
12
|
import { AppBrand } from "@krak-stack/registry/app-brand";
|
|
13
13
|
import { Field, FieldLabel, FieldSet } from "@/components/ui/field";
|
|
@@ -20,18 +20,19 @@ import { DropdownMenu, DropdownMenuContent, DropdownMenuGroup, DropdownMenuItem,
|
|
|
20
20
|
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from "@/components/ui/select";
|
|
21
21
|
import { Separator } from "@/components/ui/separator";
|
|
22
22
|
import { OrganizationEmail, OrganizationAddress, OrganizationMetadata, OrganizationPhone, OrganizationSocial, OrganizationTranslation, OrganizationWebsite, decodeOrganizationMetadata, } from "@krak-stack/auth/schema";
|
|
23
|
-
import { isOrganizationRole, normalizeOrganizationRole, normalizeOrganizationRoles, organizationRoles, parseRoleList, } from "../roles";
|
|
24
|
-
import { authClientApi } from "./auth-client-api";
|
|
25
|
-
import {
|
|
26
|
-
import {
|
|
27
|
-
import {
|
|
28
|
-
import { ApiKeyPermissions } from "./api-key-permissions";
|
|
29
|
-
import { ApiKeyRateLimit, apiKeyUsagePercent } from "./api-key-rate-limit";
|
|
30
|
-
import { ApiKeyReferrers } from "./api-key-referrers";
|
|
31
|
-
import { useOpenedOnce } from "./hooks";
|
|
32
|
-
import { invitationDisplayStatus, isInvitationExpired, useInvitationExpirationClock, } from "./invitation-expiration";
|
|
33
|
-
import { ExtraUploadedAsset } from "../extra/schema";
|
|
34
|
-
import { assetPath, assetUrl, cn } from "./utils";
|
|
23
|
+
import { isOrganizationRole, normalizeOrganizationRole, normalizeOrganizationRoles, organizationRoles, parseRoleList, } from "../roles.js";
|
|
24
|
+
import { authClientApi, authHttpClient } from "./auth-client-api.js";
|
|
25
|
+
import { activeAuthOrganizationAtom, authOrganizationsAtom, authSessionAtom, notifyAuthChange, } from "./auth-atoms.js";
|
|
26
|
+
import { useKrakstackAuth } from "./auth-provider.js";
|
|
27
|
+
import { parseApiKeyReferrers } from "./api-key.js";
|
|
28
|
+
import { ApiKeyPermissions } from "./api-key-permissions.js";
|
|
29
|
+
import { ApiKeyRateLimit, apiKeyUsagePercent } from "./api-key-rate-limit.js";
|
|
30
|
+
import { ApiKeyReferrers, apiKeyReferrers } from "./api-key-referrers.js";
|
|
31
|
+
import { useOpenedOnce } from "./hooks.js";
|
|
32
|
+
import { invitationDisplayStatus, isInvitationExpired, useInvitationExpirationClock, } from "./invitation-expiration.js";
|
|
33
|
+
import { ExtraUploadedAsset } from "../extra/schema.js";
|
|
34
|
+
import { assetPath, assetUrl, cn } from "./utils.js";
|
|
35
|
+
import { ExtraApiKeyPermissions } from "../extra/schema.js";
|
|
35
36
|
const messages = {
|
|
36
37
|
en: {
|
|
37
38
|
organization_back: "Back",
|
|
@@ -320,73 +321,55 @@ const organizationSwitcherMessages = (overrides) => ({
|
|
|
320
321
|
const interpolate = (value, params) => params
|
|
321
322
|
? value.replace(/\{([^}]+)\}/g, (_, key) => String(params[key] ?? `{${key}}`))
|
|
322
323
|
: value;
|
|
323
|
-
const
|
|
324
|
-
|
|
325
|
-
|
|
324
|
+
const interpolateMessage = (labels, key, params) => {
|
|
325
|
+
const entry = Object.entries(labels).find(([labelKey]) => labelKey === key);
|
|
326
|
+
return interpolate(entry?.[1] ?? key, params);
|
|
327
|
+
};
|
|
328
|
+
const organizationMessageFns = (labels) => {
|
|
329
|
+
return new Proxy({}, {
|
|
330
|
+
get: (_target, key) => (params) => interpolateMessage(labels, key, params),
|
|
331
|
+
});
|
|
332
|
+
};
|
|
326
333
|
const OrganizationMessagesContext = createContext(organizationMessageFns(organizationSwitcherMessages()));
|
|
327
334
|
const useOrganizationMessages = () => useContext(OrganizationMessagesContext);
|
|
328
335
|
const normalizeInvitationRole = (role) => {
|
|
329
336
|
const normalized = normalizeOrganizationRole(role);
|
|
330
337
|
return normalized === "support" ? "member" : normalized;
|
|
331
338
|
};
|
|
332
|
-
const userInvitationsAtom = Atom.family((
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
}
|
|
339
|
-
return (result.data ?? []).filter((invitation) => invitation.status === "pending");
|
|
340
|
-
},
|
|
341
|
-
catch: (error) => error,
|
|
342
|
-
}))));
|
|
343
|
-
const invitationOrganizationProfileAtom = Atom.family(({ baseUrl, locale, organizationId, }) => authClientApi(baseUrl).query("authExtra", "getOrganizationPublicProfile", {
|
|
339
|
+
const userInvitationsAtom = Atom.family((baseUrl) => authClientApi(baseUrl).query("auth", "organizationListUserInvitations", {
|
|
340
|
+
query: {},
|
|
341
|
+
timeToLive: "1 minute",
|
|
342
|
+
reactivityKeys: ["auth-user-invitations"],
|
|
343
|
+
}));
|
|
344
|
+
const invitationOrganizationProfileAtom = Atom.family((baseUrl) => Atom.family((organizationId) => Atom.family((locale) => authClientApi(baseUrl).query("authExtra", "getOrganizationPublicProfile", {
|
|
344
345
|
query: { locale, organizationId },
|
|
345
346
|
timeToLive: "5 minutes",
|
|
346
347
|
serializationKey: `invitation-organization:${organizationId}:${locale}`,
|
|
348
|
+
}))));
|
|
349
|
+
const organizationMembersAtom = Atom.family((baseUrl) => Atom.family((organizationId) => authClientApi(baseUrl).query("auth", "organizationListMembers", {
|
|
350
|
+
query: { organizationId },
|
|
351
|
+
timeToLive: "1 minute",
|
|
352
|
+
reactivityKeys: ["auth-organization-members", organizationId],
|
|
353
|
+
serializationKey: `organization-members:${organizationId}`,
|
|
354
|
+
})));
|
|
355
|
+
const organizationInvitationsAtom = Atom.family((baseUrl) => Atom.family((organizationId) => authClientApi(baseUrl).query("auth", "organizationListInvitations", {
|
|
356
|
+
query: { organizationId },
|
|
357
|
+
timeToLive: "1 minute",
|
|
358
|
+
reactivityKeys: ["auth-organization-invitations", organizationId],
|
|
359
|
+
serializationKey: `organization-invitations:${organizationId}`,
|
|
360
|
+
})));
|
|
361
|
+
const emptyOrganizationMembersAtom = Atom.make(Effect.succeed({ members: Array(), total: 0 }));
|
|
362
|
+
const emptyOrganizationInvitationsAtom = Atom.make(Effect.succeed(Array()));
|
|
363
|
+
const organizationApiKeysAtom = Atom.family((baseUrl) => Atom.family((organizationId) => authClientApi(baseUrl).query("auth", "apiKeyList", {
|
|
364
|
+
query: { configId: "organization", organizationId },
|
|
365
|
+
timeToLive: "1 minute",
|
|
366
|
+
reactivityKeys: ["auth-organization-api-keys", organizationId],
|
|
367
|
+
serializationKey: `organization-api-keys:${organizationId}`,
|
|
368
|
+
})));
|
|
369
|
+
const emptyOrganizationApiKeysAtom = Atom.make(Effect.succeed({
|
|
370
|
+
apiKeys: Array(),
|
|
371
|
+
total: 0,
|
|
347
372
|
}));
|
|
348
|
-
const emptyUserInvitationsAtom = Atom.make(Effect.try({
|
|
349
|
-
try: () => [],
|
|
350
|
-
catch: (error) => error,
|
|
351
|
-
}));
|
|
352
|
-
const organizationMembersAtom = Atom.family((authClient) => Atom.family((organizationId) => Atom.keepAlive(Atom.make(Effect.tryPromise({
|
|
353
|
-
try: async () => {
|
|
354
|
-
const [membersResult, invitationsResult] = await Promise.all([
|
|
355
|
-
authClient.organization.listMembers({
|
|
356
|
-
query: { organizationId },
|
|
357
|
-
}),
|
|
358
|
-
authClient.organization.listInvitations({
|
|
359
|
-
query: { organizationId },
|
|
360
|
-
}),
|
|
361
|
-
]);
|
|
362
|
-
if (membersResult.error) {
|
|
363
|
-
throw new Error(membersResult.error.message ?? "Could not load members.");
|
|
364
|
-
}
|
|
365
|
-
if (invitationsResult.error) {
|
|
366
|
-
throw new Error(invitationsResult.error.message ??
|
|
367
|
-
"Could not load invitations.");
|
|
368
|
-
}
|
|
369
|
-
return {
|
|
370
|
-
members: membersResult.data?.members ?? [],
|
|
371
|
-
invitations: (invitationsResult.data ?? []).filter((invitation) => invitation.status === "pending"),
|
|
372
|
-
};
|
|
373
|
-
},
|
|
374
|
-
catch: (error) => error,
|
|
375
|
-
})))));
|
|
376
|
-
const emptyOrganizationMembersAtom = Atom.make(Effect.succeed({ members: [], invitations: [] }));
|
|
377
|
-
const organizationApiKeysAtom = Atom.family((authClient) => Atom.family((organizationId) => Atom.keepAlive(Atom.make(Effect.tryPromise({
|
|
378
|
-
try: async () => {
|
|
379
|
-
const result = await authClient.apiKey.list({
|
|
380
|
-
query: { configId: "organization", organizationId },
|
|
381
|
-
});
|
|
382
|
-
if (result.error) {
|
|
383
|
-
throw new Error(result.error.message ?? "Could not load API keys.");
|
|
384
|
-
}
|
|
385
|
-
return result.data?.apiKeys ?? [];
|
|
386
|
-
},
|
|
387
|
-
catch: (error) => error,
|
|
388
|
-
})))));
|
|
389
|
-
const emptyOrganizationApiKeysAtom = Atom.make(Effect.succeed([]));
|
|
390
373
|
const organizationImageSchema = Schema.Union([
|
|
391
374
|
Schema.String,
|
|
392
375
|
Schema.instanceOf(File),
|
|
@@ -540,35 +523,46 @@ const inviteMemberFormBuilder = FormBuilder.empty
|
|
|
540
523
|
const apiKeyFormBuilder = FormBuilder.empty
|
|
541
524
|
.addField("name", Schema.NonEmptyString)
|
|
542
525
|
.addField("referrers", Schema.String);
|
|
526
|
+
const editApiKeyFormBuilder = FormBuilder.empty
|
|
527
|
+
.addField("name", Schema.NonEmptyString)
|
|
528
|
+
.addField("enabled", Schema.Boolean)
|
|
529
|
+
.addField("referrers", Schema.String)
|
|
530
|
+
.addField("permissions", Schema.Record(Schema.String, Schema.Boolean));
|
|
531
|
+
const ApiKeyPermissionsField = ({ field, props }) => (_jsx(ApiKeyPermissions, { description: props.description, idPrefix: props.idPrefix, permissions: props.permissions, labels: props.labels, selected: field.value, title: props.title, onChange: (id, checked) => field.onChange({ ...field.value, [id]: checked }) }));
|
|
543
532
|
const slugify = (value) => value
|
|
544
533
|
.trim()
|
|
545
534
|
.toLowerCase()
|
|
546
535
|
.replace(/[^a-z0-9]+/g, "-")
|
|
547
536
|
.replace(/^-+|-+$/g, "");
|
|
548
537
|
const noParentOrganization = "__none__";
|
|
549
|
-
const
|
|
550
|
-
|
|
538
|
+
const OrganizationFailure = Schema.Struct({
|
|
539
|
+
code: Schema.optional(Schema.String),
|
|
540
|
+
message: Schema.optional(Schema.String),
|
|
541
|
+
});
|
|
542
|
+
const isOrganizationSlugConflict = (cause) => {
|
|
543
|
+
const decoded = Schema.decodeUnknownOption(OrganizationFailure)(cause);
|
|
544
|
+
if (Option.isNone(decoded))
|
|
551
545
|
return false;
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
return [code, message].some((value) => {
|
|
555
|
-
if (typeof value !== "string")
|
|
546
|
+
return [decoded.value.code, decoded.value.message].some((value) => {
|
|
547
|
+
if (!value)
|
|
556
548
|
return false;
|
|
557
549
|
const normalized = value.toLowerCase().replaceAll("_", " ");
|
|
558
550
|
return normalized.includes("organization already exists");
|
|
559
551
|
});
|
|
560
552
|
};
|
|
561
|
-
const
|
|
562
|
-
const
|
|
553
|
+
const organizationFailureMessage = (cause, fallback) => {
|
|
554
|
+
const decoded = Schema.decodeUnknownOption(OrganizationFailure)(cause);
|
|
555
|
+
return Option.isSome(decoded)
|
|
556
|
+
? (decoded.value.message ?? fallback)
|
|
557
|
+
: fallback;
|
|
558
|
+
};
|
|
559
|
+
const decodeUploadedAsset = Schema.decodeUnknownEffect(ExtraUploadedAsset);
|
|
560
|
+
const OrganizationMetadataRecord = Schema.Record(Schema.String, Schema.Json);
|
|
561
|
+
const normalizeOrganizationMetadata = (metadata) => Schema.encodeUnknownEffect(Schema.UnknownFromJsonString)(metadata).pipe(Effect.flatMap(Schema.decodeUnknownEffect(Schema.fromJsonString(OrganizationMetadataRecord))));
|
|
562
|
+
const uploadImageAsset = (file, m, uploadImage) => {
|
|
563
563
|
const payload = new FormData();
|
|
564
564
|
payload.append("file", file);
|
|
565
|
-
|
|
566
|
-
const uploaded = await decodeUploadedAsset(await uploadImage({ payload }));
|
|
567
|
-
return assetPath(uploaded.url);
|
|
568
|
-
}
|
|
569
|
-
catch {
|
|
570
|
-
throw new Error(m.organization_logo_upload_error());
|
|
571
|
-
}
|
|
565
|
+
return uploadImage({ payload }).pipe(Effect.flatMap(decodeUploadedAsset), Effect.map((uploaded) => assetPath(uploaded.url)), Effect.mapError(() => new Error(m.organization_logo_upload_error())));
|
|
572
566
|
};
|
|
573
567
|
const currentOrganizationLocale = () => getLocale() === "fr" ? "fr" : "en";
|
|
574
568
|
const parseOrganizationMetadata = decodeOrganizationMetadata;
|
|
@@ -643,12 +637,12 @@ const organizationFormDefaults = (organization, baseUrl) => {
|
|
|
643
637
|
frIcon: assetUrl(fr?.icon, baseUrl) || null,
|
|
644
638
|
};
|
|
645
639
|
};
|
|
646
|
-
const organizationLogoFromForm =
|
|
640
|
+
const organizationLogoFromForm = (value, m, uploadImage) => {
|
|
647
641
|
if (value instanceof File)
|
|
648
|
-
return
|
|
649
|
-
if (
|
|
650
|
-
return assetPath(value);
|
|
651
|
-
return null;
|
|
642
|
+
return uploadImageAsset(value, m, uploadImage);
|
|
643
|
+
if (Schema.is(Schema.String)(value))
|
|
644
|
+
return Effect.succeed(assetPath(value));
|
|
645
|
+
return Effect.succeed(null);
|
|
652
646
|
};
|
|
653
647
|
const organizationNameFromForm = (value, locale) => {
|
|
654
648
|
const preferredName = locale === "fr" ? value.frName : value.enName;
|
|
@@ -684,23 +678,19 @@ const invitationStatusLabel = (status, m) => {
|
|
|
684
678
|
}
|
|
685
679
|
};
|
|
686
680
|
const formatOrganizationDate = (date) => new Intl.DateTimeFormat(getLocale(), { dateStyle: "medium" }).format(new Date(date));
|
|
687
|
-
const organizationMetadataFromForm =
|
|
681
|
+
const organizationMetadataFromForm = Effect.fn(function* (value, m, uploadImage, existingMetadata) {
|
|
688
682
|
const existing = parseOrganizationMetadata(existingMetadata);
|
|
689
|
-
const
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
decodedExistingMetadata !== null &&
|
|
694
|
-
!Array.isArray(decodedExistingMetadata)
|
|
695
|
-
? decodedExistingMetadata
|
|
696
|
-
: {};
|
|
683
|
+
const preservedMetadata = Option.getOrElse(Schema.decodeUnknownOption(Schema.Union([
|
|
684
|
+
OrganizationMetadataRecord,
|
|
685
|
+
Schema.fromJsonString(OrganizationMetadataRecord),
|
|
686
|
+
]))(existingMetadata), () => ({}));
|
|
697
687
|
const translations = [];
|
|
698
688
|
const enName = value.enName.trim();
|
|
699
689
|
const frName = value.frName.trim();
|
|
700
|
-
const enLogo =
|
|
701
|
-
const enIcon =
|
|
702
|
-
const frLogo =
|
|
703
|
-
const frIcon =
|
|
690
|
+
const enLogo = yield* organizationLogoFromForm(value.enLogo, m, uploadImage);
|
|
691
|
+
const enIcon = yield* organizationLogoFromForm(value.enIcon, m, uploadImage);
|
|
692
|
+
const frLogo = yield* organizationLogoFromForm(value.frLogo, m, uploadImage);
|
|
693
|
+
const frIcon = yield* organizationLogoFromForm(value.frIcon, m, uploadImage);
|
|
704
694
|
const localized = (values) => (values ?? []).flatMap((translation) => {
|
|
705
695
|
const label = translation.label.trim();
|
|
706
696
|
return label ? [{ ...translation, label }] : [];
|
|
@@ -718,17 +708,13 @@ const organizationMetadataFromForm = async (value, m, uploadImage, existingMetad
|
|
|
718
708
|
});
|
|
719
709
|
const phones = value.phones.flatMap((phone) => {
|
|
720
710
|
const number = phone.number.trim();
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
translations: localized(phone.translations),
|
|
729
|
-
},
|
|
730
|
-
]
|
|
731
|
-
: [];
|
|
711
|
+
if (!number)
|
|
712
|
+
return [];
|
|
713
|
+
const extension = phone.extension?.trim();
|
|
714
|
+
const result = extension
|
|
715
|
+
? { number, extension, translations: localized(phone.translations) }
|
|
716
|
+
: { number, translations: localized(phone.translations) };
|
|
717
|
+
return [result];
|
|
732
718
|
});
|
|
733
719
|
const websites = value.websites.flatMap((website) => {
|
|
734
720
|
const url = website.url.trim();
|
|
@@ -747,17 +733,22 @@ const organizationMetadataFromForm = async (value, m, uploadImage, existingMetad
|
|
|
747
733
|
: [];
|
|
748
734
|
});
|
|
749
735
|
const addresses = value.addresses.flatMap((input) => {
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
736
|
+
let normalized = {};
|
|
737
|
+
const streetAddress = input.streetAddress?.trim();
|
|
738
|
+
const locality = input.locality?.trim();
|
|
739
|
+
const region = input.region?.trim();
|
|
740
|
+
const postalCode = input.postalCode?.trim();
|
|
741
|
+
const country = input.country?.trim();
|
|
742
|
+
if (streetAddress)
|
|
743
|
+
normalized = { ...normalized, streetAddress };
|
|
744
|
+
if (locality)
|
|
745
|
+
normalized = { ...normalized, locality };
|
|
746
|
+
if (region)
|
|
747
|
+
normalized = { ...normalized, region };
|
|
748
|
+
if (postalCode)
|
|
749
|
+
normalized = { ...normalized, postalCode };
|
|
750
|
+
if (country)
|
|
751
|
+
normalized = { ...normalized, country };
|
|
761
752
|
return Object.keys(normalized).length
|
|
762
753
|
? [
|
|
763
754
|
{
|
|
@@ -814,31 +805,56 @@ const organizationMetadataFromForm = async (value, m, uploadImage, existingMetad
|
|
|
814
805
|
socials,
|
|
815
806
|
addresses,
|
|
816
807
|
};
|
|
817
|
-
};
|
|
818
|
-
export function OrganizationSwitcher({
|
|
808
|
+
});
|
|
809
|
+
export function OrganizationSwitcher({ baseUrl: providedBaseUrl, side = "bottom", className, defaultDialog = null, features, hideTrigger = false, menuActions, renderUnauthenticated, allowedOrganizationIds, messages, dialog: controlledDialog, onChange, onCreate, onDialogChange, apiKeyPermissions, }) {
|
|
819
810
|
const auth = useKrakstackAuth();
|
|
820
|
-
const
|
|
821
|
-
if (!authClient) {
|
|
822
|
-
throw new Error("KrakstackAuthProvider is required to use authClient.");
|
|
823
|
-
}
|
|
811
|
+
const baseUrl = providedBaseUrl ?? auth?.baseUrl;
|
|
824
812
|
const labels = organizationSwitcherMessages(messages);
|
|
825
813
|
const m = organizationMessageFns(labels);
|
|
826
|
-
const
|
|
827
|
-
const
|
|
828
|
-
const
|
|
814
|
+
const sessionAtom = authSessionAtom(baseUrl);
|
|
815
|
+
const organizationsAtom = authOrganizationsAtom(baseUrl);
|
|
816
|
+
const sessionResult = useAtomValue(sessionAtom);
|
|
817
|
+
const organizationsResult = useAtomValue(organizationsAtom);
|
|
818
|
+
const session = AsyncResult.match(sessionResult, {
|
|
819
|
+
onInitial: () => null,
|
|
820
|
+
onFailure: () => null,
|
|
821
|
+
onSuccess: ({ value }) => value,
|
|
822
|
+
});
|
|
823
|
+
const activeOrganizationId = session?.session.activeOrganizationId ?? null;
|
|
824
|
+
const activeOrganizationAtom = activeAuthOrganizationAtom(baseUrl)(activeOrganizationId);
|
|
825
|
+
const activeOrganizationResult = useAtomValue(activeOrganizationAtom);
|
|
826
|
+
const activeOrganization = AsyncResult.match(activeOrganizationResult, {
|
|
827
|
+
onInitial: () => null,
|
|
828
|
+
onFailure: () => null,
|
|
829
|
+
onSuccess: ({ value }) => value,
|
|
830
|
+
});
|
|
831
|
+
const organizations = AsyncResult.match(organizationsResult, {
|
|
832
|
+
onInitial: () => Array(),
|
|
833
|
+
onFailure: () => Array(),
|
|
834
|
+
onSuccess: ({ value }) => Array.from(value),
|
|
835
|
+
});
|
|
836
|
+
const organizationsError = AsyncResult.match(organizationsResult, {
|
|
837
|
+
onInitial: () => null,
|
|
838
|
+
onFailure: () => m.organization_switcher_empty(),
|
|
839
|
+
onSuccess: () => null,
|
|
840
|
+
});
|
|
841
|
+
const refreshSession = useAtomRefresh(sessionAtom);
|
|
842
|
+
const refreshOrganizations = useAtomRefresh(organizationsAtom);
|
|
843
|
+
const refreshActiveOrganization = useAtomRefresh(activeOrganizationAtom);
|
|
844
|
+
const setActiveOrganization = (organizationId) => authHttpClient(baseUrl).pipe(Effect.flatMap((client) => client.auth.organizationSetActive({
|
|
845
|
+
payload: { organizationId },
|
|
846
|
+
})));
|
|
829
847
|
const lastAuthRefreshVersion = useRef(auth?.authRefreshVersion ?? 0);
|
|
830
848
|
const [uncontrolledDialog, setUncontrolledDialog] = useState(defaultDialog);
|
|
831
849
|
const [editingOrganizationLocale, setEditingOrganizationLocale] = useState(currentOrganizationLocale);
|
|
832
850
|
const dialog = controlledDialog !== undefined ? controlledDialog : uncontrolledDialog;
|
|
833
|
-
const invitationsAtom =
|
|
834
|
-
? userInvitationsAtom(authClient)
|
|
835
|
-
: emptyUserInvitationsAtom;
|
|
851
|
+
const invitationsAtom = userInvitationsAtom(baseUrl);
|
|
836
852
|
const invitationsResult = useAtomValue(invitationsAtom);
|
|
837
853
|
const refreshUserInvitations = useAtomRefresh(invitationsAtom);
|
|
838
854
|
const userInvitations = AsyncResult.match(invitationsResult, {
|
|
839
855
|
onInitial: () => [],
|
|
840
856
|
onFailure: () => [],
|
|
841
|
-
onSuccess: ({ value }) => Array.from(value),
|
|
857
|
+
onSuccess: ({ value }) => Array.from(value).filter((invitation) => invitation.status === "pending"),
|
|
842
858
|
});
|
|
843
859
|
const userInvitationsError = AsyncResult.match(invitationsResult, {
|
|
844
860
|
onInitial: () => null,
|
|
@@ -846,14 +862,14 @@ export function OrganizationSwitcher({ authClient: providedAuthClient, baseUrl,
|
|
|
846
862
|
onSuccess: () => null,
|
|
847
863
|
});
|
|
848
864
|
const loadingUserInvitations = invitationsResult._tag === "Initial";
|
|
849
|
-
const activeMemberRoles = parseRoleList(activeOrganization
|
|
865
|
+
const activeMemberRoles = parseRoleList(activeOrganization?.members.find((member) => member.userId === session?.user.id)?.role);
|
|
850
866
|
const canManageApiKeys = activeMemberRoles.some((role) => role === "owner" || role === "admin");
|
|
851
867
|
const canUpdateOrganization = canManageApiKeys;
|
|
852
868
|
const canSwitchOrganizations = features?.organizationSwitching ?? true;
|
|
853
869
|
const canCreateOrganization = features?.organizationCreation ?? true;
|
|
854
870
|
const canViewOrganizationInvitations = features?.userInvitations ?? true;
|
|
855
871
|
const setDialog = (next) => {
|
|
856
|
-
const nextDialog =
|
|
872
|
+
const nextDialog = Predicate.isFunction(next) ? next(dialog) : next;
|
|
857
873
|
if (nextDialog === dialog)
|
|
858
874
|
return;
|
|
859
875
|
if (controlledDialog === undefined)
|
|
@@ -862,9 +878,9 @@ export function OrganizationSwitcher({ authClient: providedAuthClient, baseUrl,
|
|
|
862
878
|
};
|
|
863
879
|
const openCreate = () => setDialog("create");
|
|
864
880
|
const refresh = async () => {
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
881
|
+
refreshOrganizations();
|
|
882
|
+
refreshActiveOrganization();
|
|
883
|
+
refreshSession();
|
|
868
884
|
};
|
|
869
885
|
const refreshOnSessionChanged = useEffectEvent(() => {
|
|
870
886
|
void refresh();
|
|
@@ -876,30 +892,32 @@ export function OrganizationSwitcher({ authClient: providedAuthClient, baseUrl,
|
|
|
876
892
|
lastAuthRefreshVersion.current = version;
|
|
877
893
|
refreshOnSessionChanged();
|
|
878
894
|
}, [auth?.authRefreshVersion]);
|
|
879
|
-
if (!session
|
|
895
|
+
if (!session) {
|
|
880
896
|
return _jsx(_Fragment, { children: renderUnauthenticated?.() });
|
|
881
897
|
}
|
|
882
|
-
const active = activeOrganization
|
|
898
|
+
const active = activeOrganization;
|
|
883
899
|
const activeName = active?.name;
|
|
884
|
-
const visibleOrganizations = organizations.
|
|
885
|
-
allowedOrganizationIds.includes(organization.id))
|
|
900
|
+
const visibleOrganizations = organizations.filter((organization) => !allowedOrganizationIds ||
|
|
901
|
+
allowedOrganizationIds.includes(organization.id));
|
|
886
902
|
const selectableOrganizations = canSwitchOrganizations
|
|
887
903
|
? visibleOrganizations.filter((organization) => organization.id !== active?.id)
|
|
888
904
|
: [];
|
|
889
905
|
const scrollOrganizationList = selectableOrganizations.length > 5;
|
|
890
|
-
const hasOrganizationListItems =
|
|
891
|
-
Boolean(
|
|
906
|
+
const hasOrganizationListItems = organizationsResult._tag === "Initial" ||
|
|
907
|
+
Boolean(organizationsError) ||
|
|
892
908
|
canSwitchOrganizations;
|
|
893
909
|
const refreshAfterInvitationAction = async (previousActiveId) => {
|
|
894
910
|
refreshUserInvitations();
|
|
895
911
|
await refresh();
|
|
896
912
|
if (!canSwitchOrganizations && previousActiveId) {
|
|
897
|
-
|
|
898
|
-
|
|
899
|
-
|
|
900
|
-
if (!result.error) {
|
|
913
|
+
try {
|
|
914
|
+
await Effect.runPromise(setActiveOrganization(previousActiveId));
|
|
915
|
+
notifyAuthChange();
|
|
901
916
|
await refresh();
|
|
902
|
-
onChange?.(organizations.
|
|
917
|
+
onChange?.(organizations.find((organization) => organization.id === previousActiveId) ?? null);
|
|
918
|
+
}
|
|
919
|
+
catch {
|
|
920
|
+
// The invitation action succeeded; keep the newly active organization.
|
|
903
921
|
}
|
|
904
922
|
}
|
|
905
923
|
};
|
|
@@ -911,61 +929,71 @@ export function OrganizationSwitcher({ authClient: providedAuthClient, baseUrl,
|
|
|
911
929
|
? { imageSrc: activeDisplay.image }
|
|
912
930
|
: {}) }), _jsx(ChevronsUpDown, { className: "text-muted-foreground size-4 shrink-0 group-data-[collapsible=icon]:hidden" })] }) }), _jsx(DropdownMenuContent, { className: "max-w-[calc(100vw-1rem)] min-w-64 rounded-lg", side: side, align: "end", sideOffset: 4, children: _jsxs(DropdownMenuGroup, { children: [_jsx(DropdownMenuLabel, { className: "p-0 font-normal", children: _jsx(AppBrand, { to: null, label: activeDisplay.name, subtitle: activeSubtitle, icon: Building2, variant: "sidebar", className: "px-1 py-1.5 text-left text-sm", ...(activeDisplay.image
|
|
913
931
|
? { imageSrc: activeDisplay.image }
|
|
914
|
-
: {}) }) }), menuActions ? (_jsxs(_Fragment, { children: [_jsx(DropdownMenuSeparator, {}), menuActions] })) : null, hasOrganizationListItems ? _jsx(DropdownMenuSeparator, {}) : null,
|
|
932
|
+
: {}) }) }), menuActions ? (_jsxs(_Fragment, { children: [_jsx(DropdownMenuSeparator, {}), menuActions] })) : null, hasOrganizationListItems ? _jsx(DropdownMenuSeparator, {}) : null, organizationsResult._tag === "Initial" ? (_jsx(DropdownMenuItem, { disabled: true, children: m.organization_loading() })) : null, organizationsError ? (_jsx(DropdownMenuItem, { disabled: true, children: organizationsError })) : null, canSwitchOrganizations && selectableOrganizations.length ? (_jsx("div", { className: cn(scrollOrganizationList &&
|
|
915
933
|
"max-h-64 overflow-y-auto overscroll-contain"), children: selectableOrganizations.map((organization) => {
|
|
916
934
|
const display = organizationDisplay(organization, m, baseUrl);
|
|
917
935
|
return (_jsx(DropdownMenuItem, { onClick: async () => {
|
|
918
|
-
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
|
|
936
|
+
try {
|
|
937
|
+
const result = await Effect.runPromise(setActiveOrganization(organization.id));
|
|
938
|
+
if (!result)
|
|
939
|
+
return;
|
|
940
|
+
notifyAuthChange();
|
|
922
941
|
await refresh();
|
|
923
942
|
onChange?.(organization);
|
|
924
943
|
}
|
|
944
|
+
catch {
|
|
945
|
+
// Switching previously failed silently in this menu.
|
|
946
|
+
}
|
|
925
947
|
}, children: _jsx(AppBrand, { to: null, label: display.name, subtitle: organizationSwitcherSubtitle(organization, display.subtitle, m), icon: Building2, className: "w-full text-left [&>div:first-child]:size-7", ...(display.image
|
|
926
948
|
? { imageSrc: display.image }
|
|
927
949
|
: {}) }) }, organization.id));
|
|
928
|
-
}) })) : canSwitchOrganizations &&
|
|
950
|
+
}) })) : canSwitchOrganizations &&
|
|
951
|
+
organizationsResult._tag !== "Initial" ? (_jsx(DropdownMenuItem, { disabled: true, children: active
|
|
929
952
|
? m.organization_switcher_no_other_organizations()
|
|
930
953
|
: m.organization_switcher_empty() })) : null, canCreateOrganization || canViewOrganizationInvitations ? (_jsxs(_Fragment, { children: [_jsx(DropdownMenuSeparator, {}), canCreateOrganization ? (_jsxs(DropdownMenuItem, { onClick: openCreate, children: [_jsx(Plus, {}), m.organization_create_title()] })) : null, canViewOrganizationInvitations ? (_jsxs(DropdownMenuItem, { onClick: () => {
|
|
931
954
|
setDialog("invitations");
|
|
932
|
-
}, children: [_jsx(Mail, {}), _jsxs("span", { className: "flex flex-1 items-center justify-between gap-3", children: [m.organization_user_invitations_title(), userInvitations.length ? (_jsx(Badge, { variant: "secondary", className: "bg-secondary! text-secondary-foreground!", children: userInvitations.length })) : null] })] })) : null] })) : null, activeOrganization
|
|
933
|
-
const organizationId = activeOrganization.
|
|
955
|
+
}, children: [_jsx(Mail, {}), _jsxs("span", { className: "flex flex-1 items-center justify-between gap-3", children: [m.organization_user_invitations_title(), userInvitations.length ? (_jsx(Badge, { variant: "secondary", className: "bg-secondary! text-secondary-foreground!", children: userInvitations.length })) : null] })] })) : null] })) : null, activeOrganization ? (_jsxs(_Fragment, { children: [_jsx(DropdownMenuSeparator, {}), (() => {
|
|
956
|
+
const organizationId = activeOrganization.id;
|
|
934
957
|
return (_jsxs(DropdownMenuItem, { onClick: () => {
|
|
935
958
|
void navigator.clipboard.writeText(organizationId);
|
|
936
959
|
}, children: [_jsx(Copy, {}), m.organization_copy_id()] }));
|
|
937
960
|
})(), canUpdateOrganization ? (_jsxs(DropdownMenuItem, { onClick: () => setDialog("manage"), children: [_jsx(PencilIcon, {}), m.organization_switcher_manage()] })) : null, _jsxs(DropdownMenuItem, { onClick: () => setDialog("members"), children: [_jsx(Users, {}), m.organization_members_title()] }), canManageApiKeys ? (_jsxs(DropdownMenuItem, { onClick: () => setDialog("apiKeys"), children: [_jsx(KeyRound, {}), m.user_button_api_keys()] })) : null] })) : null] }) })] })), _jsx(Dialog, { open: dialog === "create" && canCreateOrganization, onOpenChange: (open) => {
|
|
938
961
|
setDialog((current) => open ? "create" : current === "create" ? null : current);
|
|
939
|
-
}, children: _jsxs(DialogContent, { className: "max-h-[85vh] overflow-y-auto sm:max-w-2xl", children: [_jsxs(DialogHeader, { children: [_jsx(DialogTitle, { className: "text-2xl", children: m.organization_create_title() }), _jsx(DialogDescription, { children: m.organization_create_description() }), _jsx("div", { className: "pt-2", children: _jsx(EditingLocaleSwitcher, { value: editingOrganizationLocale, onValueChange: setEditingOrganizationLocale }) })] }), _jsx(Separator, {}), _jsx(CreateOrganizationSection, {
|
|
962
|
+
}, children: _jsxs(DialogContent, { className: "max-h-[85vh] overflow-y-auto sm:max-w-2xl", children: [_jsxs(DialogHeader, { children: [_jsx(DialogTitle, { className: "text-2xl", children: m.organization_create_title() }), _jsx(DialogDescription, { children: m.organization_create_description() }), _jsx("div", { className: "pt-2", children: _jsx(EditingLocaleSwitcher, { value: editingOrganizationLocale, onValueChange: setEditingOrganizationLocale }) })] }), _jsx(Separator, {}), _jsx(CreateOrganizationSection, { baseUrl: baseUrl, editingLocale: editingOrganizationLocale, organizations: visibleOrganizations, onCreated: async (organization) => {
|
|
940
963
|
setDialog(null);
|
|
941
|
-
|
|
942
|
-
|
|
943
|
-
|
|
964
|
+
let activated = false;
|
|
965
|
+
try {
|
|
966
|
+
await Effect.runPromise(setActiveOrganization(organization.id));
|
|
967
|
+
activated = true;
|
|
968
|
+
notifyAuthChange();
|
|
969
|
+
}
|
|
970
|
+
catch {
|
|
971
|
+
// Creation succeeded even if activating the organization did not.
|
|
972
|
+
}
|
|
944
973
|
await refresh();
|
|
945
|
-
if (
|
|
974
|
+
if (activated) {
|
|
946
975
|
onCreate?.(organization);
|
|
947
976
|
onChange?.(organization);
|
|
948
977
|
}
|
|
949
978
|
} })] }) }), _jsx(Dialog, { open: dialog === "manage" && canUpdateOrganization, onOpenChange: (open) => {
|
|
950
979
|
setDialog((current) => open ? "manage" : current === "manage" ? null : current);
|
|
951
|
-
}, children: _jsxs(DialogContent, { className: "max-h-[85vh] overflow-y-auto sm:max-w-2xl", children: [_jsxs(DialogHeader, { children: [_jsx(DialogTitle, { className: "text-2xl", children: m.organization_switcher_manage() }), _jsx(DialogDescription, { children: m.organization_edit_description() }), _jsx("div", { className: "pt-2", children: _jsx(EditingLocaleSwitcher, { value: editingOrganizationLocale, onValueChange: setEditingOrganizationLocale }) })] }), _jsx(Separator, {}), activeOrganization
|
|
980
|
+
}, children: _jsxs(DialogContent, { className: "max-h-[85vh] overflow-y-auto sm:max-w-2xl", children: [_jsxs(DialogHeader, { children: [_jsx(DialogTitle, { className: "text-2xl", children: m.organization_switcher_manage() }), _jsx(DialogDescription, { children: m.organization_edit_description() }), _jsx("div", { className: "pt-2", children: _jsx(EditingLocaleSwitcher, { value: editingOrganizationLocale, onValueChange: setEditingOrganizationLocale }) })] }), _jsx(Separator, {}), activeOrganization && canUpdateOrganization ? (_jsx(EditOrganizationSection, { baseUrl: baseUrl, editingLocale: editingOrganizationLocale, organization: activeOrganization, onUpdated: refresh })) : null] }) }), _jsx(Dialog, { open: dialog === "members", onOpenChange: (open) => {
|
|
952
981
|
setDialog((current) => open ? "members" : current === "members" ? null : current);
|
|
953
|
-
}, children: _jsx(DialogContent, { className: "max-h-[85vh] overflow-y-auto sm:max-w-4xl", children: activeOrganization
|
|
982
|
+
}, children: _jsx(DialogContent, { className: "max-h-[85vh] overflow-y-auto sm:max-w-4xl", children: activeOrganization ? (_jsx(OrganizationMembersManager, { baseUrl: baseUrl, canManageMembers: canManageApiKeys, organization: activeOrganization, currentUserId: session.user.id, active: dialog === "members", onLeft: async () => {
|
|
954
983
|
setDialog(null);
|
|
955
|
-
auth?.refreshAuth();
|
|
956
984
|
await refresh();
|
|
957
985
|
onChange?.(null);
|
|
958
986
|
} })) : null }) }), _jsx(Dialog, { open: dialog === "apiKeys" && canManageApiKeys, onOpenChange: (open) => {
|
|
959
987
|
setDialog((current) => open ? "apiKeys" : current === "apiKeys" ? null : current);
|
|
960
|
-
}, children: _jsx(DialogContent, { className: "max-h-[85vh] min-w-0 overflow-x-hidden overflow-y-auto sm:max-w-3xl", children: activeOrganization
|
|
988
|
+
}, children: _jsx(DialogContent, { className: "max-h-[85vh] min-w-0 overflow-x-hidden overflow-y-auto sm:max-w-3xl", children: activeOrganization ? (_jsx(OrganizationApiKeyManager, { baseUrl: baseUrl, organization: activeOrganization, active: dialog === "apiKeys" && canManageApiKeys, permissionLabels: auth?.accessLabels ?? undefined, permissions: apiKeyPermissions ??
|
|
961
989
|
auth?.access?.apiKeyPermissions.organization ??
|
|
962
990
|
{} })) : null }) }), _jsx(Dialog, { open: dialog === "invitations" && canViewOrganizationInvitations, onOpenChange: (open) => {
|
|
963
991
|
setDialog((current) => open ? "invitations" : current === "invitations" ? null : current);
|
|
964
|
-
}, children: _jsxs(DialogContent, { className: "max-h-[85vh] min-w-0 overflow-x-hidden overflow-y-auto sm:max-w-4xl", children: [_jsxs(DialogHeader, { children: [_jsx(DialogTitle, { className: "text-2xl", children: m.organization_user_invitations_title() }), _jsx(DialogDescription, { children: m.organization_user_invitations_description() })] }), _jsx(Separator, {}), _jsx(UserInvitationsManager, {
|
|
965
|
-
? { activeOrganizationId: activeOrganization.
|
|
992
|
+
}, children: _jsxs(DialogContent, { className: "max-h-[85vh] min-w-0 overflow-x-hidden overflow-y-auto sm:max-w-4xl", children: [_jsxs(DialogHeader, { children: [_jsx(DialogTitle, { className: "text-2xl", children: m.organization_user_invitations_title() }), _jsx(DialogDescription, { children: m.organization_user_invitations_description() })] }), _jsx(Separator, {}), _jsx(UserInvitationsManager, { baseUrl: baseUrl, invitations: userInvitations, loading: loadingUserInvitations, error: userInvitationsError, ...(activeOrganization
|
|
993
|
+
? { activeOrganizationId: activeOrganization.id }
|
|
966
994
|
: {}), onActionComplete: refreshAfterInvitationAction })] }) })] }));
|
|
967
995
|
}
|
|
968
|
-
function UserInvitationsManager({
|
|
996
|
+
function UserInvitationsManager({ baseUrl, invitations, loading, error, activeOrganizationId, onActionComplete, }) {
|
|
969
997
|
const m = useOrganizationMessages();
|
|
970
998
|
const [actingInvitationId, setActingInvitationId] = useState(null);
|
|
971
999
|
const [actionError, setActionError] = useState(null);
|
|
@@ -975,28 +1003,35 @@ function UserInvitationsManager({ authClient, baseUrl, invitations, loading, err
|
|
|
975
1003
|
return;
|
|
976
1004
|
setActingInvitationId(invitation.id);
|
|
977
1005
|
setActionError(null);
|
|
978
|
-
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
|
|
982
|
-
|
|
983
|
-
|
|
984
|
-
|
|
1006
|
+
try {
|
|
1007
|
+
await Effect.runPromise(authHttpClient(baseUrl).pipe(Effect.flatMap((client) => client.auth.organizationAcceptInvitation({
|
|
1008
|
+
payload: { invitationId: invitation.id },
|
|
1009
|
+
}))));
|
|
1010
|
+
notifyAuthChange();
|
|
1011
|
+
await onActionComplete(activeOrganizationId);
|
|
1012
|
+
}
|
|
1013
|
+
catch (cause) {
|
|
1014
|
+
setActionError(organizationFailureMessage(cause, m.organization_invitation_accept_error()));
|
|
1015
|
+
}
|
|
1016
|
+
finally {
|
|
1017
|
+
setActingInvitationId(null);
|
|
985
1018
|
}
|
|
986
|
-
await onActionComplete(activeOrganizationId);
|
|
987
1019
|
};
|
|
988
1020
|
const rejectInvitation = async (invitation) => {
|
|
989
1021
|
setActingInvitationId(invitation.id);
|
|
990
1022
|
setActionError(null);
|
|
991
|
-
|
|
992
|
-
|
|
993
|
-
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
|
|
1023
|
+
try {
|
|
1024
|
+
await Effect.runPromise(authHttpClient(baseUrl).pipe(Effect.flatMap((client) => client.auth.organizationRejectInvitation({
|
|
1025
|
+
payload: { invitationId: invitation.id },
|
|
1026
|
+
}))));
|
|
1027
|
+
await onActionComplete(activeOrganizationId);
|
|
1028
|
+
}
|
|
1029
|
+
catch (cause) {
|
|
1030
|
+
setActionError(organizationFailureMessage(cause, m.organization_invitation_reject_error()));
|
|
1031
|
+
}
|
|
1032
|
+
finally {
|
|
1033
|
+
setActingInvitationId(null);
|
|
998
1034
|
}
|
|
999
|
-
await onActionComplete(activeOrganizationId);
|
|
1000
1035
|
};
|
|
1001
1036
|
return (_jsxs("section", { className: "flex min-w-0 flex-col gap-4", children: [error ? _jsx("p", { className: "text-destructive text-sm", children: error }) : null, actionError ? (_jsx("p", { className: "text-destructive text-sm", children: actionError })) : null, _jsx("div", { className: "-m-1 min-w-0 overflow-x-auto p-1", children: _jsx(DataTable, { columns: userInvitationColumns({
|
|
1002
1037
|
baseUrl,
|
|
@@ -1045,11 +1080,7 @@ const userInvitationColumns = ({ baseUrl, m, now, }) => [
|
|
|
1045
1080
|
];
|
|
1046
1081
|
function InvitationOrganizationBrand({ baseUrl, invitation, }) {
|
|
1047
1082
|
const locale = useKrakstackAuth()?.locale ?? currentOrganizationLocale();
|
|
1048
|
-
const profileResult = useAtomValue(invitationOrganizationProfileAtom(
|
|
1049
|
-
baseUrl,
|
|
1050
|
-
locale,
|
|
1051
|
-
organizationId: invitation.organizationId,
|
|
1052
|
-
}));
|
|
1083
|
+
const profileResult = useAtomValue(invitationOrganizationProfileAtom(baseUrl)(invitation.organizationId)(locale));
|
|
1053
1084
|
const profile = AsyncResult.match(profileResult, {
|
|
1054
1085
|
onInitial: () => null,
|
|
1055
1086
|
onFailure: () => null,
|
|
@@ -1076,34 +1107,39 @@ const userInvitationRowActions = ({ m, actingInvitationId, now, onAccept, onReje
|
|
|
1076
1107
|
onClick: onReject,
|
|
1077
1108
|
},
|
|
1078
1109
|
];
|
|
1079
|
-
function EditOrganizationSection({
|
|
1110
|
+
function EditOrganizationSection({ baseUrl, editingLocale, organization, onUpdated, }) {
|
|
1080
1111
|
const m = useOrganizationMessages();
|
|
1081
|
-
const uploadImage = useAtomSet(authClientApi(baseUrl).mutation("authExtra", "uploadUserImage"), { mode: "promise" });
|
|
1082
1112
|
const [defaultLocale] = useState(currentOrganizationLocale);
|
|
1083
1113
|
const defaultValues = organizationFormDefaults(organization, baseUrl);
|
|
1084
1114
|
const [form] = useState(() => FormReact.make(organizationFormBuilder, {
|
|
1085
1115
|
fields: organizationFormFields,
|
|
1086
|
-
onSubmit: (_, { decoded: value }) => Effect.
|
|
1087
|
-
|
|
1088
|
-
|
|
1089
|
-
|
|
1090
|
-
|
|
1091
|
-
|
|
1092
|
-
|
|
1093
|
-
|
|
1116
|
+
onSubmit: (_, { decoded: value }) => Effect.gen(function* () {
|
|
1117
|
+
const name = organizationNameFromForm(value, defaultLocale);
|
|
1118
|
+
if (!name)
|
|
1119
|
+
return yield* Effect.fail(new Error(m.organization_name_required()));
|
|
1120
|
+
const slug = value.slug.trim().toLowerCase();
|
|
1121
|
+
const client = yield* authHttpClient(baseUrl);
|
|
1122
|
+
const metadata = yield* organizationMetadataFromForm(value, m, (input) => client.authExtra.uploadUserImage(input), organization.metadata);
|
|
1123
|
+
const normalizedMetadata = yield* normalizeOrganizationMetadata(metadata);
|
|
1124
|
+
const updated = yield* client.auth.organizationUpdate({
|
|
1125
|
+
payload: {
|
|
1094
1126
|
organizationId: organization.id,
|
|
1095
|
-
data: {
|
|
1096
|
-
|
|
1097
|
-
|
|
1098
|
-
|
|
1099
|
-
|
|
1100
|
-
|
|
1101
|
-
|
|
1102
|
-
|
|
1103
|
-
|
|
1104
|
-
|
|
1105
|
-
:
|
|
1106
|
-
|
|
1127
|
+
data: {
|
|
1128
|
+
name,
|
|
1129
|
+
slug,
|
|
1130
|
+
metadata: normalizedMetadata,
|
|
1131
|
+
},
|
|
1132
|
+
},
|
|
1133
|
+
});
|
|
1134
|
+
yield* Effect.sync(notifyAuthChange);
|
|
1135
|
+
yield* Effect.tryPromise({
|
|
1136
|
+
try: onUpdated,
|
|
1137
|
+
catch: (cause) => cause,
|
|
1138
|
+
});
|
|
1139
|
+
return updated;
|
|
1140
|
+
}).pipe(Effect.mapError((cause) => cause instanceof Error
|
|
1141
|
+
? cause
|
|
1142
|
+
: new Error(m.organization_update_error()))),
|
|
1107
1143
|
}));
|
|
1108
1144
|
const submit = useAtomSet(form.submit);
|
|
1109
1145
|
const submitResult = useAtomValue(form.submit);
|
|
@@ -1133,40 +1169,42 @@ function EditOrganizationSection({ authClient, baseUrl, editingLocale, organizat
|
|
|
1133
1169
|
suggestedHeight: 512,
|
|
1134
1170
|
} })] })] }), _jsx(Separator, { className: "my-2" }), _jsxs(OrganizationFormSection, { title: m.organization_contact(), children: [_jsx(OrganizationContactGroup, { title: m.organization_contact_email_type(), children: _jsx(form.emails, { locale: editingLocale }) }), _jsx(OrganizationContactGroup, { title: m.organization_contact_phone_type(), children: _jsx(form.phones, { locale: editingLocale }) }), _jsx(OrganizationContactGroup, { title: m.organization_contact_website_type(), children: _jsx(form.websites, { locale: editingLocale }) }), _jsx(OrganizationContactGroup, { title: m.organization_contact_social_type(), children: _jsx(form.socials, { locale: editingLocale }) })] }), _jsx(Separator, { className: "my-2" }), _jsx(OrganizationFormSection, { title: m.organization_address(), children: _jsx(form.addresses, { locale: editingLocale }) }), _jsx(SubmitError, { result: submitResult }), _jsx(SubmitButton, { form: form })] }) }) }));
|
|
1135
1171
|
}
|
|
1136
|
-
function CreateOrganizationSection({
|
|
1172
|
+
function CreateOrganizationSection({ baseUrl, editingLocale, organizations, onCreated, }) {
|
|
1137
1173
|
const m = useOrganizationMessages();
|
|
1138
|
-
const uploadImage = useAtomSet(authClientApi(baseUrl).mutation("authExtra", "uploadUserImage"), { mode: "promise" });
|
|
1139
1174
|
const [defaultLocale] = useState(currentOrganizationLocale);
|
|
1140
1175
|
const defaultValues = organizationFormDefaults(undefined, baseUrl);
|
|
1141
1176
|
const [form] = useState(() => FormReact.make(organizationFormBuilder, {
|
|
1142
1177
|
fields: organizationFormFields,
|
|
1143
|
-
onSubmit: (_, { decoded: value }) => Effect.
|
|
1144
|
-
|
|
1145
|
-
|
|
1146
|
-
|
|
1147
|
-
|
|
1148
|
-
|
|
1149
|
-
|
|
1150
|
-
|
|
1178
|
+
onSubmit: (_, { decoded: value }) => Effect.gen(function* () {
|
|
1179
|
+
const name = organizationNameFromForm(value, defaultLocale);
|
|
1180
|
+
if (!name)
|
|
1181
|
+
return yield* Effect.fail(new Error(m.organization_name_required()));
|
|
1182
|
+
const slug = (value.slug.trim() || slugify(name)).toLowerCase();
|
|
1183
|
+
const client = yield* authHttpClient(baseUrl);
|
|
1184
|
+
const metadata = yield* organizationMetadataFromForm({ ...value, slug }, m, (input) => client.authExtra.uploadUserImage(input));
|
|
1185
|
+
const normalizedMetadata = yield* normalizeOrganizationMetadata(metadata);
|
|
1186
|
+
const createPayload = value.parentId === noParentOrganization
|
|
1187
|
+
? { name, slug, metadata: normalizedMetadata }
|
|
1188
|
+
: {
|
|
1151
1189
|
name,
|
|
1152
1190
|
slug,
|
|
1153
|
-
metadata,
|
|
1154
|
-
|
|
1155
|
-
|
|
1156
|
-
|
|
1157
|
-
})
|
|
1158
|
-
|
|
1159
|
-
|
|
1160
|
-
|
|
1161
|
-
|
|
1162
|
-
|
|
1163
|
-
|
|
1164
|
-
|
|
1165
|
-
}
|
|
1166
|
-
|
|
1167
|
-
|
|
1168
|
-
|
|
1169
|
-
|
|
1191
|
+
metadata: normalizedMetadata,
|
|
1192
|
+
parentId: value.parentId,
|
|
1193
|
+
};
|
|
1194
|
+
const created = yield* client.auth
|
|
1195
|
+
.organizationCreate({ payload: createPayload })
|
|
1196
|
+
.pipe(Effect.mapError((cause) => new Error(isOrganizationSlugConflict(cause)
|
|
1197
|
+
? m.organization_create_slug_conflict()
|
|
1198
|
+
: organizationFailureMessage(cause, m.organization_create_error()))));
|
|
1199
|
+
yield* Effect.sync(notifyAuthChange);
|
|
1200
|
+
yield* Effect.tryPromise({
|
|
1201
|
+
try: () => onCreated(created),
|
|
1202
|
+
catch: (cause) => cause,
|
|
1203
|
+
});
|
|
1204
|
+
return created;
|
|
1205
|
+
}).pipe(Effect.mapError((cause) => cause instanceof Error
|
|
1206
|
+
? cause
|
|
1207
|
+
: new Error(m.organization_create_error()))),
|
|
1170
1208
|
}));
|
|
1171
1209
|
const submit = useAtomSet(form.submit);
|
|
1172
1210
|
const submitResult = useAtomValue(form.submit);
|
|
@@ -1219,24 +1257,40 @@ function OrganizationFormSection({ children, description, title, }) {
|
|
|
1219
1257
|
function OrganizationContactGroup({ children, title, }) {
|
|
1220
1258
|
return (_jsxs("div", { className: "flex flex-col gap-3", children: [_jsx("h4", { className: "text-sm font-medium", children: title }), children] }));
|
|
1221
1259
|
}
|
|
1222
|
-
function OrganizationMembersManager({
|
|
1260
|
+
function OrganizationMembersManager({ baseUrl, canManageMembers, organization, currentUserId, active, onLeft, }) {
|
|
1223
1261
|
const m = useOrganizationMessages();
|
|
1224
1262
|
const hasOpened = useOpenedOnce(active);
|
|
1225
1263
|
const membersAtom = hasOpened
|
|
1226
|
-
? organizationMembersAtom(
|
|
1264
|
+
? organizationMembersAtom(baseUrl)(organization.id)
|
|
1227
1265
|
: emptyOrganizationMembersAtom;
|
|
1266
|
+
const invitationsAtom = hasOpened
|
|
1267
|
+
? organizationInvitationsAtom(baseUrl)(organization.id)
|
|
1268
|
+
: emptyOrganizationInvitationsAtom;
|
|
1228
1269
|
const membersResult = useAtomValue(membersAtom);
|
|
1270
|
+
const invitationsResult = useAtomValue(invitationsAtom);
|
|
1229
1271
|
const refreshMembers = useAtomRefresh(membersAtom);
|
|
1272
|
+
const refreshInvitations = useAtomRefresh(invitationsAtom);
|
|
1230
1273
|
const [inviting, setInviting] = useState(false);
|
|
1231
1274
|
const [error, setError] = useState(null);
|
|
1232
1275
|
const [cancellingInvitationId, setCancellingInvitationId] = useState(null);
|
|
1233
1276
|
const [leavingOrganization, setLeavingOrganization] = useState(false);
|
|
1234
1277
|
const [lastMembersData, setLastMembersData] = useState(null);
|
|
1235
|
-
const
|
|
1278
|
+
const currentMembers = AsyncResult.match(membersResult, {
|
|
1279
|
+
onInitial: () => null,
|
|
1280
|
+
onFailure: () => null,
|
|
1281
|
+
onSuccess: ({ value }) => value.members,
|
|
1282
|
+
});
|
|
1283
|
+
const currentInvitations = AsyncResult.match(invitationsResult, {
|
|
1236
1284
|
onInitial: () => null,
|
|
1237
1285
|
onFailure: () => null,
|
|
1238
1286
|
onSuccess: ({ value }) => value,
|
|
1239
1287
|
});
|
|
1288
|
+
const currentMembersData = currentMembers && currentInvitations
|
|
1289
|
+
? {
|
|
1290
|
+
members: Array.from(currentMembers),
|
|
1291
|
+
invitations: Array.from(currentInvitations).filter((invitation) => invitation.status === "pending"),
|
|
1292
|
+
}
|
|
1293
|
+
: null;
|
|
1240
1294
|
const membersData = currentMembersData ??
|
|
1241
1295
|
lastMembersData ?? {
|
|
1242
1296
|
members: [],
|
|
@@ -1255,36 +1309,38 @@ function OrganizationMembersManager({ authClient, baseUrl, canManageMembers, org
|
|
|
1255
1309
|
onFailure: () => m.organization_members_load_error(),
|
|
1256
1310
|
onSuccess: () => null,
|
|
1257
1311
|
});
|
|
1258
|
-
const
|
|
1312
|
+
const invitationsError = AsyncResult.match(invitationsResult, {
|
|
1313
|
+
onInitial: () => null,
|
|
1314
|
+
onFailure: () => m.organization_invitations_load_error(),
|
|
1315
|
+
onSuccess: () => null,
|
|
1316
|
+
});
|
|
1317
|
+
const loadError = membersError ?? invitationsError;
|
|
1318
|
+
const loading = !lastMembersData &&
|
|
1319
|
+
(membersResult._tag === "Initial" || invitationsResult._tag === "Initial");
|
|
1259
1320
|
const canInviteMembers = canManageMembers;
|
|
1260
1321
|
const canRemoveMembers = canManageMembers;
|
|
1261
1322
|
useEffect(() => {
|
|
1262
|
-
if (!
|
|
1323
|
+
if (!currentMembers || !currentInvitations)
|
|
1263
1324
|
return;
|
|
1264
|
-
setLastMembersData(
|
|
1265
|
-
|
|
1325
|
+
setLastMembersData({
|
|
1326
|
+
members: Array.from(currentMembers),
|
|
1327
|
+
invitations: Array.from(currentInvitations).filter((invitation) => invitation.status === "pending"),
|
|
1328
|
+
});
|
|
1329
|
+
}, [currentInvitations, currentMembers]);
|
|
1266
1330
|
const [inviteForm] = useState(() => FormReact.make(inviteMemberFormBuilder, {
|
|
1267
1331
|
fields: {
|
|
1268
1332
|
email: TextField,
|
|
1269
1333
|
role: SelectField,
|
|
1270
1334
|
},
|
|
1271
|
-
onSubmit: (_, { decoded: value }) => Effect.
|
|
1272
|
-
|
|
1273
|
-
|
|
1274
|
-
|
|
1275
|
-
|
|
1276
|
-
organizationId: organization.id,
|
|
1277
|
-
});
|
|
1278
|
-
if (result.error) {
|
|
1279
|
-
throw new Error(result.error.message ?? m.organization_invite_error());
|
|
1280
|
-
}
|
|
1281
|
-
refreshMembers();
|
|
1282
|
-
return result.data;
|
|
1335
|
+
onSubmit: (_, { decoded: value }) => authHttpClient(baseUrl).pipe(Effect.flatMap((client) => client.auth.organizationInviteMember({
|
|
1336
|
+
payload: {
|
|
1337
|
+
email: value.email.trim(),
|
|
1338
|
+
role: normalizeInvitationRole(value.role),
|
|
1339
|
+
organizationId: organization.id,
|
|
1283
1340
|
},
|
|
1284
|
-
|
|
1285
|
-
|
|
1286
|
-
|
|
1287
|
-
}),
|
|
1341
|
+
})), Effect.tap(() => Effect.sync(refreshInvitations)), Effect.mapError((cause) => cause instanceof Error
|
|
1342
|
+
? cause
|
|
1343
|
+
: new Error(m.organization_invite_error()))),
|
|
1288
1344
|
}));
|
|
1289
1345
|
const submitInvitation = useAtomSet(inviteForm.submit);
|
|
1290
1346
|
const resetInvitation = useAtomSet(inviteForm.reset);
|
|
@@ -1304,56 +1360,73 @@ function OrganizationMembersManager({ authClient, baseUrl, canManageMembers, org
|
|
|
1304
1360
|
...current,
|
|
1305
1361
|
[member.id]: nextRole,
|
|
1306
1362
|
}));
|
|
1307
|
-
|
|
1308
|
-
|
|
1309
|
-
|
|
1310
|
-
|
|
1311
|
-
|
|
1312
|
-
|
|
1363
|
+
try {
|
|
1364
|
+
await Effect.runPromise(authHttpClient(baseUrl).pipe(Effect.flatMap((client) => client.auth.organizationUpdateMemberRole({
|
|
1365
|
+
payload: {
|
|
1366
|
+
memberId: member.id,
|
|
1367
|
+
role: Array.isArray(role)
|
|
1368
|
+
? role
|
|
1369
|
+
: normalizeOrganizationRole(role),
|
|
1370
|
+
organizationId: organization.id,
|
|
1371
|
+
},
|
|
1372
|
+
}))));
|
|
1373
|
+
refreshMembers();
|
|
1374
|
+
}
|
|
1375
|
+
catch (cause) {
|
|
1313
1376
|
setMemberRoleOverrides((current) => ({
|
|
1314
1377
|
...current,
|
|
1315
1378
|
[member.id]: member.role,
|
|
1316
1379
|
}));
|
|
1317
|
-
setError(
|
|
1380
|
+
setError(organizationFailureMessage(cause, m.organization_member_role_error()));
|
|
1318
1381
|
}
|
|
1319
1382
|
};
|
|
1320
1383
|
const removeMember = async (member) => {
|
|
1321
1384
|
setError(null);
|
|
1322
|
-
|
|
1323
|
-
|
|
1324
|
-
|
|
1325
|
-
|
|
1326
|
-
|
|
1327
|
-
|
|
1328
|
-
|
|
1385
|
+
try {
|
|
1386
|
+
await Effect.runPromise(authHttpClient(baseUrl).pipe(Effect.flatMap((client) => client.auth.organizationRemoveMember({
|
|
1387
|
+
payload: {
|
|
1388
|
+
memberIdOrEmail: member.id,
|
|
1389
|
+
organizationId: organization.id,
|
|
1390
|
+
},
|
|
1391
|
+
}))));
|
|
1392
|
+
refreshMembers();
|
|
1393
|
+
}
|
|
1394
|
+
catch (cause) {
|
|
1395
|
+
setError(organizationFailureMessage(cause, m.organization_member_remove_error()));
|
|
1329
1396
|
}
|
|
1330
|
-
refreshMembers();
|
|
1331
1397
|
};
|
|
1332
1398
|
const leaveOrganization = async () => {
|
|
1333
1399
|
setLeavingOrganization(true);
|
|
1334
1400
|
setError(null);
|
|
1335
|
-
|
|
1336
|
-
|
|
1337
|
-
|
|
1338
|
-
|
|
1339
|
-
|
|
1340
|
-
|
|
1341
|
-
|
|
1401
|
+
try {
|
|
1402
|
+
await Effect.runPromise(authHttpClient(baseUrl).pipe(Effect.flatMap((client) => client.auth.organizationLeave({
|
|
1403
|
+
payload: { organizationId: organization.id },
|
|
1404
|
+
}))));
|
|
1405
|
+
notifyAuthChange();
|
|
1406
|
+
await onLeft();
|
|
1407
|
+
}
|
|
1408
|
+
catch (cause) {
|
|
1409
|
+
setError(organizationFailureMessage(cause, m.organization_member_leave_error()));
|
|
1410
|
+
}
|
|
1411
|
+
finally {
|
|
1412
|
+
setLeavingOrganization(false);
|
|
1342
1413
|
}
|
|
1343
|
-
await onLeft();
|
|
1344
1414
|
};
|
|
1345
1415
|
const cancelInvitation = async (invitation) => {
|
|
1346
1416
|
setCancellingInvitationId(invitation.id);
|
|
1347
1417
|
setError(null);
|
|
1348
|
-
|
|
1349
|
-
|
|
1350
|
-
|
|
1351
|
-
|
|
1352
|
-
|
|
1353
|
-
|
|
1354
|
-
|
|
1418
|
+
try {
|
|
1419
|
+
await Effect.runPromise(authHttpClient(baseUrl).pipe(Effect.flatMap((client) => client.auth.organizationCancelInvitation({
|
|
1420
|
+
payload: { invitationId: invitation.id },
|
|
1421
|
+
}))));
|
|
1422
|
+
refreshInvitations();
|
|
1423
|
+
}
|
|
1424
|
+
catch (cause) {
|
|
1425
|
+
setError(organizationFailureMessage(cause, m.organization_invitation_cancel_error()));
|
|
1426
|
+
}
|
|
1427
|
+
finally {
|
|
1428
|
+
setCancellingInvitationId(null);
|
|
1355
1429
|
}
|
|
1356
|
-
refreshMembers();
|
|
1357
1430
|
};
|
|
1358
1431
|
return (_jsxs(_Fragment, { children: [_jsxs(DialogHeader, { children: [_jsx(DialogTitle, { className: "text-2xl", children: inviting
|
|
1359
1432
|
? m.organization_invite_member_title()
|
|
@@ -1368,7 +1441,7 @@ function OrganizationMembersManager({ authClient, baseUrl, canManageMembers, org
|
|
|
1368
1441
|
}, children: [_jsx(inviteForm.email, { label: m.organization_member_email(), placeholder: "teammate@example.com", type: "email", required: true }), _jsx(inviteForm.role, { label: m.organization_member_role(), options: organizationRoles.map((role) => ({
|
|
1369
1442
|
label: organizationRoleLabel(role, m),
|
|
1370
1443
|
value: role,
|
|
1371
|
-
})) }), _jsx("div", { className: "self-end", children: _jsx(SubmitButton, { form: inviteForm }) }), _jsx(SubmitError, { result: inviteResult })] }) })) : null, !inviting &&
|
|
1444
|
+
})) }), _jsx("div", { className: "self-end", children: _jsx(SubmitButton, { form: inviteForm }) }), _jsx(SubmitError, { result: inviteResult })] }) })) : null, !inviting && loadError ? (_jsx("p", { className: "text-destructive text-sm", children: loadError })) : null, !inviting && error ? (_jsx("p", { className: "text-destructive text-sm", children: error })) : null, !inviting ? (_jsxs("section", { className: "flex min-w-0 flex-col gap-3", children: [_jsxs("div", { children: [_jsx("h3", { className: "font-medium", children: m.organization_members_heading() }), _jsx("p", { className: "text-muted-foreground text-sm", children: m.organization_members_description() })] }), _jsx("div", { className: "-m-1 min-w-0 overflow-x-auto p-1", children: _jsx(DataTable, { columns: memberColumns({
|
|
1372
1445
|
m,
|
|
1373
1446
|
baseUrl,
|
|
1374
1447
|
canChangeRoles: canManageMembers,
|
|
@@ -1493,11 +1566,11 @@ const invitationRowActions = ({ m, cancellingInvitationId, onCancel, }) => [
|
|
|
1493
1566
|
onClick: onCancel,
|
|
1494
1567
|
},
|
|
1495
1568
|
];
|
|
1496
|
-
function OrganizationApiKeyManager({
|
|
1569
|
+
function OrganizationApiKeyManager({ baseUrl, organization, active, permissionLabels, permissions, }) {
|
|
1497
1570
|
const m = useOrganizationMessages();
|
|
1498
1571
|
const hasOpened = useOpenedOnce(active);
|
|
1499
1572
|
const keysAtom = hasOpened
|
|
1500
|
-
? organizationApiKeysAtom(
|
|
1573
|
+
? organizationApiKeysAtom(baseUrl)(organization.id)
|
|
1501
1574
|
: emptyOrganizationApiKeysAtom;
|
|
1502
1575
|
const keysResult = useAtomValue(keysAtom);
|
|
1503
1576
|
const refreshKeys = useAtomRefresh(keysAtom);
|
|
@@ -1514,7 +1587,7 @@ function OrganizationApiKeyManager({ authClient, organization, active, permissio
|
|
|
1514
1587
|
const keys = AsyncResult.match(keysResult, {
|
|
1515
1588
|
onInitial: () => [],
|
|
1516
1589
|
onFailure: () => [],
|
|
1517
|
-
onSuccess: ({ value }) => Array.from(value),
|
|
1590
|
+
onSuccess: ({ value }) => Array.from(value.apiKeys),
|
|
1518
1591
|
});
|
|
1519
1592
|
const keysError = AsyncResult.match(keysResult, {
|
|
1520
1593
|
onInitial: () => null,
|
|
@@ -1524,25 +1597,27 @@ function OrganizationApiKeyManager({ authClient, organization, active, permissio
|
|
|
1524
1597
|
const loading = keysResult._tag === "Initial";
|
|
1525
1598
|
const [createForm] = useState(() => FormReact.make(apiKeyFormBuilder, {
|
|
1526
1599
|
fields: { name: TextField, referrers: TextAreaField },
|
|
1527
|
-
onSubmit: (_, { decoded: value }) => Effect.
|
|
1528
|
-
|
|
1529
|
-
|
|
1530
|
-
|
|
1600
|
+
onSubmit: (_, { decoded: value }) => Effect.gen(function* () {
|
|
1601
|
+
yield* Effect.sync(() => setCreatedKey(null));
|
|
1602
|
+
const client = yield* authHttpClient(baseUrl);
|
|
1603
|
+
const created = yield* client.authExtra.createApiKey({
|
|
1604
|
+
payload: {
|
|
1531
1605
|
configId: "organization",
|
|
1532
1606
|
organizationId: organization.id,
|
|
1533
1607
|
name: value.name.trim(),
|
|
1534
1608
|
permissions: organizationApiKeySelectedPermissions(permissionOptionsRef.current, selectedPermissionsRef.current),
|
|
1535
1609
|
referrers: parseApiKeyReferrers(value.referrers, m.user_api_key_referrers_error()),
|
|
1536
|
-
},
|
|
1610
|
+
},
|
|
1611
|
+
});
|
|
1612
|
+
yield* Effect.sync(() => {
|
|
1537
1613
|
setCreatedKey(created.key);
|
|
1538
1614
|
setSelectedPermissions({});
|
|
1539
1615
|
refreshKeys();
|
|
1540
|
-
|
|
1541
|
-
|
|
1542
|
-
|
|
1543
|
-
|
|
1544
|
-
|
|
1545
|
-
}),
|
|
1616
|
+
});
|
|
1617
|
+
return created;
|
|
1618
|
+
}).pipe(Effect.mapError((cause) => cause instanceof Error
|
|
1619
|
+
? cause
|
|
1620
|
+
: new Error(m.user_api_key_create_error()))),
|
|
1546
1621
|
}));
|
|
1547
1622
|
const submitApiKey = useAtomSet(createForm.submit);
|
|
1548
1623
|
const resetApiKey = useAtomSet(createForm.reset);
|
|
@@ -1555,15 +1630,16 @@ function OrganizationApiKeyManager({ authClient, organization, active, permissio
|
|
|
1555
1630
|
resetApiKey();
|
|
1556
1631
|
}, [createResult, resetApiKey]);
|
|
1557
1632
|
const deleteKey = async (key) => {
|
|
1558
|
-
|
|
1559
|
-
|
|
1560
|
-
|
|
1561
|
-
|
|
1562
|
-
|
|
1563
|
-
|
|
1564
|
-
|
|
1633
|
+
setError(null);
|
|
1634
|
+
try {
|
|
1635
|
+
await Effect.runPromise(authHttpClient(baseUrl).pipe(Effect.flatMap((client) => client.auth.apiKeyDelete({
|
|
1636
|
+
payload: { configId: "organization", keyId: key.id },
|
|
1637
|
+
}))));
|
|
1638
|
+
refreshKeys();
|
|
1639
|
+
}
|
|
1640
|
+
catch (cause) {
|
|
1641
|
+
setError(organizationFailureMessage(cause, m.user_api_key_delete_error()));
|
|
1565
1642
|
}
|
|
1566
|
-
refreshKeys();
|
|
1567
1643
|
};
|
|
1568
1644
|
return (_jsxs(_Fragment, { children: [_jsxs(DialogHeader, { children: [_jsx(DialogTitle, { className: "text-2xl", children: editingKey
|
|
1569
1645
|
? m.user_api_key_edit_title()
|
|
@@ -1606,7 +1682,7 @@ function OrganizationApiKeyManager({ authClient, organization, active, permissio
|
|
|
1606
1682
|
}, searchState: "local", state: {
|
|
1607
1683
|
empty: loading ? m.user_loading() : m.table_empty(),
|
|
1608
1684
|
loading,
|
|
1609
|
-
} }) })) : null, editingKey ? (_jsx(
|
|
1685
|
+
} }) })) : null, editingKey ? (_jsx(OrganizationApiKeyEditForm, { baseUrl: baseUrl, keyData: editingKey, permissions: permissions, permissionLabels: permissionLabels, messages: {
|
|
1610
1686
|
enabled: m.user_api_key_enabled(),
|
|
1611
1687
|
name: m.user_api_key_name(),
|
|
1612
1688
|
referrers: m.user_api_key_referrers(),
|
|
@@ -1621,6 +1697,76 @@ function OrganizationApiKeyManager({ authClient, organization, active, permissio
|
|
|
1621
1697
|
setEditingKey(null);
|
|
1622
1698
|
} }, editingKey.id)) : null] })] }));
|
|
1623
1699
|
}
|
|
1700
|
+
function OrganizationApiKeyEditForm({ baseUrl, keyData, messages, permissions, permissionLabels, onSaved, }) {
|
|
1701
|
+
const permissionOptions = Object.entries(permissions).flatMap(([project, actions]) => actions.map((action) => ({
|
|
1702
|
+
id: `${project}:${action}`,
|
|
1703
|
+
project,
|
|
1704
|
+
action,
|
|
1705
|
+
})));
|
|
1706
|
+
const currentPermissions = Schema.decodeUnknownOption(ExtraApiKeyPermissions)(keyData.permissions ?? {});
|
|
1707
|
+
const currentGrant = Option.isSome(currentPermissions)
|
|
1708
|
+
? currentPermissions.value
|
|
1709
|
+
: {};
|
|
1710
|
+
const initialSelectedPermissions = Object.fromEntries(permissionOptions.map((option) => [
|
|
1711
|
+
option.id,
|
|
1712
|
+
currentGrant[option.project]?.includes(option.action) ?? false,
|
|
1713
|
+
]));
|
|
1714
|
+
const permissionOptionsRef = useRef(permissionOptions);
|
|
1715
|
+
const permissionsRef = useRef(permissions);
|
|
1716
|
+
permissionOptionsRef.current = permissionOptions;
|
|
1717
|
+
permissionsRef.current = permissions;
|
|
1718
|
+
const [form] = useState(() => FormReact.make(editApiKeyFormBuilder, {
|
|
1719
|
+
fields: {
|
|
1720
|
+
name: TextField,
|
|
1721
|
+
enabled: CheckboxField,
|
|
1722
|
+
referrers: TextAreaField,
|
|
1723
|
+
permissions: ApiKeyPermissionsField,
|
|
1724
|
+
},
|
|
1725
|
+
mode: { validation: "onSubmit" },
|
|
1726
|
+
onSubmit: (_, { decoded }) => Effect.gen(function* () {
|
|
1727
|
+
const referrers = parseApiKeyReferrers(decoded.referrers, messages.referrersError);
|
|
1728
|
+
const selectedGrant = {};
|
|
1729
|
+
for (const project of Object.keys(permissionsRef.current)) {
|
|
1730
|
+
selectedGrant[project] = [];
|
|
1731
|
+
}
|
|
1732
|
+
for (const option of permissionOptionsRef.current) {
|
|
1733
|
+
if (!decoded.permissions[option.id])
|
|
1734
|
+
continue;
|
|
1735
|
+
selectedGrant[option.project] = [
|
|
1736
|
+
...(selectedGrant[option.project] ?? []),
|
|
1737
|
+
option.action,
|
|
1738
|
+
];
|
|
1739
|
+
}
|
|
1740
|
+
const client = yield* authHttpClient(baseUrl);
|
|
1741
|
+
const updated = yield* client.authExtra.updateApiKey({
|
|
1742
|
+
params: { keyId: keyData.id },
|
|
1743
|
+
payload: {
|
|
1744
|
+
configId: "organization",
|
|
1745
|
+
name: decoded.name.trim(),
|
|
1746
|
+
enabled: decoded.enabled,
|
|
1747
|
+
permissions: selectedGrant,
|
|
1748
|
+
referrers,
|
|
1749
|
+
},
|
|
1750
|
+
});
|
|
1751
|
+
yield* Effect.sync(onSaved);
|
|
1752
|
+
return updated;
|
|
1753
|
+
}).pipe(Effect.mapError((cause) => cause instanceof Error
|
|
1754
|
+
? cause
|
|
1755
|
+
: new Error(organizationFailureMessage(cause, messages.updateError)))),
|
|
1756
|
+
}));
|
|
1757
|
+
const submit = useAtomSet(form.submit);
|
|
1758
|
+
const submitResult = useAtomValue(form.submit);
|
|
1759
|
+
return (_jsx("section", { className: "w-full", children: _jsx(form.Initialize, { defaultValues: {
|
|
1760
|
+
name: keyData.name ?? "",
|
|
1761
|
+
enabled: keyData.enabled,
|
|
1762
|
+
referrers: apiKeyReferrers(keyData.metadata).join("\n"),
|
|
1763
|
+
permissions: initialSelectedPermissions,
|
|
1764
|
+
}, children: _jsxs("form", { className: "flex flex-col gap-4", onSubmit: (event) => {
|
|
1765
|
+
event.preventDefault();
|
|
1766
|
+
event.stopPropagation();
|
|
1767
|
+
submit();
|
|
1768
|
+
}, children: [_jsx(form.name, { label: messages.name, required: true }), _jsx(form.enabled, { label: messages.enabled }), _jsx(form.referrers, { label: messages.referrers, description: messages.referrersDescription, placeholder: messages.referrersPlaceholder, rows: 3 }), _jsx(form.permissions, { description: messages.permissionsDescription, idPrefix: `organization-edit-${keyData.id}`, labels: permissionLabels, permissions: permissions, title: messages.permissions }), _jsx(SubmitError, { result: submitResult }), _jsx(SubmitButton, { form: form })] }) }) }));
|
|
1769
|
+
}
|
|
1624
1770
|
const apiKeyColumns = ({ m, }) => [
|
|
1625
1771
|
{
|
|
1626
1772
|
accessorKey: "name",
|