import React, { useEffect } from "react"; import { useRouter } from "next/router"; import { mutate } from "swr"; // react-hook-form import { Controller, useForm } from "react-hook-form"; // headless ui import { Dialog, Transition } from "@headlessui/react"; // components import SelectLead from "components/project/modules/create-update-module-modal/select-lead"; import SelectMembers from "components/project/modules/create-update-module-modal/select-members"; import SelectStatus from "components/project/modules/create-update-module-modal/select-status"; // ui import { Button, CustomDatePicker, Input, TextArea } from "components/ui"; // services import modulesService from "services/modules.service"; // hooks import useToast from "hooks/use-toast"; // helpers import { renderDateFormat } from "helpers/date-time.helper"; // types import type { IModule } from "types"; // fetch-keys import { MODULE_LIST } from "constants/fetch-keys"; type Props = { isOpen: boolean; setIsOpen: React.Dispatch>; projectId: string; data?: IModule; }; const defaultValues: Partial = { name: "", description: "", status: null, lead: null, members_list: [], }; const CreateUpdateModuleModal: React.FC = ({ isOpen, setIsOpen, data, projectId }) => { const router = useRouter(); const { workspaceSlug } = router.query; const { setToastAlert } = useToast(); const { register, formState: { errors, isSubmitting }, handleSubmit, control, reset, setError, } = useForm({ defaultValues, }); const onSubmit = async (formData: IModule) => { if (!workspaceSlug) return; const payload = { ...formData, start_date: formData.start_date ? renderDateFormat(formData.start_date) : null, target_date: formData.target_date ? renderDateFormat(formData.target_date) : null, }; if (!data) { await modulesService .createModule(workspaceSlug as string, projectId, payload) .then(() => { mutate(MODULE_LIST(projectId)); handleClose(); setToastAlert({ title: "Success", type: "success", message: "Module created successfully", }); }) .catch((err) => { Object.keys(err).map((key) => { setError(key as keyof typeof defaultValues, { message: err[key].join(", "), }); }); }); } else { await modulesService .updateModule(workspaceSlug as string, projectId, data.id, payload) .then((res) => { mutate( MODULE_LIST(projectId), (prevData) => { const newData = prevData?.map((item) => { if (item.id === res.id) { return res; } return item; }); return newData; }, false ); handleClose(); setToastAlert({ title: "Success", type: "success", message: "Module updated successfully", }); }) .catch((err) => { Object.keys(err).map((key) => { setError(key as keyof typeof defaultValues, { message: err[key].join(", "), }); }); }); } }; const handleClose = () => { setIsOpen(false); reset(defaultValues); }; useEffect(() => { if (data) { setIsOpen(true); reset(data); } else { reset(defaultValues); } }, [data, setIsOpen, reset]); return (
{data ? "Update" : "Create"} Module