Merge branch 'main' into 706-refactor-roles-dialogs-add-edit-delete-permissions

This commit is contained in:
yassinedorbozgithub 2025-02-07 15:31:22 +01:00
commit 9b1d6c5381
35 changed files with 1189 additions and 1358 deletions

View File

@ -1,5 +1,5 @@
/*
* Copyright © 2024 Hexastack. All rights reserved.
* 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.
@ -43,7 +43,7 @@ export class ContentStub extends BaseSchema {
@Prop({ type: Boolean, default: true })
status: boolean;
@Prop({ type: mongoose.Schema.Types.Mixed })
@Prop({ type: mongoose.Schema.Types.Mixed, default: {} })
dynamicFields: Record<string, any>;
@Prop({ type: String })

View File

@ -112,7 +112,8 @@
"text_is_required": "Text is required",
"invalid_file_type": "Invalid file type. Please select a file in the supported format.",
"select_category": "Select a flow",
"logout_failed": "Something went wrong during logout"
"logout_failed": "Something went wrong during logout",
"duplicate_labels_not_allowed": "Duplicate labels are not allowed"
},
"menu": {
"terms": "Terms of Use",
@ -191,13 +192,14 @@
"entities": "Content Types",
"new_content_type": "New Content Type",
"edit_content_type": "Edit Content Type",
"manage_fields": "Manage Fields",
"nodes": "Content",
"new_node": "New Content",
"edit_node": "Edit Content",
"import": "Bulk Import",
"media_library": "Media Library",
"languages": "Languages",
"new_language": "Add Language",
"edit_language": "Edit Language",
"translations": "Translations",
"update_translation": "Update Translation",
"broadcast": "Broadcast",
@ -208,6 +210,7 @@
"new_label": "New Label",
"edit_label": "Edit Label",
"subscribers": "Subscribers",
"manage_subscribers": "Manage Subscribers",
"manage_labels": "Manage Labels",
"users": "Users",
"manage_roles": "Manage Roles",

View File

@ -112,7 +112,8 @@
"text_is_required": "Texte requis",
"invalid_file_type": "Type de fichier invalide. Veuillez choisir un fichier dans un format pris en charge.",
"select_category": "Sélectionner une catégorie",
"logout_failed": "Une erreur s'est produite lors de la déconnexion"
"logout_failed": "Une erreur s'est produite lors de la déconnexion",
"duplicate_labels_not_allowed": "Les étiquettes en double ne sont pas autorisées"
},
"menu": {
"terms": "Conditions d'utilisation",
@ -191,13 +192,14 @@
"entities": "Types de contenu",
"new_content_type": "Nouveau type de contenu",
"edit_content_type": "Modifier le type de contenu",
"manage_fields": "Gérer les champs",
"nodes": "Contenu",
"new_node": "Nouveau contenu",
"edit_node": "Modifier le contenu",
"import": "Importation en masse",
"media_library": "Bibliothéque Media",
"languages": "Langues",
"new_language": "Nouvelle langue",
"edit_language": "Modifier la langue",
"translations": "Traductions",
"update_translation": "Mettre à jour la traduction",
"broadcast": "Diffusion",
@ -208,6 +210,7 @@
"new_label": "Nouvelle étiquette",
"edit_label": "Modifier l'étiquette",
"subscribers": "Abonnés",
"manage_subscribers": "Gérer les abonnés",
"manage_labels": "Gérer les étiquettes",
"users": "Utilisateurs",
"manage_roles": "Gérer les rôles",

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,21 +17,21 @@ export const FormDialog = ({
title,
children,
onSubmit,
cancelButtonProps,
confirmButtonProps,
...rest
}: FormDialogProps) => {
const handleClose = () => rest.onClose?.({}, "backdropClick");
const dialogActions =
rest.hasButtons === false ? null : (
<DialogActions style={{ padding: "0.5rem" }}>
<DialogFormButtons onCancel={handleClose} onSubmit={onSubmit} />
</DialogActions>
);
const onCancel = () => rest.onClose?.({}, "backdropClick");
return (
<Dialog fullWidth {...rest}>
<DialogTitle onClose={handleClose}>{title}</DialogTitle>
<DialogTitle onClose={onCancel}>{title}</DialogTitle>
<DialogContent>{children}</DialogContent>
{dialogActions}
<DialogActions style={{ padding: "0.5rem" }}>
<DialogFormButtons
{...{ onSubmit, onCancel, confirmButtonProps, cancelButtonProps }}
/>
</DialogActions>
</Dialog>
);
};

View File

@ -1,14 +1,15 @@
/*
* Copyright © 2024 Hexastack. All rights reserved.
* 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 { Dialog, DialogActions, DialogContent } from "@mui/material";
import AddIcon from "@mui/icons-material/Add";
import { Button, Dialog, DialogActions, DialogContent } from "@mui/material";
import { FC, useEffect } from "react";
import { useForm } from "react-hook-form";
import { useFieldArray, useForm } from "react-hook-form";
import DialogButtons from "@/app-components/buttons/DialogButtons";
import { DialogTitle } from "@/app-components/dialogs/DialogTitle";
@ -21,10 +22,10 @@ import { DialogControlProps } from "@/hooks/useDialog";
import { useToast } from "@/hooks/useToast";
import { useTranslate } from "@/hooks/useTranslate";
import { EntityType } from "@/services/types";
import {
IContentType,
IContentTypeAttributes,
} from "@/types/content-type.types";
import { ContentFieldType, IContentType } from "@/types/content-type.types";
import { FieldInput } from "./components/FieldInput";
import { FIELDS_FORM_DEFAULT_VALUES, READ_ONLY_FIELDS } from "./constants";
export type ContentTypeDialogProps = DialogControlProps<IContentType>;
export const ContentTypeDialog: FC<ContentTypeDialogProps> = ({
@ -37,50 +38,67 @@ export const ContentTypeDialog: FC<ContentTypeDialogProps> = ({
const {
handleSubmit,
register,
control,
reset,
setValue,
formState: { errors },
} = useForm<IContentTypeAttributes>({
defaultValues: { name: data?.name || "" },
} = useForm<Partial<IContentType>>({
defaultValues: {
name: data?.name || "",
fields: data?.fields || FIELDS_FORM_DEFAULT_VALUES,
},
});
const CloseAndReset = () => {
const { append, fields, remove } = useFieldArray({
name: "fields",
control,
});
const closeAndReset = () => {
closeDialog();
reset();
reset({
name: "",
fields: FIELDS_FORM_DEFAULT_VALUES,
});
};
const { mutateAsync: createContentType } = useCreate(
EntityType.CONTENT_TYPE,
{
onError: (error) => {
toast.error(error);
},
onSuccess: () => {
closeDialog();
toast.success(t("message.success_save"));
},
const { mutate: createContentType } = useCreate(EntityType.CONTENT_TYPE, {
onError: (error) => {
toast.error(error.message || t("message.internal_server_error"));
},
);
const { mutateAsync: updateContentType } = useUpdate(
EntityType.CONTENT_TYPE,
{
onError: () => {
toast.error(t("message.internal_server_error"));
},
onSuccess: () => {
closeDialog();
toast.success(t("message.success_save"));
},
onSuccess: () => {
closeDialog();
toast.success(t("message.success_save"));
},
);
const validationRules = {
name: {
required: t("message.name_is_required"),
});
const { mutate: updateContentType } = useUpdate(EntityType.CONTENT_TYPE, {
onError: (error) => {
toast.error(error.message || t("message.internal_server_error"));
},
};
const onSubmitForm = async (params: IContentTypeAttributes) => {
onSuccess: () => {
closeDialog();
toast.success(t("message.success_save"));
},
});
const onSubmitForm = async (params) => {
const labelCounts: Record<string, number> = params.fields.reduce(
(acc, field) => {
if (!field.label.trim()) return acc;
acc[field.label] = (acc[field.label] || 0) + 1;
return acc;
},
{} as Record<string, number>,
);
const hasDuplicates = Object.values(labelCounts).some(
(count: number) => count > 1,
);
if (hasDuplicates) {
toast.error(t("message.duplicate_labels_not_allowed"));
return;
}
if (data) {
updateContentType({
id: data.id,
params,
});
updateContentType({ id: data.id, params });
} else {
createContentType(params);
}
@ -94,16 +112,17 @@ export const ContentTypeDialog: FC<ContentTypeDialogProps> = ({
if (data) {
reset({
name: data.name,
fields: data.fields || FIELDS_FORM_DEFAULT_VALUES,
});
} else {
reset();
reset({ name: "", fields: FIELDS_FORM_DEFAULT_VALUES });
}
}, [data, reset]);
return (
<Dialog open={open} fullWidth onClose={CloseAndReset}>
<Dialog open={open} fullWidth onClose={closeAndReset}>
<form onSubmit={handleSubmit(onSubmitForm)}>
<DialogTitle onClose={CloseAndReset}>
<DialogTitle onClose={closeAndReset}>
{data ? t("title.edit_content_type") : t("title.new_content_type")}
</DialogTitle>
<DialogContent>
@ -112,16 +131,46 @@ export const ContentTypeDialog: FC<ContentTypeDialogProps> = ({
<Input
label={t("label.name")}
error={!!errors.name}
{...register("name", validationRules.name)}
{...register("name", {
required: t("message.name_is_required"),
})}
helperText={errors.name ? errors.name.message : null}
required
autoFocus
/>
</ContentItem>
{fields.map((f, index) => (
<ContentItem
key={f.id}
display="flex"
justifyContent="space-between"
gap={2}
>
<FieldInput
setValue={setValue}
control={control}
remove={remove}
index={index}
disabled={READ_ONLY_FIELDS.includes(f.label as any)}
/>
</ContentItem>
))}
<ContentItem>
<Button
startIcon={<AddIcon />}
variant="contained"
onClick={() =>
append({ label: "", name: "", type: ContentFieldType.TEXT })
}
>
{t("button.add")}
</Button>
</ContentItem>
</ContentContainer>
</DialogContent>
<DialogActions>
<DialogButtons closeDialog={closeDialog} />
<DialogButtons closeDialog={closeAndReset} />
</DialogActions>
</form>
</Dialog>

View File

@ -1,219 +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 AddIcon from "@mui/icons-material/Add";
import {
Button,
CircularProgress,
Dialog,
DialogActions,
DialogContent,
Stack,
} from "@mui/material";
import { useEffect } from "react";
import { useFieldArray, useForm } from "react-hook-form";
import DialogButtons from "@/app-components/buttons/DialogButtons";
import {
DialogTitle,
ContentContainer,
ContentItem,
} from "@/app-components/dialogs";
import { Input } from "@/app-components/inputs/Input";
import { useGet } from "@/hooks/crud/useGet";
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 { ContentFieldType, IContentType } from "@/types/content-type.types";
import { FieldInput } from "./components/FieldInput";
import { FIELDS_FORM_DEFAULT_VALUES, READ_ONLY_FIELDS } from "./constants";
export type EditContentTypeDialogFieldsProps = DialogControlProps<IContentType>;
export const EditContentTypeFieldsDialog = ({
data: contentType,
closeDialog,
open,
}: EditContentTypeDialogFieldsProps) => {
const { t } = useTranslate();
const { isLoading, data, refetch } = useGet(contentType?.id || "", {
entity: EntityType.CONTENT_TYPE,
});
const { toast } = useToast();
const {
handleSubmit,
control,
reset,
setValue,
register,
formState: { errors },
} = useForm<Partial<IContentType>>({
mode: "onChange",
values: {
fields: data?.fields,
name: data?.name,
},
defaultValues: {
fields: FIELDS_FORM_DEFAULT_VALUES,
name: data?.name,
},
});
const { append, fields, replace, remove } = useFieldArray<
Pick<IContentType, "fields">,
"fields"
>({
name: "fields",
control,
keyName: "id",
rules: {
required: true,
},
});
const validationRules = {
name: {
required: t("message.name_is_required"),
},
};
useEffect(() => {
register("fields");
}, [register]);
useEffect(() => {
if (data?.fields) {
replace(data.fields);
}
}, [data, replace]);
useEffect(() => {
if (!open) {
reset();
}
if (open) {
refetch();
}
}, [open, reset]);
useEffect(() => {
if (data) {
reset({
name: data.name,
fields: data.fields,
});
} else {
reset();
}
}, [data, reset]);
function handleClose() {
closeDialog();
}
const { mutateAsync: updateContentType } = useUpdate(
EntityType.CONTENT_TYPE,
{
onError: (error) => {
toast.error(`${t("message.internal_server_error")}: ${error}`);
},
onSuccess: () => {
toast.success(t("message.success_save"));
},
},
);
return (
<Dialog
open={open}
fullWidth
maxWidth="xl"
sx={{ width: "fit-content", mx: "auto", minWidth: "600px" }}
onClose={handleClose}
>
<DialogTitle onClose={handleClose}>
{t("title.manage_fields")}
</DialogTitle>
<form
onSubmit={handleSubmit(async ({ name, fields }) => {
if (!!contentType)
await updateContentType({
id: contentType.id,
params: {
name,
fields,
},
});
handleClose();
})}
>
<DialogContent>
<ContentContainer>
<ContentItem>
<Input
label={t("label.name")}
error={!!errors.name}
{...register("name", validationRules.name)}
helperText={errors.name ? errors.name.message : null}
required
autoFocus
/>
</ContentItem>
{!isLoading
? fields.map((f, index) => (
<ContentItem
key={f.id}
justifyContent="space-between"
alignItems="center"
gap={2}
display="flex"
>
<FieldInput
setValue={setValue}
control={control}
remove={remove}
index={index}
disabled={READ_ONLY_FIELDS.includes(f.label as any)}
/>
</ContentItem>
))
: null}
{isLoading ? (
<ContentItem>
<Stack sx={{ alignItems: "center", placeContent: "center" }}>
<CircularProgress sx={{ color: "primary.main" }} />
</Stack>
</ContentItem>
) : null}
<ContentItem>
<Button
startIcon={<AddIcon />}
variant="contained"
onClick={() =>
append({
label: "",
name: "",
type: ContentFieldType.TEXT,
})
}
disabled={isLoading}
sx={{ mx: "auto" }}
>
{t("button.add")}
</Button>
</ContentItem>
</ContentContainer>
</DialogContent>
<DialogActions>
<DialogButtons closeDialog={closeDialog} />
</DialogActions>
</form>
</Dialog>
);
};

View File

@ -1,11 +1,12 @@
/*
* Copyright © 2024 Hexastack. All rights reserved.
* 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 DeleteOutlineIcon from "@mui/icons-material/DeleteOutline";
import { MenuItem } from "@mui/material";
import { useEffect } from "react";
@ -59,11 +60,14 @@ export const FieldInput = ({
<Controller
control={props.control}
name={`fields.${index}.label`}
render={({ field }) => (
rules={{ required: t("message.label_is_required") }}
render={({ field, fieldState }) => (
<Input
disabled={props.disabled}
{...field}
label={t("label.label")}
error={!!fieldState.error}
helperText={fieldState.error?.message}
/>
)}
/>

View File

@ -1,11 +1,12 @@
/*
* Copyright © 2024 Hexastack. All rights reserved.
* 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 { faAlignLeft } from "@fortawesome/free-solid-svg-icons";
import AddIcon from "@mui/icons-material/Add";
import { Button, Grid, Paper } from "@mui/material";
@ -33,7 +34,6 @@ import { PermissionAction } from "@/types/permission.types";
import { getDateTimeFormatter } from "@/utils/date";
import { ContentTypeDialog } from "./ContentTypeDialog";
import { EditContentTypeFieldsDialog } from "./EditContentTypeFieldsDialog";
export const ContentTypes = () => {
const { t } = useTranslate();
@ -125,7 +125,7 @@ export const ContentTypes = () => {
deleteContentType(deleteDialogCtl.data);
}}
/>
<EditContentTypeFieldsDialog {...fieldsDialogCtl} />
<ContentTypeDialog {...getDisplayDialogs(fieldsDialogCtl)} />
<Grid padding={2} container>
<Grid item width="100%">
<DataGrid

View File

@ -6,7 +6,6 @@
* 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 LinkIcon from "@mui/icons-material/Link";
import {
Dialog,

View File

@ -1,150 +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,
FormControlLabel,
Switch,
} from "@mui/material";
import { FC, useEffect } from "react";
import { Controller, 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 { ILanguage, ILanguageAttributes } from "@/types/language.types";
export type LanguageDialogProps = DialogControlProps<ILanguage>;
export const LanguageDialog: FC<LanguageDialogProps> = ({
open,
data,
closeDialog,
...rest
}) => {
const { t } = useTranslate();
const { toast } = useToast();
const { mutateAsync: createLanguage } = useCreate(EntityType.LANGUAGE, {
onError: () => {
toast.error(t("message.internal_server_error"));
},
onSuccess() {
closeDialog();
toast.success(t("message.success_save"));
},
});
const { mutateAsync: updateLanguage } = useUpdate(EntityType.LANGUAGE, {
onError: () => {
toast.error(t("message.internal_server_error"));
},
onSuccess() {
closeDialog();
toast.success(t("message.success_save"));
},
});
const {
reset,
register,
formState: { errors },
handleSubmit,
control,
} = useForm<ILanguageAttributes>({
defaultValues: {
title: data?.title || "",
code: data?.code || "",
isRTL: data?.isRTL || false,
},
});
const validationRules = {
title: {
required: t("message.title_is_required"),
},
code: {
required: t("message.code_is_required"),
},
};
const onSubmitForm = async (params: ILanguageAttributes) => {
if (data) {
updateLanguage({ id: data.id, params });
} else {
createLanguage(params);
}
};
useEffect(() => {
if (open) reset();
}, [open, reset]);
useEffect(() => {
if (data) {
reset({
title: data.title,
code: data.code,
isRTL: data.isRTL,
});
} else {
reset();
}
}, [data, reset]);
return (
<Dialog open={open} fullWidth onClose={closeDialog} {...rest}>
<form onSubmit={handleSubmit(onSubmitForm)}>
<DialogTitle onClose={closeDialog}>
{data ? t("title.edit_label") : t("title.new_label")}
</DialogTitle>
<DialogContent>
<ContentContainer>
<ContentItem>
<Input
label={t("label.title")}
error={!!errors.title}
{...register("title", validationRules.title)}
helperText={errors.title ? errors.title.message : null}
multiline={true}
/>
</ContentItem>
<ContentItem>
<Input
label={t("label.code")}
error={!!errors.code}
{...register("code", validationRules.code)}
helperText={errors.code ? errors.code.message : null}
multiline={true}
/>
</ContentItem>
<ContentItem>
<Controller
name="isRTL"
control={control}
render={({ field }) => (
<FormControlLabel
control={<Switch {...field} checked={field.value} />}
label={t("label.is_rtl")}
/>
)}
/>
</ContentItem>
</ContentContainer>
</DialogContent>
<DialogActions>
<DialogButtons closeDialog={closeDialog} />
</DialogActions>
</form>
</Dialog>
);
};

View File

@ -0,0 +1,127 @@
/*
* 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 { FormControlLabel, Switch } from "@mui/material";
import { FC, Fragment, useEffect } from "react";
import { Controller, useForm } from "react-hook-form";
import { ContentContainer, ContentItem } from "@/app-components/dialogs/";
import { Input } from "@/app-components/inputs/Input";
import { useCreate } from "@/hooks/crud/useCreate";
import { useUpdate } from "@/hooks/crud/useUpdate";
import { useToast } from "@/hooks/useToast";
import { useTranslate } from "@/hooks/useTranslate";
import { EntityType } from "@/services/types";
import { ComponentFormProps } from "@/types/common/dialogs.types";
import { ILanguage, ILanguageAttributes } from "@/types/language.types";
export const LanguageForm: FC<ComponentFormProps<ILanguage>> = ({
data,
Wrapper = Fragment,
WrapperProps,
...rest
}) => {
const { t } = useTranslate();
const { toast } = useToast();
const options = {
onError: () => {
rest.onError?.();
toast.error(t("message.internal_server_error"));
},
onSuccess() {
rest.onSuccess?.();
toast.success(t("message.success_save"));
},
};
const { mutate: createLanguage } = useCreate(EntityType.LANGUAGE, options);
const { mutate: updateLanguage } = useUpdate(EntityType.LANGUAGE, options);
const {
reset,
register,
formState: { errors },
handleSubmit,
control,
} = useForm<ILanguageAttributes>({
defaultValues: {
title: data?.title || "",
code: data?.code || "",
isRTL: data?.isRTL || false,
},
});
const validationRules = {
title: {
required: t("message.title_is_required"),
},
code: {
required: t("message.code_is_required"),
},
};
const onSubmitForm = (params: ILanguageAttributes) => {
if (data) {
updateLanguage({ id: data.id, params });
} else {
createLanguage(params);
}
};
useEffect(() => {
if (data) {
reset({
title: data.title,
code: data.code,
isRTL: data.isRTL,
});
} else {
reset();
}
}, [data, reset]);
return (
<Wrapper
open={!!WrapperProps?.open}
onSubmit={handleSubmit(onSubmitForm)}
{...WrapperProps}
>
<form onSubmit={handleSubmit(onSubmitForm)}>
<ContentContainer>
<ContentItem>
<Input
label={t("label.title")}
error={!!errors.title}
{...register("title", validationRules.title)}
multiline={true}
autoFocus
helperText={errors.title ? errors.title.message : null}
/>
</ContentItem>
<ContentItem>
<Input
label={t("label.code")}
error={!!errors.code}
{...register("code", validationRules.code)}
multiline={true}
helperText={errors.code ? errors.code.message : null}
/>
</ContentItem>
<ContentItem>
<Controller
name="isRTL"
control={control}
render={({ field }) => (
<FormControlLabel
control={<Switch {...field} checked={field.value} />}
label={t("label.is_rtl")}
/>
)}
/>
</ContentItem>
</ContentContainer>
</form>
</Wrapper>
);
};

View File

@ -0,0 +1,24 @@
/*
* 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 { GenericFormDialog } from "@/app-components/dialogs";
import { ComponentFormDialogProps } from "@/types/common/dialogs.types";
import { ILanguage } from "@/types/language.types";
import { LanguageForm } from "./LanguageForm";
export const LanguageFormDialog = <T extends ILanguage = ILanguage>(
props: ComponentFormDialogProps<T>,
) => (
<GenericFormDialog<T>
Form={LanguageForm}
addText="title.new_language"
editText="title.edit_language"
{...props}
/>
);

View File

@ -12,7 +12,7 @@ import { Button, Grid, Paper, Switch } from "@mui/material";
import { GridColDef } from "@mui/x-data-grid";
import { useQueryClient } from "react-query";
import { DeleteDialog } from "@/app-components/dialogs/DeleteDialog";
import { ConfirmDialogBody } from "@/app-components/dialogs";
import { FilterTextfield } from "@/app-components/inputs/FilterTextfield";
import {
ActionColumnLabel,
@ -24,7 +24,7 @@ import { isSameEntity } from "@/hooks/crud/helpers";
import { useDelete } from "@/hooks/crud/useDelete";
import { useFind } from "@/hooks/crud/useFind";
import { useUpdate } from "@/hooks/crud/useUpdate";
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";
@ -35,14 +35,12 @@ import { ILanguage } from "@/types/language.types";
import { PermissionAction } from "@/types/permission.types";
import { getDateTimeFormatter } from "@/utils/date";
import { LanguageDialog } from "./LanguageDialog";
import { LanguageFormDialog } from "./LanguageFormDialog";
export const Languages = () => {
const { t } = useTranslate();
const { toast } = useToast();
const addDialogCtl = useDialog<ILanguage>(false);
const editDialogCtl = useDialog<ILanguage>(false);
const deleteDialogCtl = useDialog<string>(false);
const dialogs = useDialogs();
const queryClient = useQueryClient();
const hasPermission = useHasPermission();
const { onSearch, searchPayload } = useSearch<ILanguage>({
@ -75,7 +73,6 @@ export const Languages = () => {
return isSameEntity(qEntity, EntityType.NLP_SAMPLE);
},
});
deleteDialogCtl.closeDialog();
toast.success(t("message.item_delete_success"));
},
});
@ -94,12 +91,18 @@ export const Languages = () => {
[
{
label: ActionColumnLabel.Edit,
action: (row) => editDialogCtl.openDialog(row),
action: (row) => dialogs.open(LanguageFormDialog, row),
requires: [PermissionAction.UPDATE],
},
{
label: ActionColumnLabel.Delete,
action: (row) => deleteDialogCtl.openDialog(row.id),
action: async ({ id }) => {
const isConfirmed = await dialogs.confirm(ConfirmDialogBody);
if (isConfirmed) {
deleteLanguage(id);
}
},
requires: [PermissionAction.DELETE],
isDisabled: (row) => row.isDefault,
},
@ -182,14 +185,6 @@ export const Languages = () => {
return (
<Grid container gap={3} flexDirection="column">
<LanguageDialog {...getDisplayDialogs(addDialogCtl)} />
<LanguageDialog {...getDisplayDialogs(editDialogCtl)} />
<DeleteDialog
{...deleteDialogCtl}
callback={() => {
if (deleteDialogCtl?.data) deleteLanguage(deleteDialogCtl.data);
}}
/>
<PageHeader icon={Flag} title={t("title.languages")}>
<Grid
justifyContent="flex-end"
@ -208,7 +203,7 @@ export const Languages = () => {
startIcon={<AddIcon />}
variant="contained"
sx={{ float: "right" }}
onClick={() => addDialogCtl.openDialog()}
onClick={() => dialogs.open(LanguageFormDialog, null)}
>
{t("button.add")}
</Button>

View File

@ -1,163 +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,
FormControl,
FormControlLabel,
FormLabel,
Radio,
RadioGroup,
DialogContent,
DialogActions,
} 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 {
INlpEntity,
INlpEntityAttributes,
NlpLookups,
} from "@/types/nlp-entity.types";
export type NlpEntityDialogProps = DialogControlProps<INlpEntity>;
export const NlpEntityDialog: FC<NlpEntityDialogProps> = ({
open,
closeDialog,
data,
...rest
}) => {
const { t } = useTranslate();
const { toast } = useToast();
const { mutateAsync: createNlpEntity } = useCreate(EntityType.NLP_ENTITY, {
onError: () => {
toast.error(t("message.internal_server_error"));
},
onSuccess: () => {
closeDialog();
toast.success(t("message.success_save"));
},
});
const { mutateAsync: updateNlpEntity } = useUpdate(EntityType.NLP_ENTITY, {
onError: () => {
toast.error(t("message.internal_server_error"));
},
onSuccess: () => {
closeDialog();
toast.success(t("message.success_save"));
},
});
const {
reset,
register,
formState: { errors },
handleSubmit,
} = useForm<INlpEntityAttributes>({
defaultValues: {
name: data?.name || "",
doc: data?.doc || "",
lookups: data?.lookups || ["keywords"],
},
});
const validationRules = {
name: {
required: t("message.name_is_required"),
},
lookups: {},
isChecked: {},
};
const onSubmitForm = async (params: INlpEntityAttributes) => {
if (data) {
updateNlpEntity({ id: data.id, params });
} else {
createNlpEntity(params);
}
};
useEffect(() => {
if (open) reset();
}, [open, reset]);
useEffect(() => {
if (data) {
reset({
name: data.name,
doc: data.doc,
});
} else {
reset();
}
}, [data, reset]);
return (
<Dialog open={open} fullWidth onClose={closeDialog} {...rest}>
<form onSubmit={handleSubmit(onSubmitForm)}>
<DialogTitle onClose={closeDialog}>
{data ? t("title.edit_nlp_entity") : t("title.new_nlp_entity")}
</DialogTitle>
<DialogContent>
<ContentContainer>
{!data ? (
<ContentItem>
<FormControl>
<FormLabel>{t("label.lookup_strategies")}</FormLabel>
<RadioGroup
row
{...register("lookups")}
defaultValue="keywords"
>
{Object.values(NlpLookups).map((nlpLookup, index) => (
<FormControlLabel
key={index}
value={nlpLookup}
control={<Radio {...register("lookups.0")} />}
label={nlpLookup}
/>
))}
</RadioGroup>
</FormControl>
</ContentItem>
) : null}
<ContentItem>
<Input
label={t("label.name")}
error={!!errors.name}
{...register("name", validationRules.name)}
required
autoFocus
helperText={errors.name ? errors.name.message : null}
/>
</ContentItem>
<ContentItem>
<Input
label={t("label.doc")}
{...register("doc")}
multiline={true}
/>
</ContentItem>
</ContentContainer>
</DialogContent>
<DialogActions>
<DialogButtons closeDialog={closeDialog} />
</DialogActions>
</form>
</Dialog>
);
};

View File

@ -1,145 +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 { useRouter } from "next/router";
import { FC, useEffect } from "react";
import { Controller, 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 MultipleInput from "@/app-components/inputs/MultipleInput";
import { useCreate } from "@/hooks/crud/useCreate";
import { useGet } from "@/hooks/crud/useGet";
import { useUpdate } from "@/hooks/crud/useUpdate";
import { DialogControlProps } from "@/hooks/useDialog";
import { useToast } from "@/hooks/useToast";
import { useTranslate } from "@/hooks/useTranslate";
import { EntityType, Format } from "@/services/types";
import { INlpValue, INlpValueAttributes } from "@/types/nlp-value.types";
export type TNlpValueAttributesWithRequiredExpressions = INlpValueAttributes & {
expressions: string[];
};
export type NlpValueDialogProps = DialogControlProps<INlpValue, INlpValue> & {
canHaveSynonyms: boolean;
};
export const NlpValueDialog: FC<NlpValueDialogProps> = ({
open,
closeDialog,
data,
canHaveSynonyms,
callback,
}) => {
const { t } = useTranslate();
const { toast } = useToast();
const { query } = useRouter();
const { refetch: refetchEntity } = useGet(data?.entity || String(query.id), {
entity: EntityType.NLP_ENTITY,
format: Format.FULL,
});
const { mutateAsync: createNlpValue } = useCreate(EntityType.NLP_VALUE, {
onError: () => {
toast.error(t("message.internal_server_error"));
},
onSuccess(data) {
refetchEntity();
closeDialog();
toast.success(t("message.success_save"));
callback?.(data);
},
});
const { mutateAsync: updateNlpValue } = useUpdate(EntityType.NLP_VALUE, {
onError: () => {
toast.error(t("message.internal_server_error"));
},
onSuccess(data) {
closeDialog();
toast.success(t("message.success_save"));
callback?.(data);
},
});
const { reset, register, handleSubmit, control } =
useForm<TNlpValueAttributesWithRequiredExpressions>({
defaultValues: {
value: data?.value || "",
expressions: data?.expressions || [],
},
});
const validationRules = {
value: {
required: t("message.value_is_required"),
},
name: {},
description: {},
};
const onSubmitForm = async (params: INlpValueAttributes) => {
if (data) {
updateNlpValue({ id: data.id, params });
} else {
createNlpValue({ ...params, entity: String(query.id) });
}
};
useEffect(() => {
if (open) reset();
}, [open, reset]);
useEffect(() => {
if (data) {
reset({
value: data.value,
expressions: data.expressions,
});
} else {
reset();
}
}, [data, reset]);
return (
<Dialog open={open} fullWidth onClose={closeDialog}>
<form onSubmit={handleSubmit(onSubmitForm)}>
<DialogTitle onClose={closeDialog}>
{data ? t("title.edit_nlp_value") : t("title.new_nlp_entity_value")}
</DialogTitle>
<DialogContent>
<ContentContainer>
<ContentItem>
<Input
label={t("placeholder.nlp_value")}
required
autoFocus
{...register("value", validationRules.value)}
/>
</ContentItem>
{canHaveSynonyms ? (
<ContentItem>
<Controller
name="expressions"
control={control}
render={({ field }) => (
<MultipleInput label="synonyms" {...field} />
)}
/>
</ContentItem>
) : null}
</ContentContainer>
</DialogContent>
<DialogActions>
<DialogButtons closeDialog={closeDialog} />
</DialogActions>
</form>
</Dialog>
);
};

View File

@ -1,11 +1,12 @@
/*
* Copyright © 2024 Hexastack. All rights reserved.
* 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 AddIcon from "@mui/icons-material/Add";
import DeleteIcon from "@mui/icons-material/Delete";
import { Button, Chip, Grid } from "@mui/material";
@ -13,7 +14,7 @@ import { GridColDef, GridRowSelectionModel } from "@mui/x-data-grid";
import { useRouter } from "next/router";
import { useState } from "react";
import { DeleteDialog } from "@/app-components/dialogs";
import { ConfirmDialogBody } from "@/app-components/dialogs";
import { FilterTextfield } from "@/app-components/inputs/FilterTextfield";
import {
ActionColumnLabel,
@ -24,7 +25,7 @@ import { DataGrid } from "@/app-components/tables/DataGrid";
import { useDelete } from "@/hooks/crud/useDelete";
import { useDeleteMany } from "@/hooks/crud/useDeleteMany";
import { useFind } from "@/hooks/crud/useFind";
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";
@ -34,39 +35,32 @@ import { INlpEntity } from "@/types/nlp-entity.types";
import { PermissionAction } from "@/types/permission.types";
import { getDateTimeFormatter } from "@/utils/date";
import { NlpEntityDialog } from "../NlpEntityDialog";
import { NlpEntityFormDialog } from "./NlpEntityFormDialog";
const NlpEntity = () => {
const { t } = useTranslate();
const { toast } = useToast();
const dialogs = useDialogs();
const router = useRouter();
const deleteEntityDialogCtl = useDialog<string>(false);
const hasPermission = useHasPermission();
const editEntityDialogCtl = useDialog<INlpEntity>(false);
const { mutateAsync: deleteNlpEntity } = useDelete(EntityType.NLP_ENTITY, {
const { mutate: deleteNlpEntity } = useDelete(EntityType.NLP_ENTITY, {
onError: () => {
toast.error(t("message.internal_server_error"));
},
onSuccess() {
deleteEntityDialogCtl.closeDialog();
toast.success(t("message.item_delete_success"));
},
});
const { mutateAsync: deleteNlpEntities } = useDeleteMany(
EntityType.NLP_ENTITY,
{
onError: (error) => {
toast.error(error);
},
onSuccess: () => {
deleteEntityDialogCtl.closeDialog();
setSelectedNlpEntities([]);
toast.success(t("message.item_delete_success"));
},
const { mutate: deleteNlpEntities } = useDeleteMany(EntityType.NLP_ENTITY, {
onError: (error) => {
toast.error(error);
},
);
onSuccess: () => {
setSelectedNlpEntities([]);
toast.success(t("message.item_delete_success"));
},
});
const [selectedNlpEntities, setSelectedNlpEntities] = useState<string[]>([]);
const addDialogCtl = useDialog<INlpEntity>(false);
const { t } = useTranslate();
const { toast } = useToast();
const { onSearch, searchPayload } = useSearch<INlpEntity>({
$or: ["name", "doc"],
});
@ -100,12 +94,18 @@ const NlpEntity = () => {
},
{
label: ActionColumnLabel.Edit,
action: (row) => editEntityDialogCtl.openDialog(row),
action: (row) => dialogs.open(NlpEntityFormDialog, row),
requires: [PermissionAction.UPDATE],
},
{
label: ActionColumnLabel.Delete,
action: (row) => deleteEntityDialogCtl.openDialog(row.id),
action: async ({ id }) => {
const isConfirmed = await dialogs.confirm(ConfirmDialogBody);
if (isConfirmed) {
deleteNlpEntity(id);
}
},
requires: [PermissionAction.DELETE],
},
],
@ -177,21 +177,6 @@ const NlpEntity = () => {
return (
<Grid item xs={12}>
<NlpEntityDialog {...getDisplayDialogs(addDialogCtl)} />
<NlpEntityDialog {...editEntityDialogCtl} />
<DeleteDialog
{...deleteEntityDialogCtl}
callback={() => {
if (selectedNlpEntities.length > 0) {
deleteNlpEntities(selectedNlpEntities);
setSelectedNlpEntities([]);
deleteEntityDialogCtl.closeDialog();
} else if (deleteEntityDialogCtl.data) {
deleteNlpEntity(deleteEntityDialogCtl.data);
}
}}
/>
<Grid
justifyContent="flex-end"
gap={1}
@ -209,24 +194,32 @@ const NlpEntity = () => {
startIcon={<AddIcon />}
variant="contained"
sx={{ float: "right" }}
onClick={() => addDialogCtl.openDialog()}
onClick={() => dialogs.open(NlpEntityFormDialog, null)}
>
{t("button.add")}
</Button>
</Grid>
) : null}
{selectedNlpEntities.length > 0 && (
<Grid item>
<Button
startIcon={<DeleteIcon />}
variant="contained"
color="error"
onClick={() => deleteEntityDialogCtl.openDialog(undefined)}
>
{t("button.delete")}
</Button>
</Grid>
)}
<Grid item>
<Button
startIcon={<DeleteIcon />}
variant="contained"
color="error"
onClick={async () => {
const isConfirmed = await dialogs.confirm(ConfirmDialogBody, {
mode: "selection",
count: selectedNlpEntities.length,
});
if (isConfirmed) {
deleteNlpEntities(selectedNlpEntities);
}
}}
disabled={!selectedNlpEntities.length}
>
{t("button.delete")}
</Button>
</Grid>
</Grid>
<Grid mt={3}>

View File

@ -0,0 +1,141 @@
/*
* 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 {
FormControl,
FormControlLabel,
FormLabel,
Radio,
RadioGroup,
} from "@mui/material";
import { FC, Fragment, useEffect } from "react";
import { useForm } from "react-hook-form";
import { ContentContainer, ContentItem } from "@/app-components/dialogs/";
import { Input } from "@/app-components/inputs/Input";
import { useCreate } from "@/hooks/crud/useCreate";
import { useUpdate } from "@/hooks/crud/useUpdate";
import { useToast } from "@/hooks/useToast";
import { useTranslate } from "@/hooks/useTranslate";
import { EntityType } from "@/services/types";
import { ComponentFormProps } from "@/types/common/dialogs.types";
import {
INlpEntity,
INlpEntityAttributes,
NlpLookups,
} from "@/types/nlp-entity.types";
export const NlpEntityVarForm: FC<ComponentFormProps<INlpEntity>> = ({
data,
Wrapper = Fragment,
WrapperProps,
...rest
}) => {
const { t } = useTranslate();
const { toast } = useToast();
const options = {
onError: (error: Error) => {
rest.onError?.();
toast.error(error.message || t("message.internal_server_error"));
},
onSuccess: () => {
rest.onSuccess?.();
toast.success(t("message.success_save"));
},
};
const { mutate: createNlpEntity } = useCreate(EntityType.NLP_ENTITY, options);
const { mutate: updateNlpEntity } = useUpdate(EntityType.NLP_ENTITY, options);
const {
reset,
register,
formState: { errors },
handleSubmit,
} = useForm<INlpEntityAttributes>({
defaultValues: {
name: data?.name || "",
doc: data?.doc || "",
lookups: data?.lookups || ["keywords"],
},
});
const validationRules = {
name: {
required: t("message.name_is_required"),
},
lookups: {},
isChecked: {},
};
const onSubmitForm = (params: INlpEntityAttributes) => {
if (data) {
updateNlpEntity({ id: data.id, params });
} else {
createNlpEntity(params);
}
};
useEffect(() => {
if (data) {
reset({
name: data.name,
doc: data.doc,
});
} else {
reset();
}
}, [data, reset]);
return (
<Wrapper
open={!!WrapperProps?.open}
onSubmit={handleSubmit(onSubmitForm)}
{...WrapperProps}
>
<form onSubmit={handleSubmit(onSubmitForm)}>
<ContentContainer>
{!data ? (
<ContentItem>
<FormControl>
<FormLabel>{t("label.lookup_strategies")}</FormLabel>
<RadioGroup
row
{...register("lookups")}
defaultValue="keywords"
>
{Object.values(NlpLookups).map((nlpLookup, index) => (
<FormControlLabel
key={index}
value={nlpLookup}
control={<Radio {...register("lookups.0")} />}
label={nlpLookup}
/>
))}
</RadioGroup>
</FormControl>
</ContentItem>
) : null}
<ContentItem>
<Input
label={t("label.name")}
error={!!errors.name}
{...register("name", validationRules.name)}
required
autoFocus
helperText={errors.name ? errors.name.message : null}
/>
</ContentItem>
<ContentItem>
<Input
label={t("label.doc")}
{...register("doc")}
multiline={true}
/>
</ContentItem>
</ContentContainer>
</form>
</Wrapper>
);
};

View File

@ -0,0 +1,24 @@
/*
* 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 { GenericFormDialog } from "@/app-components/dialogs";
import { ComponentFormDialogProps } from "@/types/common/dialogs.types";
import { INlpEntity } from "@/types/nlp-entity.types";
import { NlpEntityVarForm } from "./NlpEntityForm";
export const NlpEntityFormDialog = <T extends INlpEntity = INlpEntity>(
props: ComponentFormDialogProps<T>,
) => (
<GenericFormDialog<T>
Form={NlpEntityVarForm}
addText="title.new_nlp_entity"
editText="title.edit_nlp_entity"
{...props}
/>
);

View File

@ -1,5 +1,5 @@
/*
* Copyright © 2024 Hexastack. All rights reserved.
* 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.
@ -15,7 +15,7 @@ import { GridColDef, GridRowSelectionModel } from "@mui/x-data-grid";
import { useRouter } from "next/router";
import { useEffect, useState } from "react";
import { DeleteDialog } from "@/app-components/dialogs";
import { ConfirmDialogBody } from "@/app-components/dialogs";
import { FilterTextfield } from "@/app-components/inputs/FilterTextfield";
import {
ActionColumnLabel,
@ -27,7 +27,7 @@ import { useDelete } from "@/hooks/crud/useDelete";
import { useDeleteMany } from "@/hooks/crud/useDeleteMany";
import { useFind } from "@/hooks/crud/useFind";
import { useGet } from "@/hooks/crud/useGet";
import { useDialog } from "@/hooks/useDialog";
import { useDialogs } from "@/hooks/useDialogs";
import { useHasPermission } from "@/hooks/useHasPermission";
import { useSearch } from "@/hooks/useSearch";
import { useToast } from "@/hooks/useToast";
@ -39,21 +39,20 @@ import { INlpValue } from "@/types/nlp-value.types";
import { PermissionAction } from "@/types/permission.types";
import { getDateTimeFormatter } from "@/utils/date";
import { NlpValueDialog } from "../NlpValueDialog";
import { NlpValueFormDialog } from "./NlpValueFormDialog";
export const NlpValues = ({ entityId }: { entityId: string }) => {
const [direction, setDirection] = useState<"up" | "down">("up");
const deleteEntityDialogCtl = useDialog<string>(false);
const editValueDialogCtl = useDialog<INlpValue>(false);
const addNlpValueDialogCtl = useDialog<INlpValue>(false);
const hasPermission = useHasPermission();
const router = useRouter();
const { t } = useTranslate();
const { toast } = useToast();
const dialogs = useDialogs();
const router = useRouter();
const [direction, setDirection] = useState<"up" | "down">("up");
const hasPermission = useHasPermission();
const { data: nlpEntity, refetch: refetchEntity } = useGet(entityId, {
entity: EntityType.NLP_ENTITY,
format: Format.FULL,
});
const canHaveSynonyms = nlpEntity?.lookups?.[0] === NlpLookups.keywords;
const { onSearch, searchPayload } = useSearch<INlpValue>({
$eq: [{ entity: entityId }],
$iLike: ["value"],
@ -64,23 +63,20 @@ export const NlpValues = ({ entityId }: { entityId: string }) => {
params: searchPayload,
},
);
const { mutateAsync: deleteNlpValue } = useDelete(EntityType.NLP_VALUE, {
onError: () => {
toast.error(t("message.internal_server_error"));
const { mutate: deleteNlpValue } = useDelete(EntityType.NLP_VALUE, {
onError: (error: Error) => {
toast.error(error.message || t("message.internal_server_error"));
},
onSuccess() {
deleteEntityDialogCtl.closeDialog();
toast.success(t("message.item_delete_success"));
refetchEntity();
toast.success(t("message.item_delete_success"));
},
});
const { mutateAsync: deleteNlpValues } = useDeleteMany(EntityType.NLP_VALUE, {
onError: (error) => {
toast.error(error);
const { mutate: deleteNlpValues } = useDeleteMany(EntityType.NLP_VALUE, {
onError: (error: Error) => {
toast.error(error.message || t("message.internal_server_error"));
},
onSuccess: () => {
deleteEntityDialogCtl.closeDialog();
setSelectedNlpValues([]);
onSuccess() {
toast.success(t("message.item_delete_success"));
},
});
@ -90,11 +86,18 @@ export const NlpValues = ({ entityId }: { entityId: string }) => {
[
{
label: ActionColumnLabel.Edit,
action: (row) => editValueDialogCtl.openDialog(row),
action: (row) =>
dialogs.open(NlpValueFormDialog, { data: row, canHaveSynonyms }),
},
{
label: ActionColumnLabel.Delete,
action: (row) => deleteEntityDialogCtl.openDialog(row.id),
action: async ({ id }) => {
const isConfirmed = await dialogs.confirm(ConfirmDialogBody);
if (isConfirmed) {
deleteNlpValue(id);
}
},
},
],
t("label.operations"),
@ -150,10 +153,19 @@ export const NlpValues = ({ entityId }: { entityId: string }) => {
return setDirection("down");
}, []);
const canHaveSynonyms = nlpEntity?.lookups?.[0] === NlpLookups.keywords;
const handleSelectionChange = (selection: GridRowSelectionModel) => {
setSelectedNlpValues(selection as string[]);
};
const handleDeleteNlpValues = async () => {
const isConfirmed = await dialogs.confirm(ConfirmDialogBody, {
mode: "selection",
count: selectedNlpValues.length,
});
if (isConfirmed) {
deleteNlpValues(selectedNlpValues);
}
};
return (
<Grid container gap={2} flexDirection="column">
@ -198,8 +210,8 @@ export const NlpValues = ({ entityId }: { entityId: string }) => {
<Button
startIcon={<AddIcon />}
variant="contained"
onClick={() => addNlpValueDialogCtl.openDialog()}
sx={{ float: "right" }}
onClick={() => dialogs.open(NlpValueFormDialog, null)}
>
{t("button.add")}
</Button>
@ -207,12 +219,10 @@ export const NlpValues = ({ entityId }: { entityId: string }) => {
{selectedNlpValues.length > 0 && (
<Grid item>
<Button
startIcon={<DeleteIcon />}
variant="contained"
color="error"
onClick={() =>
deleteEntityDialogCtl.openDialog(undefined)
}
variant="contained"
onClick={handleDeleteNlpValues}
startIcon={<DeleteIcon />}
>
{t("button.delete")}
</Button>
@ -221,30 +231,6 @@ export const NlpValues = ({ entityId }: { entityId: string }) => {
</ButtonGroup>
</Grid>
</PageHeader>
<NlpValueDialog
{...addNlpValueDialogCtl}
canHaveSynonyms={canHaveSynonyms}
callback={() => {
refetchEntity();
}}
/>
<DeleteDialog
{...deleteEntityDialogCtl}
callback={() => {
if (selectedNlpValues.length > 0) {
deleteNlpValues(selectedNlpValues);
setSelectedNlpValues([]);
deleteEntityDialogCtl.closeDialog();
} else if (deleteEntityDialogCtl.data) {
deleteNlpValue(deleteEntityDialogCtl.data);
}
}}
/>
<NlpValueDialog
{...editValueDialogCtl}
canHaveSynonyms={canHaveSynonyms}
callback={() => {}}
/>
<Grid padding={1} marginTop={2} container>
<DataGrid
columns={columns}

View File

@ -0,0 +1,125 @@
/*
* 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 { useRouter } from "next/router";
import { FC, Fragment, useEffect } from "react";
import { Controller, useForm } from "react-hook-form";
import { ContentContainer, ContentItem } from "@/app-components/dialogs/";
import { Input } from "@/app-components/inputs/Input";
import MultipleInput from "@/app-components/inputs/MultipleInput";
import { useCreate } from "@/hooks/crud/useCreate";
import { useGet } from "@/hooks/crud/useGet";
import { useUpdate } from "@/hooks/crud/useUpdate";
import { useToast } from "@/hooks/useToast";
import { useTranslate } from "@/hooks/useTranslate";
import { EntityType, Format } from "@/services/types";
import { ComponentFormProps } from "@/types/common/dialogs.types";
import { INlpValue, INlpValueAttributes } from "@/types/nlp-value.types";
export const NlpValueForm: FC<
ComponentFormProps<{ data: INlpValue; canHaveSynonyms: boolean }>
> = ({ data: props, Wrapper = Fragment, WrapperProps, ...rest }) => {
const { data, canHaveSynonyms } = props || {};
const { t } = useTranslate();
const { toast } = useToast();
const { query } = useRouter();
const { refetch: refetchEntity } = useGet(data?.entity || String(query.id), {
entity: EntityType.NLP_ENTITY,
format: Format.FULL,
});
const { mutate: createNlpValue } = useCreate(EntityType.NLP_VALUE, {
onError: () => {
rest.onError?.();
toast.error(t("message.internal_server_error"));
},
onSuccess() {
rest.onSuccess?.();
refetchEntity();
toast.success(t("message.success_save"));
},
});
const { mutate: updateNlpValue } = useUpdate(EntityType.NLP_VALUE, {
onError: () => {
rest.onError?.();
toast.error(t("message.internal_server_error"));
},
onSuccess() {
rest.onSuccess?.();
toast.success(t("message.success_save"));
},
});
const { reset, register, handleSubmit, control } = useForm<
INlpValueAttributes & {
expressions: string[];
}
>({
defaultValues: {
value: data?.value || "",
expressions: data?.expressions || [],
},
});
const validationRules = {
value: {
required: t("message.value_is_required"),
},
name: {},
description: {},
};
const onSubmitForm = async (params: INlpValueAttributes) => {
if (data) {
updateNlpValue({ id: data.id, params });
} else {
createNlpValue({ ...params, entity: String(query.id) });
}
};
useEffect(() => {
if (data) {
reset({
value: data.value,
expressions: data.expressions,
});
} else {
reset();
}
}, [data, reset]);
return (
<Wrapper
open={!!WrapperProps?.open}
onSubmit={handleSubmit(onSubmitForm)}
{...WrapperProps}
>
<form onSubmit={handleSubmit(onSubmitForm)}>
<ContentContainer>
<ContentItem>
<Input
label={t("placeholder.nlp_value")}
required
autoFocus
{...register("value", validationRules.value)}
/>
</ContentItem>
{canHaveSynonyms ? (
<ContentItem>
<Controller
name="expressions"
control={control}
render={({ field }) => (
<MultipleInput label="synonyms" {...field} />
)}
/>
</ContentItem>
) : null}
</ContentContainer>
</form>
</Wrapper>
);
};

View File

@ -0,0 +1,29 @@
/*
* 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 { GenericFormDialog } from "@/app-components/dialogs";
import { ComponentFormDialogProps } from "@/types/common/dialogs.types";
import { INlpValue } from "@/types/nlp-value.types";
import { NlpValueForm } from "./NlpValueForm";
export const NlpValueFormDialog = <
T extends { data: INlpValue; canHaveSynonyms: boolean } = {
data: INlpValue;
canHaveSynonyms: boolean;
},
>(
props: ComponentFormDialogProps<T>,
) => (
<GenericFormDialog<T>
Form={NlpValueForm}
addText="title.new_nlp_entity_value"
editText="title.edit_nlp_value"
{...props}
/>
);

View File

@ -1,11 +1,12 @@
/*
* Copyright © 2024 Hexastack. All rights reserved.
* 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 { faGraduationCap } from "@fortawesome/free-solid-svg-icons";
import { Grid, Paper, Tab, Tabs } from "@mui/material";
import dynamic from "next/dynamic";
@ -29,7 +30,7 @@ import {
import NlpDatasetCounter from "./components/NlpDatasetCounter";
import NlpSample from "./components/NlpSample";
import NlpDatasetSample from "./components/NlpTrainForm";
import { NlpValues } from "./components/NlpValues";
import { NlpValues } from "./components/NlpValue";
const NlpEntity = dynamic(() => import("./components/NlpEntity"));

View File

@ -1,146 +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 {
Button,
Dialog,
DialogActions,
DialogContent,
Grid,
} from "@mui/material";
import Link from "next/link";
import { useEffect, FC, useState } from "react";
import { Controller, 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 AutoCompleteEntitySelect from "@/app-components/inputs/AutoCompleteEntitySelect";
import { Input } from "@/app-components/inputs/Input";
import { useUpdate } from "@/hooks/crud/useUpdate";
import { DialogControlProps } from "@/hooks/useDialog";
import { useToast } from "@/hooks/useToast";
import { useTranslate } from "@/hooks/useTranslate";
import { EntityType, Format } from "@/services/types";
import { ILabel } from "@/types/label.types";
import { ISubscriber, ISubscriberAttributes } from "@/types/subscriber.types";
const getFullName = (val: ISubscriber) => `${val.first_name} ${val.last_name}`;
export type EditSubscriberDialogProps = DialogControlProps<{
labels: ILabel[];
subscriber: ISubscriber;
}>;
export const EditSubscriberDialog: FC<EditSubscriberDialogProps> = ({
open,
data,
closeDialog,
...rest
}) => {
const { t } = useTranslate();
const { toast } = useToast();
const [fullName, setFullName] = useState<string>("");
const { mutateAsync: updateSubscriber } = useUpdate(EntityType.SUBSCRIBER, {
onError: () => {
toast.error(t("message.internal_server_error"));
},
onSuccess() {
closeDialog();
toast.success(t("message.success_save"));
},
});
const {
reset,
control,
formState: { errors },
handleSubmit,
} = useForm<ISubscriberAttributes>();
const validationRules = {
labels: {},
};
const onSubmitForm = async (params: ISubscriberAttributes) => {
if (data?.subscriber.id)
updateSubscriber({ id: data?.subscriber.id, params });
};
useEffect(() => {
if (data?.subscriber) setFullName(getFullName(data?.subscriber));
if (open) {
reset({ labels: data?.subscriber?.labels });
}
}, [open, reset, data]);
return (
<Dialog open={open} fullWidth onClose={closeDialog} {...rest}>
<form onSubmit={handleSubmit(onSubmitForm)}>
<DialogTitle onClose={closeDialog}>
{t("title.manage_labels")}
</DialogTitle>
<DialogContent>
<ContentContainer>
<ContentItem>
<Input
label={t("label.auth_user")}
disabled
InputProps={{
readOnly: true,
}}
value={fullName}
/>
</ContentItem>
<ContentItem>
<Grid container gap="20px">
<Grid item xs>
<Controller
name="labels"
rules={validationRules.labels}
control={control}
render={({ field }) => {
const { onChange, ...rest } = field;
return (
<AutoCompleteEntitySelect<ILabel>
autoFocus
searchFields={["name"]}
entity={EntityType.LABEL}
format={Format.BASIC}
labelKey="name"
label={t("label.labels")}
multiple
{...field}
error={!!errors.labels}
helperText={
errors.labels ? errors.labels.message : null
}
onChange={(_e, selected) =>
onChange(selected.map(({ id }) => id))
}
{...rest}
/>
);
}}
/>
</Grid>
<Grid alignContent="center">
<Link href="/subscribers/labels">
<Button variant="contained">{t("button.manage")}</Button>
</Link>
</Grid>
</Grid>
</ContentItem>
</ContentContainer>
</DialogContent>
<DialogActions>
<DialogButtons closeDialog={closeDialog} />
</DialogActions>
</form>
</Dialog>
);
};

View File

@ -0,0 +1,124 @@
/*
* 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, Grid, Link } from "@mui/material";
import { FC, Fragment, useEffect } 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 { useUpdate } from "@/hooks/crud/useUpdate";
import { useToast } from "@/hooks/useToast";
import { useTranslate } from "@/hooks/useTranslate";
import { EntityType, Format } from "@/services/types";
import { ComponentFormProps } from "@/types/common/dialogs.types";
import { ILabel } from "@/types/label.types";
import { ISubscriber, ISubscriberAttributes } from "@/types/subscriber.types";
const getFullName = (subscriber: ISubscriber | null) =>
`${subscriber?.first_name} ${subscriber?.last_name}`;
export const SubscriberForm: FC<ComponentFormProps<ISubscriber>> = ({
data,
Wrapper = Fragment,
WrapperProps,
...rest
}) => {
const { t } = useTranslate();
const { toast } = useToast();
const { mutate: updateSubscriber } = useUpdate(EntityType.SUBSCRIBER, {
onError: () => {
rest.onError?.();
toast.error(t("message.internal_server_error"));
},
onSuccess() {
rest.onSuccess?.();
toast.success(t("message.success_save"));
},
});
const {
reset,
control,
formState: { errors },
handleSubmit,
} = useForm<ISubscriberAttributes>();
const onSubmitForm = (params: ISubscriberAttributes) => {
if (data?.id) {
updateSubscriber({ id: data.id, params });
}
};
useEffect(() => {
if (data) {
reset({ labels: data?.labels });
}
}, [data, reset]);
return (
<Wrapper
open={!!WrapperProps?.open}
onSubmit={handleSubmit(onSubmitForm)}
{...WrapperProps}
>
<form onSubmit={handleSubmit(onSubmitForm)}>
<ContentContainer>
<ContentItem>
<Input
label={t("label.user")}
value={getFullName(data)}
disabled
InputProps={{
readOnly: true,
}}
/>
</ContentItem>
<ContentItem>
<Grid container gap="20px">
<Grid item xs>
<Controller
name="labels"
render={({ field }) => {
const { onChange, ...rest } = field;
return (
<AutoCompleteEntitySelect<ILabel>
autoFocus
searchFields={["name"]}
entity={EntityType.LABEL}
format={Format.BASIC}
labelKey="name"
label={t("label.labels")}
multiple
{...field}
error={!!errors.labels}
helperText={
errors.labels ? errors.labels.message : null
}
onChange={(_e, selected) =>
onChange(selected.map(({ id }) => id))
}
{...rest}
/>
);
}}
control={control}
/>
</Grid>
<Grid alignContent="center">
<Link href="/subscribers/labels">
<Button variant="contained">{t("button.manage")}</Button>
</Link>
</Grid>
</Grid>
</ContentItem>
</ContentContainer>
</form>
</Wrapper>
);
};

View File

@ -0,0 +1,23 @@
/*
* 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 { GenericFormDialog } from "@/app-components/dialogs";
import { ComponentFormDialogProps } from "@/types/common/dialogs.types";
import { ISubscriber } from "@/types/subscriber.types";
import { SubscriberForm } from "./SubscriberForm";
export const SubscriberFormDialog = <T extends ISubscriber = ISubscriber>(
props: ComponentFormDialogProps<T>,
) => (
<GenericFormDialog<T>
Form={SubscriberForm}
editText="title.manage_subscribers"
{...props}
/>
);

View File

@ -10,7 +10,7 @@ import AccountCircleIcon from "@mui/icons-material/AccountCircle";
import DeleteIcon from "@mui/icons-material/Close";
import { Grid, IconButton, MenuItem, Paper } from "@mui/material";
import { GridColDef } from "@mui/x-data-grid";
import React, { useState } from "react";
import { useState } from "react";
import { ChipEntity } from "@/app-components/displays/ChipEntity";
import { FilterTextfield } from "@/app-components/inputs/FilterTextfield";
@ -23,23 +23,19 @@ import { renderHeader } from "@/app-components/tables/columns/renderHeader";
import { buildRenderPicture } from "@/app-components/tables/columns/renderPicture";
import { DataGrid } from "@/app-components/tables/DataGrid";
import { useFind } from "@/hooks/crud/useFind";
import { getDisplayDialogs, useDialog } from "@/hooks/useDialog";
import { useDialogs } from "@/hooks/useDialogs";
import { useSearch } from "@/hooks/useSearch";
import { useTranslate } from "@/hooks/useTranslate";
import { PageHeader } from "@/layout/content/PageHeader";
import { EntityType, Format } from "@/services/types";
import { ILabel } from "@/types/label.types";
import { ISubscriber } from "@/types/subscriber.types";
import { getDateTimeFormatter } from "@/utils/date";
import { EditSubscriberDialog } from "./EditSubscriberDialog";
import { SubscriberFormDialog } from "./SubscriberFormDialog";
export const Subscribers = () => {
const { t } = useTranslate();
const editDialogCtl = useDialog<{
labels: ILabel[];
subscriber: ISubscriber;
}>(false);
const dialogs = useDialogs();
const { data: labels } = useFind(
{
entity: EntityType.LABEL,
@ -155,11 +151,7 @@ export const Subscribers = () => {
[
{
label: ActionColumnLabel.Manage_Labels,
action: (row) =>
editDialogCtl.openDialog({
labels: labels || [],
subscriber: row,
}),
action: (row) => dialogs.open(SubscriberFormDialog, row),
},
],
t("label.operations"),
@ -168,7 +160,6 @@ export const Subscribers = () => {
return (
<Grid container gap={3} flexDirection="column">
<EditSubscriberDialog {...getDisplayDialogs(editDialogCtl)} />
<PageHeader icon={AccountCircleIcon} title={t("title.subscribers")}>
<Grid
justifyContent="flex-end"

View File

@ -1,153 +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 {
Button,
Dialog,
DialogActions,
DialogContent,
Grid,
} from "@mui/material";
import Link from "next/link";
import { FC, useEffect, useState } from "react";
import { Controller, 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 AutoCompleteEntitySelect from "@/app-components/inputs/AutoCompleteEntitySelect";
import { Input } from "@/app-components/inputs/Input";
import { useUpdate } from "@/hooks/crud/useUpdate";
import { DialogControlProps } from "@/hooks/useDialog";
import { useToast } from "@/hooks/useToast";
import { useTranslate } from "@/hooks/useTranslate";
import { EntityType, Format } from "@/services/types";
import { IRole } from "@/types/role.types";
import { IUser, IUserAttributes } from "@/types/user.types";
const getFullName = (val: IUser) => `${val.first_name} ${val.last_name}`;
export type EditUserDialogProps = DialogControlProps<{
user: IUser;
roles: IRole[];
}>;
export const EditUserDialog: FC<EditUserDialogProps> = ({
open,
data,
closeDialog,
...rest
}) => {
const { t } = useTranslate();
const { toast } = useToast();
const [fullName, setFullName] = useState<string>("");
const { mutateAsync: updateUser } = useUpdate(EntityType.USER, {
onError: (error) => {
toast.error(error.message || t("message.internal_server_error"));
},
onSuccess() {
closeDialog();
toast.success(t("message.success_save"));
},
});
const {
handleSubmit,
control,
reset,
formState: { errors },
} = useForm<IUserAttributes>({
defaultValues: { roles: data?.roles.map((role) => role.id) },
});
const validationRules = {
roles: {
required: t("message.roles_is_required"),
},
};
const onSubmitForm = async (params: IUserAttributes) => {
if (data?.user.id)
updateUser({
id: data.user.id,
params,
});
};
useEffect(() => {
if (data?.user) setFullName(getFullName(data?.user));
if (open) reset({ roles: data?.user?.roles });
}, [open, reset, data]);
return (
<Dialog open={open} fullWidth onClose={closeDialog} {...rest}>
<form onSubmit={handleSubmit(onSubmitForm)}>
<DialogTitle onClose={closeDialog}>
{t("title.manage_roles")}
</DialogTitle>
<DialogContent>
<ContentContainer>
<ContentItem>
<Input
disabled
label={t("label.auth_user")}
value={fullName}
InputProps={{
readOnly: true,
}}
/>
</ContentItem>
<ContentItem>
<Grid container gap={3}>
<Grid item xs>
<Controller
name="roles"
rules={validationRules.roles}
control={control}
defaultValue={data?.roles?.map(({ id }) => id) || []}
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}
/>
);
}}
/>
</Grid>
<Grid alignContent="center">
<Link href="/roles">
<Button variant="contained">{t("button.manage")}</Button>
</Link>
</Grid>
</Grid>
</ContentItem>
</ContentContainer>
</DialogContent>
<DialogActions>
<DialogButtons closeDialog={closeDialog} />
</DialogActions>
</form>
</Dialog>
);
};

View File

@ -0,0 +1,137 @@
/*
* 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, Grid, Link } from "@mui/material";
import { FC, Fragment, useEffect } 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 { useUpdate } from "@/hooks/crud/useUpdate";
import { useToast } from "@/hooks/useToast";
import { useTranslate } from "@/hooks/useTranslate";
import { EntityType, Format } from "@/services/types";
import { ComponentFormProps } from "@/types/common/dialogs.types";
import { IRole } from "@/types/role.types";
import { IUser, IUserAttributes } from "@/types/user.types";
const getFullName = (user?: IUser) => `${user?.first_name} ${user?.last_name}`;
export type EditUserFormData = {
user: IUser;
roles: IRole[];
};
export const EditUserForm: FC<ComponentFormProps<EditUserFormData>> = ({
data,
Wrapper = Fragment,
WrapperProps,
...rest
}) => {
const { t } = useTranslate();
const { toast } = useToast();
const { mutate: updateUser } = useUpdate(EntityType.USER, {
onError: (error) => {
rest.onError?.();
toast.error(error.message || t("message.internal_server_error"));
},
onSuccess() {
rest.onSuccess?.();
toast.success(t("message.success_save"));
},
});
const {
reset,
control,
formState: { errors },
handleSubmit,
} = useForm<IUserAttributes>({
defaultValues: { roles: data?.roles.map((role) => role.id) },
});
const validationRules = {
roles: {
required: t("message.roles_is_required"),
},
};
const onSubmitForm = (params: IUserAttributes) => {
if (data?.user.id) {
updateUser({
id: data.user.id,
params,
});
}
};
useEffect(() => {
if (data?.user) {
reset({ roles: data?.user?.roles });
}
}, [reset, data?.user]);
return (
<Wrapper
open={!!WrapperProps?.open}
onSubmit={handleSubmit(onSubmitForm)}
{...WrapperProps}
>
<form onSubmit={handleSubmit(onSubmitForm)}>
<ContentContainer>
<ContentItem>
<Input
disabled
label={t("label.auth_user")}
value={getFullName(data?.user)}
InputProps={{
readOnly: true,
}}
/>
</ContentItem>
<ContentItem>
<Grid container gap={3}>
<Grid item xs>
<Controller
name="roles"
rules={validationRules.roles}
control={control}
defaultValue={data?.roles?.map(({ id }) => id) || []}
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}
/>
);
}}
/>
</Grid>
<Grid alignContent="center">
<Link href="/roles">
<Button variant="contained">{t("button.manage")}</Button>
</Link>
</Grid>
</Grid>
</ContentItem>
</ContentContainer>
</form>
</Wrapper>
);
};

View File

@ -0,0 +1,24 @@
/*
* 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 { GenericFormDialog } from "@/app-components/dialogs";
import { ComponentFormDialogProps } from "@/types/common/dialogs.types";
import { EditUserForm, EditUserFormData } from "./EditUserForm";
export const CategoryFormDialog = <
T extends EditUserFormData = EditUserFormData,
>(
props: ComponentFormDialogProps<T>,
) => (
<GenericFormDialog<T>
Form={EditUserForm}
editText="title.manage_roles"
{...props}
/>
);

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,115 @@
/*
* 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 { mutate: 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 = (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

@ -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 DialogExtraOptions {
@ -26,6 +26,8 @@ export interface OpenDialogOptions<R> extends DialogExtraOptions {
* @returns A promise that resolves when the dialog can be closed.
*/
onClose?: (result: R) => Promise<void>;
onSubmit?: (e: BaseSyntheticEvent) => void;
}
/**
@ -49,6 +51,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>>;
@ -144,24 +148,28 @@ export interface DialogProviderProps {
}
// form dialog
export interface FormDialogProps extends MuiDialogProps, DialogExtraOptions {
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>;