import { standardSchemaResolver as zodResolver } from "@hookform/resolvers/standard-schema"; import { useEffect, useState } from "react"; import { useForm } from "react-hook-form"; import { toast } from "sonner"; import { z } from "zod"; import { AlertBlock } from "@/components/shared/alert-block"; import { Button } from "@/components/ui/button"; import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, DialogTrigger, } from "@/components/ui/dialog"; import { DropdownMenuItem } from "@/components/ui/dropdown-menu"; import { Form, FormControl, FormDescription, FormField, FormItem, FormLabel, FormMessage, } from "@/components/ui/form"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from "@/components/ui/select"; import { api } from "@/utils/api"; const changeRoleSchema = z.object({ role: z.string().min(1), }); type ChangeRoleSchema = z.infer; interface Props { memberId: string; currentRole: string; userEmail: string; } export const ChangeRole = ({ memberId, currentRole, userEmail }: Props) => { const [isOpen, setIsOpen] = useState(false); const utils = api.useUtils(); const { data: customRoles } = api.customRole.all.useQuery(undefined, { enabled: isOpen, }); const { mutateAsync, isError, error, isPending } = api.organization.updateMemberRole.useMutation(); const form = useForm({ defaultValues: { role: currentRole, }, resolver: zodResolver(changeRoleSchema), }); useEffect(() => { if (isOpen) { form.reset({ role: currentRole, }); } }, [form, currentRole, isOpen]); const onSubmit = async (data: ChangeRoleSchema) => { await mutateAsync({ memberId, role: data.role, }) .then(async () => { toast.success("Role updated successfully"); await utils.user.all.invalidate(); setIsOpen(false); }) .catch((error) => { toast.error(error?.message || "Error updating role"); }); }; return ( e.preventDefault()} > Change Role Change User Role Change the role for {userEmail} {isError && {error?.message}}
( Role Admin: Can manage users and settings.
Member: Limited permissions, can be customized. {customRoles && customRoles.length > 0 && ( <>
Custom roles: Enterprise-defined permissions. )}
Note: Owner role is nontransferable.
)} />
); };