Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 44 additions & 0 deletions src/features/user-management/api/create-user.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import { api } from "@/lib/api-client"
import type { MutationConfig } from "@/lib/react-query"
import type { UserCreateInput, UserCreateResult } from "@/types/api"
import { useMutation, useQueryClient } from "@tanstack/react-query"
import z from "zod"
import { getUsersQueryOptions } from "./get-users"

export const createUserInputSchema = z.object({
email: z.string().email("Invalid email address"),
first_name: z.string().min(1, "First name is required"),
last_name: z.string().min(1, "Last name is required"),
role: z.enum(["system_admin", "admin", "operator"]),
}) satisfies z.ZodType<UserCreateInput>

export const createUser = ({
data,
}: {
data: UserCreateInput
}): Promise<UserCreateResult> => {
return api.post("/api/users/", data)
}

type UseCreateUserOptions = {
mutationConfig?: MutationConfig<typeof createUser>
}

export const useCreateUser = ({
mutationConfig,
}: UseCreateUserOptions = {}) => {
const queryClient = useQueryClient()

const { onSuccess, ...restConfig } = mutationConfig || {}

return useMutation({
onSuccess: (...args) => {
queryClient.invalidateQueries({
queryKey: getUsersQueryOptions().queryKey,
})
onSuccess?.(...args)
},
...restConfig,
mutationFn: createUser,
})
}
30 changes: 30 additions & 0 deletions src/features/user-management/api/get-users.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { keepPreviousData, queryOptions, useQuery } from "@tanstack/react-query"
import { api } from "@/lib/api-client"
import type { QueryConfig } from "@/lib/react-query"
import type { UserQuery, UserPage } from "@/types/api"

export const getUsers = (params: UserQuery = {}): Promise<UserPage> => {
return api.get("/api/users/", {
params,
})
}

export const getUsersQueryOptions = (params: UserQuery = {}) => {
return queryOptions({
queryKey: ["users", params],
queryFn: () => getUsers(params),
})
}

type UseUsersOptions = {
params?: UserQuery
queryConfig?: QueryConfig<typeof getUsersQueryOptions>
}

export const useUsers = ({ params, queryConfig }: UseUsersOptions = {}) => {
return useQuery({
...getUsersQueryOptions(params),
...queryConfig,
placeholderData: keepPreviousData,
})
}
151 changes: 32 additions & 119 deletions src/features/user-management/components/add-user-dialog.tsx
Original file line number Diff line number Diff line change
@@ -1,134 +1,47 @@
import { useState } from "react"
import { Button } from "@/components/ui/button"
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog"
import { Field, FieldLabel, FieldGroup } from "@/components/ui/field"
import { Input } from "@/components/ui/input"
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select"
import { Dialog, DialogContent, DialogTrigger } from "@/components/ui/dialog"
import { Plus } from "lucide-react"
import type { UserRole } from "../types"
import type z from "zod"
import { useCreateUser, createUserInputSchema } from "../api/create-user"
import { useState } from "react"
import { AddUserForm } from "./add-user-form"

export function AddUserDialog() {
const [open, setOpen] = useState(false)
const [role, setRole] = useState<UserRole | "">("")

const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault()

const formData = new FormData(e.currentTarget)
const userData = {
firstName: formData.get("firstName") as string,
lastName: formData.get("lastName") as string,
email: formData.get("email") as string,
role: role,
}

// TODO: Add new user to table data
console.log("New user data:", userData)

setOpen(false)
e.currentTarget.reset()
setRole("")
}

const handleOpenChange = (newOpen: boolean) => {
setOpen(newOpen)
if (!newOpen) {
setRole("")
}
const createUserMutation = useCreateUser()

function onSubmit(data: z.infer<typeof createUserInputSchema>) {
createUserMutation.mutate(
{ data },
{
onSuccess: () => {
setOpen(false)
// TODO: Show success toast/notification
},
}
)
}

return (
<Dialog open={open} onOpenChange={handleOpenChange}>
<Dialog
open={open}
onOpenChange={(next, eventDetails) => {
if (!next && createUserMutation.isPending) {
eventDetails.cancel()
return
}
setOpen(next)
}}
>
<DialogTrigger render={<Button />}>
<Plus />
Add User
</DialogTrigger>
<DialogContent className="sm:max-w-[425px]">
<form onSubmit={handleSubmit}>
<DialogHeader>
<DialogTitle>Add New User</DialogTitle>
<DialogDescription>
Fill in the details to create a new user account.
</DialogDescription>
</DialogHeader>

<FieldGroup className="py-4">
<Field>
<FieldLabel htmlFor="firstName">First Name</FieldLabel>
<Input
id="firstName"
name="firstName"
type="text"
placeholder="Enter first name"
required
/>
</Field>

<Field>
<FieldLabel htmlFor="lastName">Last Name</FieldLabel>
<Input
id="lastName"
name="lastName"
type="text"
placeholder="Enter last name"
required
/>
</Field>

<Field>
<FieldLabel htmlFor="email">Email</FieldLabel>
<Input
id="email"
name="email"
type="email"
placeholder="Enter email address"
required
/>
</Field>

<Field>
<FieldLabel htmlFor="role">Role</FieldLabel>
<Select
value={role}
onValueChange={(value) => setRole(value as UserRole)}
required
>
<SelectTrigger id="role" className="w-full">
<SelectValue placeholder="Select a role" />
</SelectTrigger>
<SelectContent>
<SelectItem value="Admin">Admin</SelectItem>
<SelectItem value="Operator">Operator</SelectItem>
</SelectContent>
</Select>
</Field>
</FieldGroup>

<DialogFooter>
<Button
type="button"
variant="outline"
onClick={() => setOpen(false)}
>
Cancel
</Button>
<Button type="submit">Add User</Button>
</DialogFooter>
</form>
<DialogContent>
<AddUserForm
onSubmit={onSubmit}
isPending={createUserMutation.isPending}
/>
</DialogContent>
</Dialog>
)
Expand Down
Loading