Files
Crm-Frontend/src/app/modules/hooks/useModulesActions.tsx
2025-10-25 18:05:49 +04:00

87 lines
2.5 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import React from "react";
import { redirect } from "next/navigation";
import { useMutation } from "@tanstack/react-query";
import { AxiosError } from "axios";
import { Text } from "@mantine/core";
import { modals } from "@mantine/modals";
import { HttpValidationError, ModuleSchemaOutput } from "@/lib/client";
import {
createModuleMutation,
deleteModuleMutation,
} from "@/lib/client/@tanstack/react-query.gen";
import { notifications } from "@/lib/notifications";
export type ModulesActions = {
onCreate: () => void;
onUpdate: (module: ModuleSchemaOutput) => void;
onDelete: (module: ModuleSchemaOutput) => void;
};
type Props = {
refetchModules: () => void;
};
const useModulesActions = ({ refetchModules }: Props): ModulesActions => {
const onError = (error: AxiosError<HttpValidationError>, _: any) => {
console.error(error);
notifications.error({
message: error.response?.data?.detail as string | undefined,
});
};
const createMutation = useMutation({
...createModuleMutation(),
onError,
});
const onCreate = () => {
modals.openContextModal({
modal: "moduleCreatorModal",
title: "Создание модуля",
innerProps: {
onCreate: (data, onSuccess) =>
createMutation.mutate(
{ body: { entity: data } },
{
onSuccess: () => {
refetchModules();
onSuccess && onSuccess();
},
}
),
},
});
};
const onUpdate = (module: ModuleSchemaOutput) => {
redirect(`/module-editor/${module.id}`);
};
const deleteMutation = useMutation({
...deleteModuleMutation(),
onError,
onSuccess: refetchModules,
});
const onDelete = (module: ModuleSchemaOutput) => {
modals.openConfirmModal({
title: "Удаление модуля",
children: (
<Text>
Вы уверены, что хотите удалить модуль "{module.label}"?
</Text>
),
confirmProps: { color: "red" },
onConfirm: () => deleteMutation.mutate({ path: { pk: module.id } }),
});
};
return {
onCreate,
onUpdate,
onDelete,
};
};
export default useModulesActions;