diff --git a/apps/app/components/estimates/create-update-estimate-modal.tsx b/apps/app/components/estimates/create-update-estimate-modal.tsx new file mode 100644 index 000000000..da127a455 --- /dev/null +++ b/apps/app/components/estimates/create-update-estimate-modal.tsx @@ -0,0 +1,205 @@ +import React, { useEffect } from "react"; + +import { useRouter } from "next/router"; + +import { mutate } from "swr"; + +// react-hook-form +import { useForm } from "react-hook-form"; +// services +import estimatesService from "services/estimates.service"; +// ui +import { Input, PrimaryButton, SecondaryButton, TextArea } from "components/ui"; +import { Dialog, Transition } from "@headlessui/react"; + +// hooks +import useToast from "hooks/use-toast"; + +// types +import { IEstimate } from "types"; +// fetch-keys +import { ESTIMATES_LIST } from "constants/fetch-keys"; + +type Props = { + handleClose: () => void; + data?: IEstimate; + isOpen: boolean; + isCreate: boolean; +}; + +const defaultValues: Partial = { + name: "", + description: "", +}; + +export const CreateUpdateEstimateModal: React.FC = ({ handleClose, data, isOpen, isCreate }) => { + const { + register, + formState: { errors, isSubmitting }, + handleSubmit, + reset, + } = useForm({ + defaultValues, + }); + + const router = useRouter(); + const { workspaceSlug, projectId } = router.query; + + const { setToastAlert } = useToast(); + + const createEstimate = async (formData: IEstimate) => { + if (!workspaceSlug || !projectId) return; + + const payload = { + name: formData.name, + description: formData.description, + }; + + await estimatesService + .createEstimate(workspaceSlug as string, projectId as string, payload) + .then((res) => { + mutate( + ESTIMATES_LIST(projectId as string), + (prevData) => [res, ...(prevData ?? [])], + false + ); + handleClose(); + }) + .catch(() => { + setToastAlert({ + type: "error", + title: "Error!", + message: "Error: Estimate could not be created", + }); + }); + }; + + const updateEstimate = async (formData: IEstimate) => { + if (!workspaceSlug || !projectId || !data) return; + + const payload = { + name: formData.name, + description: formData.description, + }; + + mutate( + ESTIMATES_LIST(projectId as string), + (prevData) => + prevData?.map((p) => { + if (p.id === data.id) return { ...p, ...payload }; + + return p; + }), + false + ); + + await estimatesService + .patchEstimate(workspaceSlug as string, projectId as string, data?.id as string, payload) + .then(() => { + handleClose(); + }) + .catch(() => { + setToastAlert({ + type: "error", + title: "Error!", + message: "Error: Estimate could not be updated", + }); + }); + handleClose(); + }; + + useEffect(() => { + if (!data && isCreate) return; + reset({ + ...defaultValues, + ...data, + }); + }, [data, reset, isCreate]); + + return ( + <> + + + +
+ + +
+
+ + +
+
+
Create Estimate
+
+ +
+
+