import { zodResolver } from "@hookform/resolvers/zod" import { useMutation, useQueryClient } from "@tanstack/react-query" import { Plus } from "lucide-react" import { useState } from "react" import { useForm } from "react-hook-form" import { z } from "zod" import { type UserCreate, UsersService } from "@/client" import { Button } from "@/components/ui/button" import { Checkbox } from "@/components/ui/checkbox" import { Dialog, DialogClose, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, DialogTrigger, } from "@/components/ui/dialog" import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage, } from "@/components/ui/form" import { Input } from "@/components/ui/input" import { LoadingButton } from "@/components/ui/loading-button" import useCustomToast from "@/hooks/useCustomToast" import { handleError } from "@/utils" const formSchema = z .object({ email: z.email({ message: "Invalid email address" }), full_name: z.string().optional(), password: z .string() .min(1, { message: "Password is required" }) .min(8, { message: "Password must be at least 8 characters" }), confirm_password: z .string() .min(1, { message: "Please confirm your password" }), is_superuser: z.boolean(), is_active: z.boolean(), }) .refine((data) => data.password === data.confirm_password, { message: "The passwords don't match", path: ["confirm_password"], }) type FormData = z.infer const AddUser = () => { const [isOpen, setIsOpen] = useState(false) const queryClient = useQueryClient() const { showSuccessToast, showErrorToast } = useCustomToast() const form = useForm({ resolver: zodResolver(formSchema), mode: "onBlur", criteriaMode: "all", defaultValues: { email: "", full_name: "", password: "", confirm_password: "", is_superuser: false, is_active: false, }, }) const mutation = useMutation({ mutationFn: (data: UserCreate) => UsersService.createUser({ requestBody: data }), onSuccess: () => { showSuccessToast("User created successfully") form.reset() setIsOpen(false) }, onError: handleError.bind(showErrorToast), onSettled: () => { queryClient.invalidateQueries({ queryKey: ["users"] }) }, }) const onSubmit = (data: FormData) => { mutation.mutate(data) } return ( Add User Fill in the form below to add a new user to the system.
( Email * )} /> ( Full Name )} /> ( Set Password * )} /> ( Confirm Password{" "} * )} /> ( Is superuser? )} /> ( Is active? )} />
Save
) } export default AddUser