refactor(frontend): update inviteUser dialog

This commit is contained in:
yassinedorbozgithub 2025-02-07 06:25:15 +01:00
parent c972626a78
commit 6efc305244
8 changed files with 187 additions and 176 deletions

View File

@ -13,7 +13,12 @@ import { Button, Grid } from "@mui/material";
import { useTranslate } from "@/hooks/useTranslate";
import { FormButtonsProps } from "@/types/common/dialogs.types";
export const DialogFormButtons = ({ onCancel, onSubmit }: FormButtonsProps) => {
export const DialogFormButtons = ({
onSubmit,
onCancel,
cancelButtonProps,
confirmButtonProps,
}: FormButtonsProps) => {
const { t } = useTranslate();
return (
@ -28,6 +33,7 @@ export const DialogFormButtons = ({ onCancel, onSubmit }: FormButtonsProps) => {
variant="outlined"
onClick={onCancel}
startIcon={<CloseIcon />}
{...cancelButtonProps}
>
{t("button.cancel")}
</Button>
@ -36,6 +42,7 @@ export const DialogFormButtons = ({ onCancel, onSubmit }: FormButtonsProps) => {
variant="contained"
onClick={onSubmit}
startIcon={<CheckIcon />}
{...confirmButtonProps}
>
{t("button.submit")}
</Button>

View File

@ -17,16 +17,20 @@ export const FormDialog = ({
title,
children,
onSubmit,
cancelButtonProps,
confirmButtonProps,
...rest
}: FormDialogProps) => {
const handleClose = () => rest.onClose?.({}, "backdropClick");
const onCancel = () => rest.onClose?.({}, "backdropClick");
return (
<Dialog fullWidth {...rest}>
<DialogTitle onClose={handleClose}>{title}</DialogTitle>
<DialogTitle onClose={onCancel}>{title}</DialogTitle>
<DialogContent>{children}</DialogContent>
<DialogActions style={{ padding: "0.5rem" }}>
<DialogFormButtons onCancel={handleClose} onSubmit={onSubmit} />
<DialogFormButtons
{...{ onSubmit, onCancel, confirmButtonProps, cancelButtonProps }}
/>
</DialogActions>
</Dialog>
);

View File

@ -1,144 +0,0 @@
/*
* Copyright © 2024 Hexastack. All rights reserved.
*
* Licensed under the GNU Affero General Public License v3.0 (AGPLv3) with the following additional terms:
* 1. The name "Hexabot" is a trademark of Hexastack. You may not use this name in derivative works without express written permission.
* 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file).
*/
import CloseIcon from "@mui/icons-material/Close";
import SendIcon from "@mui/icons-material/Send";
import { Button, Dialog, DialogActions, DialogContent } from "@mui/material";
import { FC, useEffect } from "react";
import { Controller, useForm } from "react-hook-form";
import { DialogTitle } from "@/app-components/dialogs/DialogTitle";
import { ContentContainer } from "@/app-components/dialogs/layouts/ContentContainer";
import { ContentItem } from "@/app-components/dialogs/layouts/ContentItem";
import AutoCompleteEntitySelect from "@/app-components/inputs/AutoCompleteEntitySelect";
import { Input } from "@/app-components/inputs/Input";
import { useSendInvitation } from "@/hooks/entities/invitation-hooks";
import { DialogControlProps } from "@/hooks/useDialog";
import { useToast } from "@/hooks/useToast";
import { useTranslate } from "@/hooks/useTranslate";
import { useValidationRules } from "@/hooks/useValidationRules";
import { EntityType, Format } from "@/services/types";
import { IInvitationAttributes } from "@/types/invitation.types";
import { IRole } from "@/types/role.types";
const DEFAULT_VALUES: IInvitationAttributes = { email: "", roles: [] };
export type InvitationDialogProps = DialogControlProps<IRole[]>;
export const InvitationDialog: FC<InvitationDialogProps> = ({
open,
closeDialog,
...rest
}) => {
const { t } = useTranslate();
const { toast } = useToast();
const { mutateAsync: sendInvitation } = useSendInvitation({
onSuccess: () => {
closeDialog();
toast.success(t("message.success_invitation_sent"));
},
onError: () => {
toast.error(t("message.internal_server_error"));
},
});
const {
handleSubmit,
reset,
register,
control,
formState: { errors },
} = useForm<IInvitationAttributes>({
defaultValues: DEFAULT_VALUES,
});
const rules = useValidationRules();
const validationRules = {
email: {
...rules.email,
required: t("message.email_is_required"),
},
roles: {
required: t("message.roles_is_required"),
},
};
const onSubmitForm = async (params: IInvitationAttributes) => {
sendInvitation(params);
};
useEffect(() => {
if (open) reset(DEFAULT_VALUES);
}, [open, reset]);
return (
<Dialog open={open} fullWidth onClose={closeDialog} {...rest}>
<form onSubmit={handleSubmit(onSubmitForm)}>
<DialogTitle onClose={closeDialog}>
{t("title.invite_new_user")}
</DialogTitle>
<DialogContent>
<ContentContainer>
<ContentItem>
<Input
label={t("placeholder.email")}
error={!!errors.email}
required
autoFocus
{...register("email", validationRules.email)}
helperText={errors.email ? errors.email.message : null}
/>
</ContentItem>
<ContentItem>
<Controller
name="roles"
rules={validationRules.roles}
control={control}
render={({ field }) => {
const { onChange, ...rest } = field;
return (
<AutoCompleteEntitySelect<IRole>
autoFocus
searchFields={["name"]}
entity={EntityType.ROLE}
format={Format.BASIC}
labelKey="name"
label={t("label.roles")}
multiple={true}
{...field}
error={!!errors.roles}
helperText={errors.roles ? errors.roles.message : null}
onChange={(_e, selected) =>
onChange(selected.map(({ id }) => id))
}
{...rest}
/>
);
}}
/>
</ContentItem>
</ContentContainer>
</DialogContent>
<DialogActions>
<Button
startIcon={<SendIcon />}
variant="contained"
type="submit"
onClick={handleSubmit(onSubmitForm)}
>
{t("button.send")}
</Button>
<Button
startIcon={<CloseIcon />}
variant="outlined"
onClick={closeDialog}
>
{t("button.cancel")}
</Button>
</DialogActions>
</form>
</Dialog>
);
};

View File

@ -0,0 +1,116 @@
/*
* Copyright © 2025 Hexastack. All rights reserved.
*
* Licensed under the GNU Affero General Public License v3.0 (AGPLv3) with the following additional terms:
* 1. The name "Hexabot" is a trademark of Hexastack. You may not use this name in derivative works without express written permission.
* 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file).
*/
import { FC, Fragment } from "react";
import { Controller, useForm } from "react-hook-form";
import { ContentContainer, ContentItem } from "@/app-components/dialogs/";
import AutoCompleteEntitySelect from "@/app-components/inputs/AutoCompleteEntitySelect";
import { Input } from "@/app-components/inputs/Input";
import { useSendInvitation } from "@/hooks/entities/invitation-hooks";
import { useToast } from "@/hooks/useToast";
import { useTranslate } from "@/hooks/useTranslate";
import { useValidationRules } from "@/hooks/useValidationRules";
import { EntityType, Format } from "@/services/types";
import { ComponentFormProps } from "@/types/common/dialogs.types";
import { IInvitationAttributes } from "@/types/invitation.types";
import { IRole } from "@/types/role.types";
const DEFAULT_VALUES: IInvitationAttributes = { email: "", roles: [] };
export const InviteUserForm: FC<ComponentFormProps<undefined>> = ({
Wrapper = Fragment,
WrapperProps,
...rest
}) => {
const { t } = useTranslate();
const { toast } = useToast();
const { mutateAsync: sendInvitation } = useSendInvitation({
onSuccess: () => {
rest.onSuccess?.();
toast.success(t("message.success_invitation_sent"));
},
onError: () => {
rest.onError?.();
toast.error(t("message.internal_server_error"));
},
});
const {
control,
register,
formState: { errors },
handleSubmit,
} = useForm<IInvitationAttributes>({
defaultValues: DEFAULT_VALUES,
});
const rules = useValidationRules();
const validationRules = {
email: {
...rules.email,
required: t("message.email_is_required"),
},
roles: {
required: t("message.roles_is_required"),
},
};
const onSubmitForm = async (params: IInvitationAttributes) => {
sendInvitation(params);
};
return (
<Wrapper
open={!!WrapperProps?.open}
onSubmit={handleSubmit(onSubmitForm)}
{...WrapperProps}
>
<form onSubmit={handleSubmit(onSubmitForm)}>
<ContentContainer>
<ContentItem>
<Input
label={t("placeholder.email")}
error={!!errors.email}
required
autoFocus
{...register("email", validationRules.email)}
helperText={errors.email ? errors.email.message : null}
/>
</ContentItem>
<ContentItem>
<Controller
name="roles"
rules={validationRules.roles}
control={control}
render={({ field }) => {
const { onChange, ...rest } = field;
return (
<AutoCompleteEntitySelect<IRole>
autoFocus
searchFields={["name"]}
entity={EntityType.ROLE}
format={Format.BASIC}
labelKey="name"
label={t("label.roles")}
multiple={true}
{...field}
error={!!errors.roles}
helperText={errors.roles ? errors.roles.message : null}
onChange={(_e, selected) =>
onChange(selected.map(({ id }) => id))
}
{...rest}
/>
);
}}
/>
</ContentItem>
</ContentContainer>
</form>
</Wrapper>
);
};

View File

@ -0,0 +1,25 @@
/*
* Copyright © 2025 Hexastack. All rights reserved.
*
* Licensed under the GNU Affero General Public License v3.0 (AGPLv3) with the following additional terms:
* 1. The name "Hexabot" is a trademark of Hexastack. You may not use this name in derivative works without express written permission.
* 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file).
*/
import SendIcon from "@mui/icons-material/Send";
import { GenericFormDialog } from "@/app-components/dialogs";
import { ComponentFormDialogProps } from "@/types/common/dialogs.types";
import { InviteUserForm } from "./InviteUserForm";
export const InviteUserFormFormDialog = <T extends undefined = undefined>(
props: ComponentFormDialogProps<T>,
) => (
<GenericFormDialog<T>
Form={InviteUserForm}
addText="title.invite_new_user"
confirmButtonProps={{ startIcon: <SendIcon /> }}
{...props}
/>
);

View File

@ -24,7 +24,7 @@ import { useFind } from "@/hooks/crud/useFind";
import { useUpdate } from "@/hooks/crud/useUpdate";
import { useAuth } from "@/hooks/useAuth";
import { useConfig } from "@/hooks/useConfig";
import { getDisplayDialogs, useDialog } from "@/hooks/useDialog";
import { useDialogs } from "@/hooks/useDialogs";
import { useHasPermission } from "@/hooks/useHasPermission";
import { useSearch } from "@/hooks/useSearch";
import { useToast } from "@/hooks/useToast";
@ -32,19 +32,19 @@ import { useTranslate } from "@/hooks/useTranslate";
import { PageHeader } from "@/layout/content/PageHeader";
import { EntityType, Format } from "@/services/types";
import { PermissionAction } from "@/types/permission.types";
import { IRole } from "@/types/role.types";
import { IUser } from "@/types/user.types";
import { getDateTimeFormatter } from "@/utils/date";
import { EditUserDialog } from "./EditUserDialog";
import { InvitationDialog } from "./InvitationDialog";
import { CategoryFormDialog } from "./EditUserFormDialog";
import { InviteUserFormFormDialog } from "./InviteUserFormDialog";
export const Users = () => {
const { ssoEnabled } = useConfig();
const { t } = useTranslate();
const { toast } = useToast();
const dialogs = useDialogs();
const { user } = useAuth();
const { mutateAsync: updateUser } = useUpdate(EntityType.USER, {
const { mutate: updateUser } = useUpdate(EntityType.USER, {
onError: (error) => {
toast.error(error.message || t("message.internal_server_error"));
},
@ -52,8 +52,6 @@ export const Users = () => {
toast.success(t("message.success_save"));
},
});
const invitationDialogCtl = useDialog<IRole[]>(false);
const editDialogCtl = useDialog<{ user: IUser; roles: IRole[] }>(false);
const hasPermission = useHasPermission();
const { onSearch, searchPayload } = useSearch<IUser>({
$or: ["first_name", "last_name", "email"],
@ -76,9 +74,9 @@ export const Users = () => {
{
label: ActionColumnLabel.Manage_Roles,
action: (row) =>
editDialogCtl.openDialog({
roles: roles || [],
dialogs.open(CategoryFormDialog, {
user: row,
roles: roles || [],
}),
requires: [PermissionAction.CREATE],
},
@ -151,14 +149,14 @@ export const Users = () => {
ssoEnabled ||
!hasPermission(EntityType.USER, PermissionAction.UPDATE)
}
onChange={() => {
onChange={() =>
updateUser({
id: params.row.id,
params: {
state: !params.row.state,
},
});
}}
})
}
/>
),
},
@ -189,8 +187,6 @@ export const Users = () => {
return (
<Grid container gap={3} flexDirection="column">
<InvitationDialog {...getDisplayDialogs(invitationDialogCtl)} />
<EditUserDialog {...getDisplayDialogs(editDialogCtl)} />
<PageHeader icon={faUsers} title={t("title.users")}>
<Grid
justifyContent="flex-end"
@ -212,9 +208,7 @@ export const Users = () => {
sx={{
float: "right",
}}
onClick={() => {
invitationDialogCtl.openDialog(roles);
}}
onClick={() => dialogs.open(InviteUserFormFormDialog)}
>
{t("button.invite")}
</Button>

View File

@ -137,6 +137,7 @@ function DialogsProvider(props: DialogProviderProps) {
onClose={async (result) => {
await closeDialog(promise, result);
}}
onSubmit={() => {}}
{...msgProps}
/>
))}

View File

@ -6,7 +6,7 @@
* 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file).
*/
import { DialogProps as MuiDialogProps } from "@mui/material";
import { ButtonProps, DialogProps as MuiDialogProps } from "@mui/material";
import { BaseSyntheticEvent } from "react";
interface ConfirmDialogExtraOptions {
@ -24,6 +24,8 @@ export interface OpenDialogOptions<R> extends ConfirmDialogExtraOptions {
* @returns A promise that resolves when the dialog can be closed.
*/
onClose?: (result: R) => Promise<void>;
onSubmit?: (e: BaseSyntheticEvent) => void;
}
/**
@ -47,6 +49,8 @@ export interface DialogProps<P = undefined, R = void> {
* @returns A promise that resolves when the dialog can be fully closed.
*/
onClose: (result: R) => Promise<void>;
onSubmit: (e: BaseSyntheticEvent) => void;
}
export type DialogComponent<P, R> = React.ComponentType<DialogProps<P, R>>;
@ -142,24 +146,28 @@ export interface DialogProviderProps {
}
// form dialog
export interface FormDialogProps extends MuiDialogProps {
export interface FormDialogProps
extends FormButtonsProps,
Omit<MuiDialogProps, "onSubmit"> {
title?: string;
children?: React.ReactNode;
onSubmit: (e: BaseSyntheticEvent) => void;
}
// form
export type ComponentFormProps<T> = {
export interface FormButtonsProps {
onSubmit: (e: BaseSyntheticEvent) => void;
onCancel?: () => void;
cancelButtonProps?: ButtonProps;
confirmButtonProps?: ButtonProps;
}
export type ComponentFormProps<T> = FormButtonsProps & {
data: T | null;
onError?: () => void;
onSuccess?: () => void;
Wrapper?: React.FC<FormDialogProps>;
WrapperProps?: Partial<FormDialogProps>;
WrapperProps?: Partial<FormDialogProps> & Partial<FormButtonsProps>;
};
export interface FormButtonsProps {
onCancel?: () => void;
onSubmit: (e: BaseSyntheticEvent) => void;
}
export type ComponentFormDialogProps<T> = DialogProps<T | null, boolean>;
export type ComponentFormDialogProps<T> = FormButtonsProps &
DialogProps<T | null, boolean>;