@krak-stack/auth 0.1.70 → 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 -46
- package/dist/components/admin-users.js +115 -138
- 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 -324
- 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 +265 -316
- 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 +30 -32
- package/dist/server/actor.js +39 -22
- 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 +3 -3
- package/dist/server/middleware.js +10 -5
- package/dist/server/schema.js +1 -1
- package/dist/service.d.ts +2053 -201
- package/dist/service.js +32 -21
- package/package.json +10 -9
- 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,13 +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 {} from "
|
|
6
|
-
import { Effect, Option, Schema } from "effect";
|
|
5
|
+
import { Effect, Option, Predicate, Schema } from "effect";
|
|
7
6
|
import { AsyncResult, Atom } from "effect/unstable/reactivity";
|
|
8
7
|
import { ArrowLeft, Building2, Check, ChevronsUpDown, Copy, KeyRound, LogOut, Mail, PencilIcon, Plus, Trash2, UserIcon, UserPlus, Users, X, } from "lucide-react";
|
|
9
8
|
import { createContext, useContext, useEffect, useEffectEvent, useRef, useState, } from "react";
|
|
10
9
|
import { DataTable, DataTableRelationshipCell, } from "@krak-stack/registry/data-table";
|
|
11
|
-
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";
|
|
12
11
|
import { EditingLocaleSwitcher } from "@krak-stack/registry/editing-locale-switcher";
|
|
13
12
|
import { AppBrand } from "@krak-stack/registry/app-brand";
|
|
14
13
|
import { Field, FieldLabel, FieldSet } from "@/components/ui/field";
|
|
@@ -21,18 +20,19 @@ import { DropdownMenu, DropdownMenuContent, DropdownMenuGroup, DropdownMenuItem,
|
|
|
21
20
|
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from "@/components/ui/select";
|
|
22
21
|
import { Separator } from "@/components/ui/separator";
|
|
23
22
|
import { OrganizationEmail, OrganizationAddress, OrganizationMetadata, OrganizationPhone, OrganizationSocial, OrganizationTranslation, OrganizationWebsite, decodeOrganizationMetadata, } from "@krak-stack/auth/schema";
|
|
24
|
-
import { isOrganizationRole, normalizeOrganizationRole, normalizeOrganizationRoles, organizationRoles, parseRoleList, } from "../roles";
|
|
25
|
-
import { authClientApi } from "./auth-client-api";
|
|
26
|
-
import {
|
|
27
|
-
import {
|
|
28
|
-
import {
|
|
29
|
-
import { ApiKeyPermissions } from "./api-key-permissions";
|
|
30
|
-
import { ApiKeyRateLimit, apiKeyUsagePercent } from "./api-key-rate-limit";
|
|
31
|
-
import { ApiKeyReferrers } from "./api-key-referrers";
|
|
32
|
-
import { useOpenedOnce } from "./hooks";
|
|
33
|
-
import { invitationDisplayStatus, isInvitationExpired, useInvitationExpirationClock, } from "./invitation-expiration";
|
|
34
|
-
import { ExtraUploadedAsset } from "../extra/schema";
|
|
35
|
-
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";
|
|
36
36
|
const messages = {
|
|
37
37
|
en: {
|
|
38
38
|
organization_back: "Back",
|
|
@@ -321,73 +321,55 @@ const organizationSwitcherMessages = (overrides) => ({
|
|
|
321
321
|
const interpolate = (value, params) => params
|
|
322
322
|
? value.replace(/\{([^}]+)\}/g, (_, key) => String(params[key] ?? `{${key}}`))
|
|
323
323
|
: value;
|
|
324
|
-
const
|
|
325
|
-
|
|
326
|
-
|
|
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
|
+
};
|
|
327
333
|
const OrganizationMessagesContext = createContext(organizationMessageFns(organizationSwitcherMessages()));
|
|
328
334
|
const useOrganizationMessages = () => useContext(OrganizationMessagesContext);
|
|
329
335
|
const normalizeInvitationRole = (role) => {
|
|
330
336
|
const normalized = normalizeOrganizationRole(role);
|
|
331
337
|
return normalized === "support" ? "member" : normalized;
|
|
332
338
|
};
|
|
333
|
-
const userInvitationsAtom = Atom.family((
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
}
|
|
340
|
-
return (result.data ?? []).filter((invitation) => invitation.status === "pending");
|
|
341
|
-
},
|
|
342
|
-
catch: (error) => error,
|
|
343
|
-
}))));
|
|
344
|
-
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", {
|
|
345
345
|
query: { locale, organizationId },
|
|
346
346
|
timeToLive: "5 minutes",
|
|
347
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,
|
|
348
372
|
}));
|
|
349
|
-
const emptyUserInvitationsAtom = Atom.make(Effect.try({
|
|
350
|
-
try: () => [],
|
|
351
|
-
catch: (error) => error,
|
|
352
|
-
}));
|
|
353
|
-
const organizationMembersAtom = Atom.family((authClient) => Atom.family((organizationId) => Atom.keepAlive(Atom.make(Effect.tryPromise({
|
|
354
|
-
try: async () => {
|
|
355
|
-
const [membersResult, invitationsResult] = await Promise.all([
|
|
356
|
-
authClient.organization.listMembers({
|
|
357
|
-
query: { organizationId },
|
|
358
|
-
}),
|
|
359
|
-
authClient.organization.listInvitations({
|
|
360
|
-
query: { organizationId },
|
|
361
|
-
}),
|
|
362
|
-
]);
|
|
363
|
-
if (membersResult.error) {
|
|
364
|
-
throw new Error(membersResult.error.message ?? "Could not load members.");
|
|
365
|
-
}
|
|
366
|
-
if (invitationsResult.error) {
|
|
367
|
-
throw new Error(invitationsResult.error.message ??
|
|
368
|
-
"Could not load invitations.");
|
|
369
|
-
}
|
|
370
|
-
return {
|
|
371
|
-
members: membersResult.data?.members ?? [],
|
|
372
|
-
invitations: (invitationsResult.data ?? []).filter((invitation) => invitation.status === "pending"),
|
|
373
|
-
};
|
|
374
|
-
},
|
|
375
|
-
catch: (error) => error,
|
|
376
|
-
})))));
|
|
377
|
-
const emptyOrganizationMembersAtom = Atom.make(Effect.succeed({ members: [], invitations: [] }));
|
|
378
|
-
const organizationApiKeysAtom = Atom.family((authClient) => Atom.family((organizationId) => Atom.keepAlive(Atom.make(Effect.tryPromise({
|
|
379
|
-
try: async () => {
|
|
380
|
-
const result = await authClient.apiKey.list({
|
|
381
|
-
query: { configId: "organization", organizationId },
|
|
382
|
-
});
|
|
383
|
-
if (result.error) {
|
|
384
|
-
throw new Error(result.error.message ?? "Could not load API keys.");
|
|
385
|
-
}
|
|
386
|
-
return result.data?.apiKeys ?? [];
|
|
387
|
-
},
|
|
388
|
-
catch: (error) => error,
|
|
389
|
-
})))));
|
|
390
|
-
const emptyOrganizationApiKeysAtom = Atom.make(Effect.succeed([]));
|
|
391
373
|
const organizationImageSchema = Schema.Union([
|
|
392
374
|
Schema.String,
|
|
393
375
|
Schema.instanceOf(File),
|
|
@@ -541,35 +523,46 @@ const inviteMemberFormBuilder = FormBuilder.empty
|
|
|
541
523
|
const apiKeyFormBuilder = FormBuilder.empty
|
|
542
524
|
.addField("name", Schema.NonEmptyString)
|
|
543
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 }) }));
|
|
544
532
|
const slugify = (value) => value
|
|
545
533
|
.trim()
|
|
546
534
|
.toLowerCase()
|
|
547
535
|
.replace(/[^a-z0-9]+/g, "-")
|
|
548
536
|
.replace(/^-+|-+$/g, "");
|
|
549
537
|
const noParentOrganization = "__none__";
|
|
550
|
-
const
|
|
551
|
-
|
|
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))
|
|
552
545
|
return false;
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
return [code, message].some((value) => {
|
|
556
|
-
if (typeof value !== "string")
|
|
546
|
+
return [decoded.value.code, decoded.value.message].some((value) => {
|
|
547
|
+
if (!value)
|
|
557
548
|
return false;
|
|
558
549
|
const normalized = value.toLowerCase().replaceAll("_", " ");
|
|
559
550
|
return normalized.includes("organization already exists");
|
|
560
551
|
});
|
|
561
552
|
};
|
|
562
|
-
const
|
|
563
|
-
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) => {
|
|
564
563
|
const payload = new FormData();
|
|
565
564
|
payload.append("file", file);
|
|
566
|
-
|
|
567
|
-
const uploaded = await decodeUploadedAsset(await uploadImage({ payload }));
|
|
568
|
-
return assetPath(uploaded.url);
|
|
569
|
-
}
|
|
570
|
-
catch {
|
|
571
|
-
throw new Error(m.organization_logo_upload_error());
|
|
572
|
-
}
|
|
565
|
+
return uploadImage({ payload }).pipe(Effect.flatMap(decodeUploadedAsset), Effect.map((uploaded) => assetPath(uploaded.url)), Effect.mapError(() => new Error(m.organization_logo_upload_error())));
|
|
573
566
|
};
|
|
574
567
|
const currentOrganizationLocale = () => getLocale() === "fr" ? "fr" : "en";
|
|
575
568
|
const parseOrganizationMetadata = decodeOrganizationMetadata;
|
|
@@ -644,12 +637,12 @@ const organizationFormDefaults = (organization, baseUrl) => {
|
|
|
644
637
|
frIcon: assetUrl(fr?.icon, baseUrl) || null,
|
|
645
638
|
};
|
|
646
639
|
};
|
|
647
|
-
const organizationLogoFromForm =
|
|
640
|
+
const organizationLogoFromForm = (value, m, uploadImage) => {
|
|
648
641
|
if (value instanceof File)
|
|
649
|
-
return
|
|
650
|
-
if (
|
|
651
|
-
return assetPath(value);
|
|
652
|
-
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);
|
|
653
646
|
};
|
|
654
647
|
const organizationNameFromForm = (value, locale) => {
|
|
655
648
|
const preferredName = locale === "fr" ? value.frName : value.enName;
|
|
@@ -685,23 +678,19 @@ const invitationStatusLabel = (status, m) => {
|
|
|
685
678
|
}
|
|
686
679
|
};
|
|
687
680
|
const formatOrganizationDate = (date) => new Intl.DateTimeFormat(getLocale(), { dateStyle: "medium" }).format(new Date(date));
|
|
688
|
-
const organizationMetadataFromForm =
|
|
681
|
+
const organizationMetadataFromForm = Effect.fn(function* (value, m, uploadImage, existingMetadata) {
|
|
689
682
|
const existing = parseOrganizationMetadata(existingMetadata);
|
|
690
|
-
const
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
decodedExistingMetadata !== null &&
|
|
695
|
-
!Array.isArray(decodedExistingMetadata)
|
|
696
|
-
? decodedExistingMetadata
|
|
697
|
-
: {};
|
|
683
|
+
const preservedMetadata = Option.getOrElse(Schema.decodeUnknownOption(Schema.Union([
|
|
684
|
+
OrganizationMetadataRecord,
|
|
685
|
+
Schema.fromJsonString(OrganizationMetadataRecord),
|
|
686
|
+
]))(existingMetadata), () => ({}));
|
|
698
687
|
const translations = [];
|
|
699
688
|
const enName = value.enName.trim();
|
|
700
689
|
const frName = value.frName.trim();
|
|
701
|
-
const enLogo =
|
|
702
|
-
const enIcon =
|
|
703
|
-
const frLogo =
|
|
704
|
-
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);
|
|
705
694
|
const localized = (values) => (values ?? []).flatMap((translation) => {
|
|
706
695
|
const label = translation.label.trim();
|
|
707
696
|
return label ? [{ ...translation, label }] : [];
|
|
@@ -719,17 +708,13 @@ const organizationMetadataFromForm = async (value, m, uploadImage, existingMetad
|
|
|
719
708
|
});
|
|
720
709
|
const phones = value.phones.flatMap((phone) => {
|
|
721
710
|
const number = phone.number.trim();
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
translations: localized(phone.translations),
|
|
730
|
-
},
|
|
731
|
-
]
|
|
732
|
-
: [];
|
|
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];
|
|
733
718
|
});
|
|
734
719
|
const websites = value.websites.flatMap((website) => {
|
|
735
720
|
const url = website.url.trim();
|
|
@@ -748,17 +733,22 @@ const organizationMetadataFromForm = async (value, m, uploadImage, existingMetad
|
|
|
748
733
|
: [];
|
|
749
734
|
});
|
|
750
735
|
const addresses = value.addresses.flatMap((input) => {
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
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 };
|
|
762
752
|
return Object.keys(normalized).length
|
|
763
753
|
? [
|
|
764
754
|
{
|
|
@@ -815,31 +805,56 @@ const organizationMetadataFromForm = async (value, m, uploadImage, existingMetad
|
|
|
815
805
|
socials,
|
|
816
806
|
addresses,
|
|
817
807
|
};
|
|
818
|
-
};
|
|
819
|
-
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, }) {
|
|
820
810
|
const auth = useKrakstackAuth();
|
|
821
|
-
const
|
|
822
|
-
if (!authClient) {
|
|
823
|
-
throw new Error("KrakstackAuthProvider is required to use authClient.");
|
|
824
|
-
}
|
|
811
|
+
const baseUrl = providedBaseUrl ?? auth?.baseUrl;
|
|
825
812
|
const labels = organizationSwitcherMessages(messages);
|
|
826
813
|
const m = organizationMessageFns(labels);
|
|
827
|
-
const
|
|
828
|
-
const
|
|
829
|
-
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
|
+
})));
|
|
830
847
|
const lastAuthRefreshVersion = useRef(auth?.authRefreshVersion ?? 0);
|
|
831
848
|
const [uncontrolledDialog, setUncontrolledDialog] = useState(defaultDialog);
|
|
832
849
|
const [editingOrganizationLocale, setEditingOrganizationLocale] = useState(currentOrganizationLocale);
|
|
833
850
|
const dialog = controlledDialog !== undefined ? controlledDialog : uncontrolledDialog;
|
|
834
|
-
const invitationsAtom =
|
|
835
|
-
? userInvitationsAtom(authClient)
|
|
836
|
-
: emptyUserInvitationsAtom;
|
|
851
|
+
const invitationsAtom = userInvitationsAtom(baseUrl);
|
|
837
852
|
const invitationsResult = useAtomValue(invitationsAtom);
|
|
838
853
|
const refreshUserInvitations = useAtomRefresh(invitationsAtom);
|
|
839
854
|
const userInvitations = AsyncResult.match(invitationsResult, {
|
|
840
855
|
onInitial: () => [],
|
|
841
856
|
onFailure: () => [],
|
|
842
|
-
onSuccess: ({ value }) => Array.from(value),
|
|
857
|
+
onSuccess: ({ value }) => Array.from(value).filter((invitation) => invitation.status === "pending"),
|
|
843
858
|
});
|
|
844
859
|
const userInvitationsError = AsyncResult.match(invitationsResult, {
|
|
845
860
|
onInitial: () => null,
|
|
@@ -847,14 +862,14 @@ export function OrganizationSwitcher({ authClient: providedAuthClient, baseUrl,
|
|
|
847
862
|
onSuccess: () => null,
|
|
848
863
|
});
|
|
849
864
|
const loadingUserInvitations = invitationsResult._tag === "Initial";
|
|
850
|
-
const activeMemberRoles = parseRoleList(activeOrganization
|
|
865
|
+
const activeMemberRoles = parseRoleList(activeOrganization?.members.find((member) => member.userId === session?.user.id)?.role);
|
|
851
866
|
const canManageApiKeys = activeMemberRoles.some((role) => role === "owner" || role === "admin");
|
|
852
867
|
const canUpdateOrganization = canManageApiKeys;
|
|
853
868
|
const canSwitchOrganizations = features?.organizationSwitching ?? true;
|
|
854
869
|
const canCreateOrganization = features?.organizationCreation ?? true;
|
|
855
870
|
const canViewOrganizationInvitations = features?.userInvitations ?? true;
|
|
856
871
|
const setDialog = (next) => {
|
|
857
|
-
const nextDialog =
|
|
872
|
+
const nextDialog = Predicate.isFunction(next) ? next(dialog) : next;
|
|
858
873
|
if (nextDialog === dialog)
|
|
859
874
|
return;
|
|
860
875
|
if (controlledDialog === undefined)
|
|
@@ -863,9 +878,9 @@ export function OrganizationSwitcher({ authClient: providedAuthClient, baseUrl,
|
|
|
863
878
|
};
|
|
864
879
|
const openCreate = () => setDialog("create");
|
|
865
880
|
const refresh = async () => {
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
881
|
+
refreshOrganizations();
|
|
882
|
+
refreshActiveOrganization();
|
|
883
|
+
refreshSession();
|
|
869
884
|
};
|
|
870
885
|
const refreshOnSessionChanged = useEffectEvent(() => {
|
|
871
886
|
void refresh();
|
|
@@ -877,30 +892,32 @@ export function OrganizationSwitcher({ authClient: providedAuthClient, baseUrl,
|
|
|
877
892
|
lastAuthRefreshVersion.current = version;
|
|
878
893
|
refreshOnSessionChanged();
|
|
879
894
|
}, [auth?.authRefreshVersion]);
|
|
880
|
-
if (!session
|
|
895
|
+
if (!session) {
|
|
881
896
|
return _jsx(_Fragment, { children: renderUnauthenticated?.() });
|
|
882
897
|
}
|
|
883
|
-
const active = activeOrganization
|
|
898
|
+
const active = activeOrganization;
|
|
884
899
|
const activeName = active?.name;
|
|
885
|
-
const visibleOrganizations = organizations.
|
|
886
|
-
allowedOrganizationIds.includes(organization.id))
|
|
900
|
+
const visibleOrganizations = organizations.filter((organization) => !allowedOrganizationIds ||
|
|
901
|
+
allowedOrganizationIds.includes(organization.id));
|
|
887
902
|
const selectableOrganizations = canSwitchOrganizations
|
|
888
903
|
? visibleOrganizations.filter((organization) => organization.id !== active?.id)
|
|
889
904
|
: [];
|
|
890
905
|
const scrollOrganizationList = selectableOrganizations.length > 5;
|
|
891
|
-
const hasOrganizationListItems =
|
|
892
|
-
Boolean(
|
|
906
|
+
const hasOrganizationListItems = organizationsResult._tag === "Initial" ||
|
|
907
|
+
Boolean(organizationsError) ||
|
|
893
908
|
canSwitchOrganizations;
|
|
894
909
|
const refreshAfterInvitationAction = async (previousActiveId) => {
|
|
895
910
|
refreshUserInvitations();
|
|
896
911
|
await refresh();
|
|
897
912
|
if (!canSwitchOrganizations && previousActiveId) {
|
|
898
|
-
|
|
899
|
-
|
|
900
|
-
|
|
901
|
-
if (!result.error) {
|
|
913
|
+
try {
|
|
914
|
+
await Effect.runPromise(setActiveOrganization(previousActiveId));
|
|
915
|
+
notifyAuthChange();
|
|
902
916
|
await refresh();
|
|
903
|
-
onChange?.(organizations.
|
|
917
|
+
onChange?.(organizations.find((organization) => organization.id === previousActiveId) ?? null);
|
|
918
|
+
}
|
|
919
|
+
catch {
|
|
920
|
+
// The invitation action succeeded; keep the newly active organization.
|
|
904
921
|
}
|
|
905
922
|
}
|
|
906
923
|
};
|
|
@@ -912,61 +929,71 @@ export function OrganizationSwitcher({ authClient: providedAuthClient, baseUrl,
|
|
|
912
929
|
? { imageSrc: activeDisplay.image }
|
|
913
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
|
|
914
931
|
? { imageSrc: activeDisplay.image }
|
|
915
|
-
: {}) }) }), 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 &&
|
|
916
933
|
"max-h-64 overflow-y-auto overscroll-contain"), children: selectableOrganizations.map((organization) => {
|
|
917
934
|
const display = organizationDisplay(organization, m, baseUrl);
|
|
918
935
|
return (_jsx(DropdownMenuItem, { onClick: async () => {
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
|
|
936
|
+
try {
|
|
937
|
+
const result = await Effect.runPromise(setActiveOrganization(organization.id));
|
|
938
|
+
if (!result)
|
|
939
|
+
return;
|
|
940
|
+
notifyAuthChange();
|
|
923
941
|
await refresh();
|
|
924
942
|
onChange?.(organization);
|
|
925
943
|
}
|
|
944
|
+
catch {
|
|
945
|
+
// Switching previously failed silently in this menu.
|
|
946
|
+
}
|
|
926
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
|
|
927
948
|
? { imageSrc: display.image }
|
|
928
949
|
: {}) }) }, organization.id));
|
|
929
|
-
}) })) : canSwitchOrganizations &&
|
|
950
|
+
}) })) : canSwitchOrganizations &&
|
|
951
|
+
organizationsResult._tag !== "Initial" ? (_jsx(DropdownMenuItem, { disabled: true, children: active
|
|
930
952
|
? m.organization_switcher_no_other_organizations()
|
|
931
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: () => {
|
|
932
954
|
setDialog("invitations");
|
|
933
|
-
}, 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
|
|
934
|
-
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;
|
|
935
957
|
return (_jsxs(DropdownMenuItem, { onClick: () => {
|
|
936
958
|
void navigator.clipboard.writeText(organizationId);
|
|
937
959
|
}, children: [_jsx(Copy, {}), m.organization_copy_id()] }));
|
|
938
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) => {
|
|
939
961
|
setDialog((current) => open ? "create" : current === "create" ? null : current);
|
|
940
|
-
}, 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) => {
|
|
941
963
|
setDialog(null);
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
|
|
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
|
+
}
|
|
945
973
|
await refresh();
|
|
946
|
-
if (
|
|
974
|
+
if (activated) {
|
|
947
975
|
onCreate?.(organization);
|
|
948
976
|
onChange?.(organization);
|
|
949
977
|
}
|
|
950
978
|
} })] }) }), _jsx(Dialog, { open: dialog === "manage" && canUpdateOrganization, onOpenChange: (open) => {
|
|
951
979
|
setDialog((current) => open ? "manage" : current === "manage" ? null : current);
|
|
952
|
-
}, 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) => {
|
|
953
981
|
setDialog((current) => open ? "members" : current === "members" ? null : current);
|
|
954
|
-
}, 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 () => {
|
|
955
983
|
setDialog(null);
|
|
956
|
-
auth?.refreshAuth();
|
|
957
984
|
await refresh();
|
|
958
985
|
onChange?.(null);
|
|
959
986
|
} })) : null }) }), _jsx(Dialog, { open: dialog === "apiKeys" && canManageApiKeys, onOpenChange: (open) => {
|
|
960
987
|
setDialog((current) => open ? "apiKeys" : current === "apiKeys" ? null : current);
|
|
961
|
-
}, 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 ??
|
|
962
989
|
auth?.access?.apiKeyPermissions.organization ??
|
|
963
990
|
{} })) : null }) }), _jsx(Dialog, { open: dialog === "invitations" && canViewOrganizationInvitations, onOpenChange: (open) => {
|
|
964
991
|
setDialog((current) => open ? "invitations" : current === "invitations" ? null : current);
|
|
965
|
-
}, 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, {
|
|
966
|
-
? { 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 }
|
|
967
994
|
: {}), onActionComplete: refreshAfterInvitationAction })] }) })] }));
|
|
968
995
|
}
|
|
969
|
-
function UserInvitationsManager({
|
|
996
|
+
function UserInvitationsManager({ baseUrl, invitations, loading, error, activeOrganizationId, onActionComplete, }) {
|
|
970
997
|
const m = useOrganizationMessages();
|
|
971
998
|
const [actingInvitationId, setActingInvitationId] = useState(null);
|
|
972
999
|
const [actionError, setActionError] = useState(null);
|
|
@@ -976,28 +1003,35 @@ function UserInvitationsManager({ authClient, baseUrl, invitations, loading, err
|
|
|
976
1003
|
return;
|
|
977
1004
|
setActingInvitationId(invitation.id);
|
|
978
1005
|
setActionError(null);
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
|
|
982
|
-
|
|
983
|
-
|
|
984
|
-
|
|
985
|
-
|
|
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);
|
|
986
1018
|
}
|
|
987
|
-
await onActionComplete(activeOrganizationId);
|
|
988
1019
|
};
|
|
989
1020
|
const rejectInvitation = async (invitation) => {
|
|
990
1021
|
setActingInvitationId(invitation.id);
|
|
991
1022
|
setActionError(null);
|
|
992
|
-
|
|
993
|
-
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
|
|
998
|
-
|
|
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);
|
|
999
1034
|
}
|
|
1000
|
-
await onActionComplete(activeOrganizationId);
|
|
1001
1035
|
};
|
|
1002
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({
|
|
1003
1037
|
baseUrl,
|
|
@@ -1046,11 +1080,7 @@ const userInvitationColumns = ({ baseUrl, m, now, }) => [
|
|
|
1046
1080
|
];
|
|
1047
1081
|
function InvitationOrganizationBrand({ baseUrl, invitation, }) {
|
|
1048
1082
|
const locale = useKrakstackAuth()?.locale ?? currentOrganizationLocale();
|
|
1049
|
-
const profileResult = useAtomValue(invitationOrganizationProfileAtom(
|
|
1050
|
-
baseUrl,
|
|
1051
|
-
locale,
|
|
1052
|
-
organizationId: invitation.organizationId,
|
|
1053
|
-
}));
|
|
1083
|
+
const profileResult = useAtomValue(invitationOrganizationProfileAtom(baseUrl)(invitation.organizationId)(locale));
|
|
1054
1084
|
const profile = AsyncResult.match(profileResult, {
|
|
1055
1085
|
onInitial: () => null,
|
|
1056
1086
|
onFailure: () => null,
|
|
@@ -1077,34 +1107,39 @@ const userInvitationRowActions = ({ m, actingInvitationId, now, onAccept, onReje
|
|
|
1077
1107
|
onClick: onReject,
|
|
1078
1108
|
},
|
|
1079
1109
|
];
|
|
1080
|
-
function EditOrganizationSection({
|
|
1110
|
+
function EditOrganizationSection({ baseUrl, editingLocale, organization, onUpdated, }) {
|
|
1081
1111
|
const m = useOrganizationMessages();
|
|
1082
|
-
const uploadImage = useAtomSet(authClientApi(baseUrl).mutation("authExtra", "uploadUserImage"), { mode: "promise" });
|
|
1083
1112
|
const [defaultLocale] = useState(currentOrganizationLocale);
|
|
1084
1113
|
const defaultValues = organizationFormDefaults(organization, baseUrl);
|
|
1085
1114
|
const [form] = useState(() => FormReact.make(organizationFormBuilder, {
|
|
1086
1115
|
fields: organizationFormFields,
|
|
1087
|
-
onSubmit: (_, { decoded: value }) => Effect.
|
|
1088
|
-
|
|
1089
|
-
|
|
1090
|
-
|
|
1091
|
-
|
|
1092
|
-
|
|
1093
|
-
|
|
1094
|
-
|
|
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: {
|
|
1095
1126
|
organizationId: organization.id,
|
|
1096
|
-
data: {
|
|
1097
|
-
|
|
1098
|
-
|
|
1099
|
-
|
|
1100
|
-
|
|
1101
|
-
|
|
1102
|
-
|
|
1103
|
-
|
|
1104
|
-
|
|
1105
|
-
|
|
1106
|
-
:
|
|
1107
|
-
|
|
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()))),
|
|
1108
1143
|
}));
|
|
1109
1144
|
const submit = useAtomSet(form.submit);
|
|
1110
1145
|
const submitResult = useAtomValue(form.submit);
|
|
@@ -1134,40 +1169,42 @@ function EditOrganizationSection({ authClient, baseUrl, editingLocale, organizat
|
|
|
1134
1169
|
suggestedHeight: 512,
|
|
1135
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 })] }) }) }));
|
|
1136
1171
|
}
|
|
1137
|
-
function CreateOrganizationSection({
|
|
1172
|
+
function CreateOrganizationSection({ baseUrl, editingLocale, organizations, onCreated, }) {
|
|
1138
1173
|
const m = useOrganizationMessages();
|
|
1139
|
-
const uploadImage = useAtomSet(authClientApi(baseUrl).mutation("authExtra", "uploadUserImage"), { mode: "promise" });
|
|
1140
1174
|
const [defaultLocale] = useState(currentOrganizationLocale);
|
|
1141
1175
|
const defaultValues = organizationFormDefaults(undefined, baseUrl);
|
|
1142
1176
|
const [form] = useState(() => FormReact.make(organizationFormBuilder, {
|
|
1143
1177
|
fields: organizationFormFields,
|
|
1144
|
-
onSubmit: (_, { decoded: value }) => Effect.
|
|
1145
|
-
|
|
1146
|
-
|
|
1147
|
-
|
|
1148
|
-
|
|
1149
|
-
|
|
1150
|
-
|
|
1151
|
-
|
|
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
|
+
: {
|
|
1152
1189
|
name,
|
|
1153
1190
|
slug,
|
|
1154
|
-
metadata,
|
|
1155
|
-
|
|
1156
|
-
|
|
1157
|
-
|
|
1158
|
-
})
|
|
1159
|
-
|
|
1160
|
-
|
|
1161
|
-
|
|
1162
|
-
|
|
1163
|
-
|
|
1164
|
-
|
|
1165
|
-
|
|
1166
|
-
}
|
|
1167
|
-
|
|
1168
|
-
|
|
1169
|
-
|
|
1170
|
-
|
|
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()))),
|
|
1171
1208
|
}));
|
|
1172
1209
|
const submit = useAtomSet(form.submit);
|
|
1173
1210
|
const submitResult = useAtomValue(form.submit);
|
|
@@ -1220,24 +1257,40 @@ function OrganizationFormSection({ children, description, title, }) {
|
|
|
1220
1257
|
function OrganizationContactGroup({ children, title, }) {
|
|
1221
1258
|
return (_jsxs("div", { className: "flex flex-col gap-3", children: [_jsx("h4", { className: "text-sm font-medium", children: title }), children] }));
|
|
1222
1259
|
}
|
|
1223
|
-
function OrganizationMembersManager({
|
|
1260
|
+
function OrganizationMembersManager({ baseUrl, canManageMembers, organization, currentUserId, active, onLeft, }) {
|
|
1224
1261
|
const m = useOrganizationMessages();
|
|
1225
1262
|
const hasOpened = useOpenedOnce(active);
|
|
1226
1263
|
const membersAtom = hasOpened
|
|
1227
|
-
? organizationMembersAtom(
|
|
1264
|
+
? organizationMembersAtom(baseUrl)(organization.id)
|
|
1228
1265
|
: emptyOrganizationMembersAtom;
|
|
1266
|
+
const invitationsAtom = hasOpened
|
|
1267
|
+
? organizationInvitationsAtom(baseUrl)(organization.id)
|
|
1268
|
+
: emptyOrganizationInvitationsAtom;
|
|
1229
1269
|
const membersResult = useAtomValue(membersAtom);
|
|
1270
|
+
const invitationsResult = useAtomValue(invitationsAtom);
|
|
1230
1271
|
const refreshMembers = useAtomRefresh(membersAtom);
|
|
1272
|
+
const refreshInvitations = useAtomRefresh(invitationsAtom);
|
|
1231
1273
|
const [inviting, setInviting] = useState(false);
|
|
1232
1274
|
const [error, setError] = useState(null);
|
|
1233
1275
|
const [cancellingInvitationId, setCancellingInvitationId] = useState(null);
|
|
1234
1276
|
const [leavingOrganization, setLeavingOrganization] = useState(false);
|
|
1235
1277
|
const [lastMembersData, setLastMembersData] = useState(null);
|
|
1236
|
-
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, {
|
|
1237
1284
|
onInitial: () => null,
|
|
1238
1285
|
onFailure: () => null,
|
|
1239
1286
|
onSuccess: ({ value }) => value,
|
|
1240
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;
|
|
1241
1294
|
const membersData = currentMembersData ??
|
|
1242
1295
|
lastMembersData ?? {
|
|
1243
1296
|
members: [],
|
|
@@ -1256,36 +1309,38 @@ function OrganizationMembersManager({ authClient, baseUrl, canManageMembers, org
|
|
|
1256
1309
|
onFailure: () => m.organization_members_load_error(),
|
|
1257
1310
|
onSuccess: () => null,
|
|
1258
1311
|
});
|
|
1259
|
-
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");
|
|
1260
1320
|
const canInviteMembers = canManageMembers;
|
|
1261
1321
|
const canRemoveMembers = canManageMembers;
|
|
1262
1322
|
useEffect(() => {
|
|
1263
|
-
if (!
|
|
1323
|
+
if (!currentMembers || !currentInvitations)
|
|
1264
1324
|
return;
|
|
1265
|
-
setLastMembersData(
|
|
1266
|
-
|
|
1325
|
+
setLastMembersData({
|
|
1326
|
+
members: Array.from(currentMembers),
|
|
1327
|
+
invitations: Array.from(currentInvitations).filter((invitation) => invitation.status === "pending"),
|
|
1328
|
+
});
|
|
1329
|
+
}, [currentInvitations, currentMembers]);
|
|
1267
1330
|
const [inviteForm] = useState(() => FormReact.make(inviteMemberFormBuilder, {
|
|
1268
1331
|
fields: {
|
|
1269
1332
|
email: TextField,
|
|
1270
1333
|
role: SelectField,
|
|
1271
1334
|
},
|
|
1272
|
-
onSubmit: (_, { decoded: value }) => Effect.
|
|
1273
|
-
|
|
1274
|
-
|
|
1275
|
-
|
|
1276
|
-
|
|
1277
|
-
organizationId: organization.id,
|
|
1278
|
-
});
|
|
1279
|
-
if (result.error) {
|
|
1280
|
-
throw new Error(result.error.message ?? m.organization_invite_error());
|
|
1281
|
-
}
|
|
1282
|
-
refreshMembers();
|
|
1283
|
-
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,
|
|
1284
1340
|
},
|
|
1285
|
-
|
|
1286
|
-
|
|
1287
|
-
|
|
1288
|
-
}),
|
|
1341
|
+
})), Effect.tap(() => Effect.sync(refreshInvitations)), Effect.mapError((cause) => cause instanceof Error
|
|
1342
|
+
? cause
|
|
1343
|
+
: new Error(m.organization_invite_error()))),
|
|
1289
1344
|
}));
|
|
1290
1345
|
const submitInvitation = useAtomSet(inviteForm.submit);
|
|
1291
1346
|
const resetInvitation = useAtomSet(inviteForm.reset);
|
|
@@ -1305,56 +1360,73 @@ function OrganizationMembersManager({ authClient, baseUrl, canManageMembers, org
|
|
|
1305
1360
|
...current,
|
|
1306
1361
|
[member.id]: nextRole,
|
|
1307
1362
|
}));
|
|
1308
|
-
|
|
1309
|
-
|
|
1310
|
-
|
|
1311
|
-
|
|
1312
|
-
|
|
1313
|
-
|
|
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) {
|
|
1314
1376
|
setMemberRoleOverrides((current) => ({
|
|
1315
1377
|
...current,
|
|
1316
1378
|
[member.id]: member.role,
|
|
1317
1379
|
}));
|
|
1318
|
-
setError(
|
|
1380
|
+
setError(organizationFailureMessage(cause, m.organization_member_role_error()));
|
|
1319
1381
|
}
|
|
1320
1382
|
};
|
|
1321
1383
|
const removeMember = async (member) => {
|
|
1322
1384
|
setError(null);
|
|
1323
|
-
|
|
1324
|
-
|
|
1325
|
-
|
|
1326
|
-
|
|
1327
|
-
|
|
1328
|
-
|
|
1329
|
-
|
|
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()));
|
|
1330
1396
|
}
|
|
1331
|
-
refreshMembers();
|
|
1332
1397
|
};
|
|
1333
1398
|
const leaveOrganization = async () => {
|
|
1334
1399
|
setLeavingOrganization(true);
|
|
1335
1400
|
setError(null);
|
|
1336
|
-
|
|
1337
|
-
|
|
1338
|
-
|
|
1339
|
-
|
|
1340
|
-
|
|
1341
|
-
|
|
1342
|
-
|
|
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);
|
|
1343
1413
|
}
|
|
1344
|
-
await onLeft();
|
|
1345
1414
|
};
|
|
1346
1415
|
const cancelInvitation = async (invitation) => {
|
|
1347
1416
|
setCancellingInvitationId(invitation.id);
|
|
1348
1417
|
setError(null);
|
|
1349
|
-
|
|
1350
|
-
|
|
1351
|
-
|
|
1352
|
-
|
|
1353
|
-
|
|
1354
|
-
|
|
1355
|
-
|
|
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);
|
|
1356
1429
|
}
|
|
1357
|
-
refreshMembers();
|
|
1358
1430
|
};
|
|
1359
1431
|
return (_jsxs(_Fragment, { children: [_jsxs(DialogHeader, { children: [_jsx(DialogTitle, { className: "text-2xl", children: inviting
|
|
1360
1432
|
? m.organization_invite_member_title()
|
|
@@ -1369,7 +1441,7 @@ function OrganizationMembersManager({ authClient, baseUrl, canManageMembers, org
|
|
|
1369
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) => ({
|
|
1370
1442
|
label: organizationRoleLabel(role, m),
|
|
1371
1443
|
value: role,
|
|
1372
|
-
})) }), _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({
|
|
1373
1445
|
m,
|
|
1374
1446
|
baseUrl,
|
|
1375
1447
|
canChangeRoles: canManageMembers,
|
|
@@ -1494,11 +1566,11 @@ const invitationRowActions = ({ m, cancellingInvitationId, onCancel, }) => [
|
|
|
1494
1566
|
onClick: onCancel,
|
|
1495
1567
|
},
|
|
1496
1568
|
];
|
|
1497
|
-
function OrganizationApiKeyManager({
|
|
1569
|
+
function OrganizationApiKeyManager({ baseUrl, organization, active, permissionLabels, permissions, }) {
|
|
1498
1570
|
const m = useOrganizationMessages();
|
|
1499
1571
|
const hasOpened = useOpenedOnce(active);
|
|
1500
1572
|
const keysAtom = hasOpened
|
|
1501
|
-
? organizationApiKeysAtom(
|
|
1573
|
+
? organizationApiKeysAtom(baseUrl)(organization.id)
|
|
1502
1574
|
: emptyOrganizationApiKeysAtom;
|
|
1503
1575
|
const keysResult = useAtomValue(keysAtom);
|
|
1504
1576
|
const refreshKeys = useAtomRefresh(keysAtom);
|
|
@@ -1515,7 +1587,7 @@ function OrganizationApiKeyManager({ authClient, organization, active, permissio
|
|
|
1515
1587
|
const keys = AsyncResult.match(keysResult, {
|
|
1516
1588
|
onInitial: () => [],
|
|
1517
1589
|
onFailure: () => [],
|
|
1518
|
-
onSuccess: ({ value }) => Array.from(value),
|
|
1590
|
+
onSuccess: ({ value }) => Array.from(value.apiKeys),
|
|
1519
1591
|
});
|
|
1520
1592
|
const keysError = AsyncResult.match(keysResult, {
|
|
1521
1593
|
onInitial: () => null,
|
|
@@ -1525,25 +1597,27 @@ function OrganizationApiKeyManager({ authClient, organization, active, permissio
|
|
|
1525
1597
|
const loading = keysResult._tag === "Initial";
|
|
1526
1598
|
const [createForm] = useState(() => FormReact.make(apiKeyFormBuilder, {
|
|
1527
1599
|
fields: { name: TextField, referrers: TextAreaField },
|
|
1528
|
-
onSubmit: (_, { decoded: value }) => Effect.
|
|
1529
|
-
|
|
1530
|
-
|
|
1531
|
-
|
|
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: {
|
|
1532
1605
|
configId: "organization",
|
|
1533
1606
|
organizationId: organization.id,
|
|
1534
1607
|
name: value.name.trim(),
|
|
1535
1608
|
permissions: organizationApiKeySelectedPermissions(permissionOptionsRef.current, selectedPermissionsRef.current),
|
|
1536
1609
|
referrers: parseApiKeyReferrers(value.referrers, m.user_api_key_referrers_error()),
|
|
1537
|
-
},
|
|
1610
|
+
},
|
|
1611
|
+
});
|
|
1612
|
+
yield* Effect.sync(() => {
|
|
1538
1613
|
setCreatedKey(created.key);
|
|
1539
1614
|
setSelectedPermissions({});
|
|
1540
1615
|
refreshKeys();
|
|
1541
|
-
|
|
1542
|
-
|
|
1543
|
-
|
|
1544
|
-
|
|
1545
|
-
|
|
1546
|
-
}),
|
|
1616
|
+
});
|
|
1617
|
+
return created;
|
|
1618
|
+
}).pipe(Effect.mapError((cause) => cause instanceof Error
|
|
1619
|
+
? cause
|
|
1620
|
+
: new Error(m.user_api_key_create_error()))),
|
|
1547
1621
|
}));
|
|
1548
1622
|
const submitApiKey = useAtomSet(createForm.submit);
|
|
1549
1623
|
const resetApiKey = useAtomSet(createForm.reset);
|
|
@@ -1556,15 +1630,16 @@ function OrganizationApiKeyManager({ authClient, organization, active, permissio
|
|
|
1556
1630
|
resetApiKey();
|
|
1557
1631
|
}, [createResult, resetApiKey]);
|
|
1558
1632
|
const deleteKey = async (key) => {
|
|
1559
|
-
|
|
1560
|
-
|
|
1561
|
-
|
|
1562
|
-
|
|
1563
|
-
|
|
1564
|
-
|
|
1565
|
-
|
|
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()));
|
|
1566
1642
|
}
|
|
1567
|
-
refreshKeys();
|
|
1568
1643
|
};
|
|
1569
1644
|
return (_jsxs(_Fragment, { children: [_jsxs(DialogHeader, { children: [_jsx(DialogTitle, { className: "text-2xl", children: editingKey
|
|
1570
1645
|
? m.user_api_key_edit_title()
|
|
@@ -1607,7 +1682,7 @@ function OrganizationApiKeyManager({ authClient, organization, active, permissio
|
|
|
1607
1682
|
}, searchState: "local", state: {
|
|
1608
1683
|
empty: loading ? m.user_loading() : m.table_empty(),
|
|
1609
1684
|
loading,
|
|
1610
|
-
} }) })) : null, editingKey ? (_jsx(
|
|
1685
|
+
} }) })) : null, editingKey ? (_jsx(OrganizationApiKeyEditForm, { baseUrl: baseUrl, keyData: editingKey, permissions: permissions, permissionLabels: permissionLabels, messages: {
|
|
1611
1686
|
enabled: m.user_api_key_enabled(),
|
|
1612
1687
|
name: m.user_api_key_name(),
|
|
1613
1688
|
referrers: m.user_api_key_referrers(),
|
|
@@ -1622,6 +1697,76 @@ function OrganizationApiKeyManager({ authClient, organization, active, permissio
|
|
|
1622
1697
|
setEditingKey(null);
|
|
1623
1698
|
} }, editingKey.id)) : null] })] }));
|
|
1624
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
|
+
}
|
|
1625
1770
|
const apiKeyColumns = ({ m, }) => [
|
|
1626
1771
|
{
|
|
1627
1772
|
accessorKey: "name",
|