refactor(frontend): update categories pages

This commit is contained in:
yassinedorbozgithub 2025-02-02 13:52:00 +01:00
parent 735e783864
commit c68939945f
10 changed files with 269 additions and 185 deletions

View File

@ -0,0 +1,42 @@
/*
* 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 CheckIcon from "@mui/icons-material/Check";
import CloseIcon from "@mui/icons-material/Close";
import { Button } from "@mui/material";
import { useTranslate } from "@/hooks/useTranslate";
import { FormButtonsProps } from "@/types/common/dialogs.types";
export const FormButtons = <T,>({
onCancel,
onConfirm,
}: FormButtonsProps<T>) => {
const { t } = useTranslate();
return (
<>
<Button
type="submit"
variant="contained"
onClick={onConfirm}
startIcon={<CheckIcon />}
>
{t("button.submit")}
</Button>
<Button
color="error"
variant="outlined"
onClick={onCancel}
startIcon={<CloseIcon />}
>
{t("button.cancel")}
</Button>
</>
);
};

View File

@ -6,34 +6,30 @@
* 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 {
Dialog,
DialogActions,
DialogContent,
DialogProps,
} from "@mui/material";
import { FC, ReactNode } from "react";
import { Dialog, DialogActions, DialogContent } from "@mui/material";
import { DialogTitle } from "@/app-components/dialogs/DialogTitle";
import { DialogTitle } from "@/app-components/dialogs";
import { FormDialogProps } from "@/types/common/dialogs.types";
export interface FormDialogProps extends DialogProps {
title: string;
children: ReactNode;
}
import { FormButtons } from "../buttons/FormButtons";
export const FormDialog: FC<FormDialogProps> = ({
export const FormDialog = <T,>({
title,
children,
open,
onClose,
onConfirm,
...rest
}) => {
}: FormDialogProps<T>) => {
return (
<Dialog open={open} fullWidth onClose={onClose} {...rest}>
<DialogTitle onClose={onClose}>{title}</DialogTitle>
<Dialog fullWidth {...rest}>
<DialogTitle onClose={() => rest.onClose?.({}, "backdropClick")}>
{title}
</DialogTitle>
<DialogContent>{children}</DialogContent>
<DialogActions>
{/* <DialogButtons closeDialog={closeDialog} /> */}
<FormButtons<T>
onCancel={() => rest.onClose?.({}, "backdropClick")}
onConfirm={onConfirm}
/>
</DialogActions>
</Dialog>
);

View File

@ -0,0 +1,56 @@
/*
* 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 { Button, Dialog, DialogActions, DialogContent } from "@mui/material";
import { FC, ReactNode } from "react";
import { ConfirmOptions, DialogProps } from "@/types/common/dialogs.types";
import { DialogTitle } from "../DialogTitle";
import { useDialogLoadingButton } from "./hooks/useDialogLoadingButton";
export interface ConfirmDialogPayload extends ConfirmOptions {
msg: ReactNode;
}
export interface ConfirmDialogProps
extends DialogProps<ConfirmDialogPayload, boolean> {}
export const ConfirmDialog: FC<ConfirmDialogProps> = ({ payload, ...rest }) => {
const cancelButtonProps = useDialogLoadingButton(() => rest.onClose(false));
const okButtonProps = useDialogLoadingButton(() => rest.onClose(true));
return (
<Dialog
maxWidth="sm"
fullWidth
{...rest}
onClose={() => rest.onClose(false)}
>
<DialogTitle onClose={() => rest.onClose(false)}>
{payload.title}
</DialogTitle>
<DialogContent>{payload.msg}</DialogContent>
<DialogActions>
<Button
color={payload.severity || "error"}
variant="contained"
disabled={!open}
autoFocus
{...okButtonProps}
>
{payload.okText}
</Button>
<Button variant="outlined" disabled={!open} {...cancelButtonProps}>
{payload.cancelText}
</Button>
</DialogActions>
</Dialog>
);
};

View File

@ -0,0 +1,27 @@
/*
* 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 ErrorIcon from "@mui/icons-material/Error";
import { Grid, Typography } from "@mui/material";
import { useTranslate } from "@/hooks/useTranslate";
export const ConfirmDialogBody = () => {
const { t } = useTranslate();
return (
<Grid container gap={1}>
<Grid item height="28px">
<ErrorIcon sx={{ fontSize: "28px" }} color="error" />
</Grid>
<Grid item alignSelf="center">
<Typography>{t("message.item_delete_confirm")}</Typography>
</Grid>
</Grid>
);
};

View File

@ -0,0 +1,26 @@
/*
* 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 { useState } from "react";
export const useDialogLoadingButton = (onClose: () => Promise<void>) => {
const [loading, setLoading] = useState(false);
const handleClick = async () => {
try {
setLoading(true);
await onClose();
} finally {
setLoading(false);
}
};
return {
onClick: handleClick,
loading,
};
};

View File

@ -6,7 +6,10 @@
* 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).
*/
export * from "./confirm/ConfirmDialog";
export * from "./confirm/ConfirmDialogBody";
export * from "./DeleteDialog";
export * from "./DialogTitle";
export * from "./FormDialog";
export * from "./layouts/ContentContainer";
export * from "./layouts/ContentItem";

View File

@ -1,113 +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 { Dialog, DialogActions, DialogContent } from "@mui/material";
import { FC, useEffect } from "react";
import { useForm } from "react-hook-form";
import DialogButtons from "@/app-components/buttons/DialogButtons";
import { DialogTitle } from "@/app-components/dialogs/DialogTitle";
import { ContentContainer } from "@/app-components/dialogs/layouts/ContentContainer";
import { ContentItem } from "@/app-components/dialogs/layouts/ContentItem";
import { Input } from "@/app-components/inputs/Input";
import { useCreate } from "@/hooks/crud/useCreate";
import { useUpdate } from "@/hooks/crud/useUpdate";
import { DialogControlProps } from "@/hooks/useDialog";
import { useToast } from "@/hooks/useToast";
import { useTranslate } from "@/hooks/useTranslate";
import { EntityType } from "@/services/types";
import { ICategory, ICategoryAttributes } from "@/types/category.types";
export type CategoryDialogProps = DialogControlProps<ICategory>;
export const CategoryDialog: FC<CategoryDialogProps> = ({
open,
data,
closeDialog,
...rest
}) => {
const { t } = useTranslate();
const { toast } = useToast();
const { mutateAsync: createCategory } = useCreate(EntityType.CATEGORY, {
onError: (error) => {
toast.error(error);
},
onSuccess: () => {
closeDialog();
toast.success(t("message.success_save"));
},
});
const { mutateAsync: updateCategory } = useUpdate(EntityType.CATEGORY, {
onError: () => {
toast.error(t("message.internal_server_error"));
},
onSuccess: () => {
closeDialog();
toast.success(t("message.success_save"));
},
});
const {
reset,
register,
formState: { errors },
handleSubmit,
} = useForm<ICategoryAttributes>({
defaultValues: { label: data?.label || "" },
});
const validationRules = {
label: {
required: t("message.label_is_required"),
},
};
const onSubmitForm = async (params: ICategoryAttributes) => {
if (data) {
updateCategory({ id: data.id, params });
} else {
createCategory(params);
}
};
useEffect(() => {
if (open) reset();
}, [open, reset]);
useEffect(() => {
if (data) {
reset({
label: data.label,
});
} else {
reset();
}
}, [data, reset]);
return (
<Dialog open={open} fullWidth onClose={closeDialog} {...rest}>
<form onSubmit={handleSubmit(onSubmitForm)}>
<DialogTitle onClose={closeDialog}>
{data ? t("title.edit_category") : t("title.new_category")}
</DialogTitle>
<DialogContent>
<ContentContainer>
<ContentItem>
<Input
label={t("placeholder.label")}
{...register("label", validationRules.label)}
autoFocus
helperText={errors.label ? errors.label.message : null}
/>
</ContentItem>
</ContentContainer>
</DialogContent>
<DialogActions>
<DialogButtons closeDialog={closeDialog} />
</DialogActions>
</form>
</Dialog>
);
};

View File

@ -6,7 +6,12 @@
* 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, useEffect } from "react";
import {
BaseSyntheticEvent,
forwardRef,
useEffect,
useImperativeHandle,
} from "react";
import { useForm } from "react-hook-form";
import { ContentContainer } from "@/app-components/dialogs/layouts/ContentContainer";
@ -18,30 +23,36 @@ import { useToast } from "@/hooks/useToast";
import { useTranslate } from "@/hooks/useTranslate";
import { EntityType } from "@/services/types";
import { ICategory, ICategoryAttributes } from "@/types/category.types";
import {
ComponentFormProps,
HTMLFormElementExtension,
HTMLFormElementExtra,
} from "@/types/common/dialogs.types";
export type CategoryFormProps = {
data: ICategory | null;
};
export const CategoryForm: FC<CategoryFormProps> = ({ data }) => {
export const CategoryForm = forwardRef<
HTMLFormElement,
ComponentFormProps<ICategory>
>(({ data, ...rest }, ref) => {
const { t } = useTranslate();
const { toast } = useToast();
const { mutateAsync: createCategory } = useCreate(EntityType.CATEGORY, {
onError: (error) => {
toast.error(error);
const options = {
onError: (error: Error) => {
rest.onError?.();
toast.error(error || t("message.internal_server_error"));
},
onSuccess: () => {
rest.onSuccess?.();
toast.success(t("message.success_save"));
},
});
const { mutateAsync: updateCategory } = useUpdate(EntityType.CATEGORY, {
onError: () => {
toast.error(t("message.internal_server_error"));
},
onSuccess: () => {
toast.success(t("message.success_save"));
},
});
};
const { mutateAsync: createCategory } = useCreate(
EntityType.CATEGORY,
options,
);
const { mutateAsync: updateCategory } = useUpdate(
EntityType.CATEGORY,
options,
);
const {
reset,
register,
@ -57,11 +68,25 @@ export const CategoryForm: FC<CategoryFormProps> = ({ data }) => {
};
const onSubmitForm = async (params: ICategoryAttributes) => {
if (data) {
updateCategory({ id: data.id, params });
return await updateCategory({ id: data.id, params });
} else {
createCategory(params);
return await createCategory(params);
}
};
const submitAsync = async (e: BaseSyntheticEvent) => {
return await new Promise<ICategory>((resolve) => {
handleSubmit((params) => {
resolve(onSubmitForm(params));
})(e);
});
};
useImperativeHandle<
HTMLFormElementExtension<ICategory>,
HTMLFormElementExtra<ICategory>
>(ref, () => ({
submitAsync,
}));
useEffect(() => {
if (data) {
@ -74,7 +99,7 @@ export const CategoryForm: FC<CategoryFormProps> = ({ data }) => {
}, [data, reset]);
return (
<form onSubmit={handleSubmit(onSubmitForm)}>
<form ref={ref} onSubmit={submitAsync}>
<ContentContainer>
<ContentItem>
<Input
@ -87,4 +112,6 @@ export const CategoryForm: FC<CategoryFormProps> = ({ data }) => {
</ContentContainer>
</form>
);
};
});
CategoryForm.displayName = "CategoryForm";

View File

@ -6,32 +6,42 @@
* 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 } from "react";
import { useRef } from "react";
import { FormDialog } from "@/app-components/dialogs/FormDialog";
import { DialogProps } from "@/contexts/dialogs.context";
import { FormDialog } from "@/app-components/dialogs";
import { useTranslate } from "@/hooks/useTranslate";
import { ICategory } from "@/types/category.types";
import {
ComponentFormDialogProps,
HTMLFormElementExtra,
} from "@/types/common/dialogs.types";
import { CategoryForm } from "./CategoryForm";
export type CategoryFormProps = DialogProps<ICategory | null, boolean>;
export const CategoryFormDialog: FC<CategoryFormProps> = ({
onClose,
export const CategoryFormDialog = <T extends ICategory = ICategory>({
payload,
...rest
}) => {
}: ComponentFormDialogProps<T>) => {
const { t } = useTranslate();
const formRef = useRef<(HTMLFormElement & HTMLFormElementExtra<T>) | null>(
null,
);
return (
<FormDialog
<FormDialog<T>
title={payload ? t("title.edit_category") : t("title.new_category")}
onConfirm={async (e) => {
return await formRef.current?.submitAsync(e);
}}
{...rest}
// @TODO: fix typing
onClose={async () => await onClose(false)}
>
<CategoryForm data={payload} />
<CategoryForm
ref={formRef}
data={payload}
onSuccess={() => {
rest.onClose(true);
}}
/>
</FormDialog>
);
};

View File

@ -13,6 +13,7 @@ import { Button, Grid, Paper } from "@mui/material";
import { GridColDef, GridRowSelectionModel } from "@mui/x-data-grid";
import { useState } from "react";
import { ConfirmDialogBody } from "@/app-components/dialogs";
import { FilterTextfield } from "@/app-components/inputs/FilterTextfield";
import {
ActionColumnLabel,
@ -78,12 +79,24 @@ export const Categories = () => {
[
{
label: ActionColumnLabel.Edit,
action: (row) => dialogs.open(CategoryFormDialog, row),
action: async (row) => {
await dialogs.open(CategoryFormDialog, row);
},
requires: [PermissionAction.UPDATE],
},
{
label: ActionColumnLabel.Delete,
action: (row) => deleteDialogCtl.openDialog(row.id),
action: async ({ id }) => {
const isConfirmed = await dialogs.confirm(<ConfirmDialogBody />, {
title: t("title.warning"),
okText: t("label.yes"),
cancelText: t("label.no"),
});
if (isConfirmed) {
await deleteCategory(id);
}
},
requires: [PermissionAction.DELETE],
},
],
@ -130,22 +143,6 @@ export const Categories = () => {
return (
<Grid container gap={3} flexDirection="column">
{/* <CategoryDialog {...getDisplayDialogs(addDialogCtl)} />
<CategoryDialog {...getDisplayDialogs(editDialogCtl)} />
<DeleteDialog
{...deleteDialogCtl}
callback={async () => {
if (selectedCategories.length > 0) {
deleteCategories(selectedCategories), setSelectedCategories([]);
deleteDialogCtl.closeDialog();
} else if (deleteDialogCtl?.data) {
{
deleteCategory(deleteDialogCtl.data);
deleteDialogCtl.closeDialog();
}
}
}}
/> */}
<Grid>
<PageHeader icon={FolderIcon} title={t("title.categories")}>
<Grid
@ -177,7 +174,20 @@ export const Categories = () => {
startIcon={<DeleteIcon />}
variant="contained"
color="error"
onClick={() => deleteDialogCtl.openDialog(undefined)}
onClick={async () => {
const isConfirmed = await dialogs.confirm(
<ConfirmDialogBody />,
{
title: t("title.warning"),
okText: t("label.yes"),
cancelText: t("label.no"),
},
);
if (isConfirmed) {
await deleteCategories(selectedCategories);
}
}}
>
{t("button.delete")}
</Button>