'use client'; import { useEffect, useState } from 'react'; import { zodResolver } from '@hookform/resolvers/zod'; import type * as DialogPrimitive from '@radix-ui/react-dialog'; import { useForm } from 'react-hook-form'; import { z } from 'zod'; import { TEAM_MEMBER_ROLE_HIERARCHY, TEAM_MEMBER_ROLE_MAP } from '@documenso/lib/constants/teams'; import { isTeamRoleWithinUserHierarchy } from '@documenso/lib/utils/teams'; import { TeamMemberRole } from '@documenso/prisma/client'; import { trpc } from '@documenso/trpc/react'; import { Button } from '@documenso/ui/primitives/button'; import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, DialogTrigger, } from '@documenso/ui/primitives/dialog'; import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage, } from '@documenso/ui/primitives/form/form'; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from '@documenso/ui/primitives/select'; import { useToast } from '@documenso/ui/primitives/use-toast'; export type UpdateTeamMemberDialogProps = { currentUserTeamRole: TeamMemberRole; trigger?: React.ReactNode; teamId: number; teamMemberId: number; teamMemberName: string; teamMemberRole: TeamMemberRole; } & Omit; const ZUpdateTeamMemberFormSchema = z.object({ role: z.nativeEnum(TeamMemberRole), }); type ZUpdateTeamMemberSchema = z.infer; export const UpdateTeamMemberDialog = ({ currentUserTeamRole, trigger, teamId, teamMemberId, teamMemberName, teamMemberRole, ...props }: UpdateTeamMemberDialogProps) => { const [open, setOpen] = useState(false); const { toast } = useToast(); const form = useForm({ resolver: zodResolver(ZUpdateTeamMemberFormSchema), defaultValues: { role: teamMemberRole, }, }); const { mutateAsync: updateTeamMember } = trpc.team.updateTeamMember.useMutation(); const onFormSubmit = async ({ role }: ZUpdateTeamMemberSchema) => { try { await updateTeamMember({ teamId, teamMemberId, data: { role, }, }); toast({ title: 'Success', description: `You have updated ${teamMemberName}.`, duration: 5000, }); setOpen(false); } catch { toast({ title: 'An unknown error occurred', variant: 'destructive', description: 'We encountered an unknown error while attempting to update this team member. Please try again later.', }); } }; useEffect(() => { if (!open) { return; } form.reset(); if (!isTeamRoleWithinUserHierarchy(currentUserTeamRole, teamMemberRole)) { setOpen(false); toast({ title: 'You cannot modify a team member who has a higher role than you.', variant: 'destructive', }); } }, [open, currentUserTeamRole, teamMemberRole, form, toast]); return ( !form.formState.isSubmitting && setOpen(value)} > e.stopPropagation()} asChild> {trigger ?? } Update team member You are currently updating {teamMemberName}.
( Role )} />
); };