import { useEffect, useState } from "react"; import { Controller, useForm } from "react-hook-form"; import { zodResolver } from "@hookform/resolvers/zod"; import { z } from "zod"; import { createNotification } from "@app/components/notifications"; import { OrgPermissionCan } from "@app/components/permissions"; import { Button, FormControl, Input, Select, SelectItem, Spinner } from "@app/components/v2"; import { OrgPermissionActions, OrgPermissionSubjects, useOrganization, useOrgPermission } from "@app/context"; import { isCustomOrgRole } from "@app/helpers/roles"; import { useGetOrgRoles, useUpdateOrg } from "@app/hooks/api"; const formSchema = z.object({ name: z.string().max(64, "Too long, maximum length is 64 characters"), slug: z .string() .regex(/^[a-zA-Z0-9-]+$/, "Name must only contain alphanumeric characters or hyphens"), defaultMembershipRole: z.string() }); type FormData = z.infer; export const OrgNameChangeSection = (): JSX.Element => { const { currentOrg } = useOrganization(); const { permission } = useOrgPermission(); const { handleSubmit, control, reset } = useForm({ resolver: zodResolver(formSchema) }); const { mutateAsync, isPending } = useUpdateOrg(); const canReadOrgRoles = permission.can(OrgPermissionActions.Read, OrgPermissionSubjects.Role); const { data: roles, isPending: isRolesLoading } = useGetOrgRoles(currentOrg.id, canReadOrgRoles); const [isFormInitialized, setIsFormInitialized] = useState(false); useEffect(() => { if (currentOrg) { reset({ name: currentOrg.name, slug: currentOrg.slug, ...(canReadOrgRoles && roles?.length && { // will always be present, can't remove role if default defaultMembershipRole: isCustomOrgRole(currentOrg.defaultMembershipRole) ? roles?.find((role) => currentOrg.defaultMembershipRole === role.id)?.slug || "" : currentOrg.defaultMembershipRole }) }); setIsFormInitialized(true); } }, [currentOrg, roles]); const onFormSubmit = async ({ name, slug, defaultMembershipRole }: FormData) => { try { if (!currentOrg?.id || !roles?.length) return; await mutateAsync({ orgId: currentOrg?.id, name, slug, defaultMembershipRoleSlug: defaultMembershipRole }); createNotification({ text: "Successfully updated organization details", type: "success" }); } catch (error) { console.error(error); createNotification({ text: "Failed to update organization details", type: "error" }); } }; if (!isFormInitialized) { return (
); } return (

Organization Name

( )} control={control} name="name" />

Organization Slug

( )} control={control} name="slug" />
{canReadOrgRoles && (

Default Organization Member Role

( )} />

)} {(isAllowed) => ( )}
); };