hook up role

This commit is contained in:
Alex Holliday committed 2026-02-09 20:38:04 +00:00
1 parent 4434189c72
commit ece6970fa7
4 files changed
+188 -99

No files matched your search

+13
View File
@@ -0,0 +1,13 @@
import { zodResolver } from "@hookform/resolvers/zod";
import { editUserSchema, type EditUserFormData } from "@/Validation/editUser";
export const useEditUserForm = () => {
return {
resolver: zodResolver(editUserSchema),
defaults: {
firstName: "",
lastName: "",
role: [],
} as EditUserFormData,
};
};
+156 -97
View File
@@ -1,122 +1,181 @@
import { Stack, Typography, IconButton, Divider } from "@mui/material";
import { useTheme } from "@mui/material";
import { useTranslation } from "react-i18next";
import { ConfigBox, BasePage, Breadcrumb } from "@/Components/v2/design-elements";
import { TextField, Button, Autocomplete } from "@/Components/v2/inputs";
import { UserRoles } from "@/Types/User";
import { useState } from "react";
import { Trash2 } from "lucide-react"; import { Trash2 } from "lucide-react";
import { TextField, Button, Autocomplete } from "@/Components/v2/inputs";
import Stack from "@mui/material/Stack";
import Typography from "@mui/material/Typography";
import IconButton from "@mui/material/IconButton";
import Divider from "@mui/material/Divider";
import FormHelperText from "@mui/material/FormHelperText";
import { useForm, Controller } from "react-hook-form";
import { ConfigBox, BasePage } from "@/Components/v2/design-elements";
import { UserRoles } from "@/Types/User";
import { useTranslation } from "react-i18next";
import type { UserRole, User } from "@/Types/User";
import { useParams } from "react-router-dom";
import { useTheme } from "@mui/material";
import { useEditUserForm } from "@/Hooks/useEditUserForm";
import { useGet, usePatch } from "@/Hooks/UseApi";
import type { EditUserFormData } from "@/Validation/editUser";
import { useEffect } from "react";
interface RoleOption { interface RoleOption {
id: string; id: UserRole;
name: string; name: string;
} }
const EditUserPage = () => { const EditUserPage = () => {
const theme = useTheme(); const theme = useTheme();
const { t } = useTranslation(); const { t } = useTranslation();
const { userId } = useParams<{ userId: string }>();
const { resolver, defaults } = useEditUserForm();
const { patch, loading: isSaving } = usePatch();
const [firstName, setFirstName] = useState(""); const { data: user, isLoading } = useGet<User>(`/auth/users/${userId}`);
const [lastName, setLastName] = useState("");
const [email] = useState(""); const { control, handleSubmit, reset, watch, setValue } = useForm<EditUserFormData>({
const [roles, setRoles] = useState<string[]>([]); resolver,
defaultValues: defaults,
});
useEffect(() => {
if (user) {
reset({
firstName: user.firstName || "",
lastName: user.lastName || "",
role: user.role || [],
});
}
}, [user, reset]);
const editableRoles = UserRoles.filter((role) => role !== "superadmin"); const editableRoles = UserRoles.filter((role) => role !== "superadmin");
const roleOptions: RoleOption[] = editableRoles.map((role) => ({ const roleOptions: RoleOption[] = editableRoles.map((role) => ({
id: role, id: role,
name: t(`common.auth.roles.${role}`), name: t(`common.auth.roles.${role}`),
})); }));
const selectedRoles = roleOptions.filter((r) => roles.includes(r.id)); const watchedRoles = watch("role");
const selectedRoles = roleOptions.filter((r) => watchedRoles?.includes(r.id));
const handleRemoveRole = (roleToRemove: UserRole) => {
const newRoles = watchedRoles.filter((role) => role !== roleToRemove);
setValue("role", newRoles, { shouldValidate: true });
};
const handleRemoveRole = (roleToRemove: string) => { const onSubmit = async (data: EditUserFormData) => {
setRoles(roles.filter((role) => role !== roleToRemove)); await patch(`/auth/users/${userId}`, data);
}; };
return ( return (
<BasePage> <BasePage loading={isLoading}>
<Stack gap={theme.spacing(8)}> <form onSubmit={handleSubmit(onSubmit)}>
<ConfigBox <Stack gap={theme.spacing(8)}>
title={t("pages.account.form.name.title")} <ConfigBox
subtitle={t("pages.account.form.name.description")} title={t("pages.account.form.name.title")}
rightContent={ subtitle={t("pages.account.form.name.description")}
<Stack gap={theme.spacing(8)}> rightContent={
<TextField <Stack gap={theme.spacing(8)}>
fieldLabel={t("common.form.name.option.firstName.label")} <Controller
placeholder={t("common.form.name.option.firstName.placeholder")} name="firstName"
value={firstName} control={control}
onChange={(e) => setFirstName(e.target.value)} render={({ field, fieldState }) => (
autoComplete="given-name" <TextField
/> {...field}
<TextField fieldLabel={t("common.form.name.option.firstName.label")}
fieldLabel={t("common.form.name.option.lastName.label")} placeholder={t("common.form.name.option.firstName.placeholder")}
placeholder={t("common.form.name.option.lastName.placeholder")} error={!!fieldState.error}
value={lastName} helperText={fieldState.error?.message}
onChange={(e) => setLastName(e.target.value)} autoComplete="given-name"
autoComplete="family-name" />
/> )}
<TextField />
fieldLabel={t("common.form.email.option.email.label")} <Controller
placeholder={t("common.form.email.option.email.placeholder")} name="lastName"
value={email} control={control}
disabled render={({ field, fieldState }) => (
/> <TextField
</Stack> {...field}
} fieldLabel={t("common.form.name.option.lastName.label")}
/> placeholder={t("common.form.name.option.lastName.placeholder")}
<ConfigBox error={!!fieldState.error}
title={t("pages.editUser.form.roles.title")} helperText={fieldState.error?.message}
subtitle={t("pages.editUser.form.roles.description")} autoComplete="family-name"
rightContent={ />
<Stack spacing={theme.spacing(4)}> )}
<Autocomplete />
fieldLabel={t("common.form.role.option.role.label")} <TextField
multiple fieldLabel={t("common.form.email.option.email.label")}
options={roleOptions} placeholder={t("common.form.email.option.email.placeholder")}
value={selectedRoles} value={user?.email || ""}
getOptionLabel={(option) => option.name} disabled
onChange={(_: unknown, newValue: RoleOption[]) => { />
setRoles(newValue.map((r) => r.id)); </Stack>
}} }
isOptionEqualToValue={(option, value) => option.id === value.id} />
/> <ConfigBox
{selectedRoles.length > 0 && ( title={t("pages.editUser.form.roles.title")}
<Stack subtitle={t("pages.editUser.form.roles.description")}
flex={1} rightContent={
width="100%" <Stack spacing={theme.spacing(4)}>
> <Controller
{selectedRoles.map((role, index) => ( name="role"
<Stack control={control}
direction="row" render={({ field, fieldState }) => (
alignItems="center" <>
key={role.id} <Autocomplete
width="100%" fieldLabel={t("common.form.role.option.role.label")}
> multiple
<Typography flexGrow={1}>{role.name}</Typography> options={roleOptions}
<IconButton value={selectedRoles}
size="small" getOptionLabel={(option) => option.name}
onClick={() => handleRemoveRole(role.id)} onChange={(_: unknown, newValue: RoleOption[]) => {
aria-label="Remove role" field.onChange(newValue.map((r) => r.id));
}}
isOptionEqualToValue={(option, value) => option.id === value.id}
/>
{fieldState.error && (
<FormHelperText error>{fieldState.error.message}</FormHelperText>
)}
</>
)}
/>
{selectedRoles.length > 0 && (
<Stack
flex={1}
width="100%"
>
{selectedRoles.map((role, index) => (
<Stack
direction="row"
alignItems="center"
key={role.id}
width="100%"
> >
<Trash2 size={16} /> <Typography flexGrow={1}>{role.name}</Typography>
</IconButton> <IconButton
{index < selectedRoles.length - 1 && <Divider />} size="small"
</Stack> onClick={() => handleRemoveRole(role.id)}
))} aria-label="Remove role"
</Stack> >
)} <Trash2 size={16} />
</Stack> </IconButton>
} {index < selectedRoles.length - 1 && <Divider />}
/> </Stack>
<Button ))}
variant="contained" </Stack>
color="primary" )}
sx={{ alignSelf: "flex-end", minWidth: 100 }} </Stack>
> }
{t("common.buttons.save")} />
</Button> <Button
</Stack> type="submit"
variant="contained"
color="primary"
loading={isSaving}
sx={{ alignSelf: "flex-end", minWidth: 100 }}
>
{t("common.buttons.save")}
</Button>
</Stack>
</form>
</BasePage> </BasePage>
); );
}; };
+19
View File
@@ -0,0 +1,19 @@
import { z } from "zod";
import { namePattern } from "@/Validation/patterns";
import { UserRoles } from "@/Types/User";
export const editUserSchema = z.object({
firstName: z
.string()
.min(1, "First name is required")
.max(50, "First name must be 50 characters or less")
.regex(namePattern, "First name contains invalid characters"),
lastName: z
.string()
.min(1, "Last name is required")
.max(50, "Last name must be 50 characters or less")
.regex(namePattern, "Last name contains invalid characters"),
role: z.array(z.enum(UserRoles)).min(1, "At least one role is required"),
});
export type EditUserFormData = z.infer<typeof editUserSchema>;
-2
View File
@@ -689,7 +689,6 @@ const editUserByIdParamValidation = joi.object({
const editUserByIdBodyValidation = joi.object({ const editUserByIdBodyValidation = joi.object({
firstName: nameValidation.required(), firstName: nameValidation.required(),
lastName: nameValidation.required(), lastName: nameValidation.required(),
email: joi.string().email().required(),
role: joi role: joi
.array() .array()
.items(joi.string().valid(...UserRoles)) .items(joi.string().valid(...UserRoles))
@@ -700,7 +699,6 @@ const editUserByIdBodyValidation = joi.object({
const editSuperadminUserByIdBodyValidation = joi.object({ const editSuperadminUserByIdBodyValidation = joi.object({
firstName: nameValidation.required(), firstName: nameValidation.required(),
lastName: nameValidation.required(), lastName: nameValidation.required(),
email: joi.string().email().required(),
role: joi role: joi
.array() .array()
.items(joi.string().valid(...UserRoles)) .items(joi.string().valid(...UserRoles))