import React, { useEffect, useState } from "react"; import { useRouter } from "next/router"; import { mutate } from "swr"; // react-hook-form import { Controller, useForm } from "react-hook-form"; // icons import { ArrowLongRightIcon, CalendarDaysIcon, ChartPieIcon, ChevronDownIcon, DocumentIcon, PlusIcon, TrashIcon, } from "@heroicons/react/24/outline"; import { Disclosure, Popover, Transition } from "@headlessui/react"; import DatePicker from "react-datepicker"; // services import modulesService from "services/modules.service"; // contexts import { useProjectMyMembership } from "contexts/project-member.context"; // hooks import useToast from "hooks/use-toast"; // components import { LinkModal, LinksList, SidebarProgressStats } from "components/core"; import { DeleteModuleModal, SidebarLeadSelect, SidebarMembersSelect } from "components/modules"; import ProgressChart from "components/core/sidebar/progress-chart"; import { CustomMenu, CustomSelect, Loader, ProgressBar } from "components/ui"; // icon import { ExclamationIcon } from "components/icons"; import { LinkIcon } from "@heroicons/react/20/solid"; // helpers import { renderDateFormat, renderShortDate } from "helpers/date-time.helper"; import { capitalizeFirstLetter, copyTextToClipboard } from "helpers/string.helper"; // types import { ICurrentUserResponse, IIssue, IModule, ModuleLink } from "types"; // fetch-keys import { MODULE_DETAILS } from "constants/fetch-keys"; // constant import { MODULE_STATUS } from "constants/module"; const defaultValues: Partial = { lead: "", members_list: [], start_date: null, target_date: null, status: null, }; type Props = { module?: IModule; isOpen: boolean; moduleIssues?: IIssue[]; user: ICurrentUserResponse | undefined; }; export const ModuleDetailsSidebar: React.FC = ({ module, isOpen, moduleIssues, user }) => { const [moduleDeleteModal, setModuleDeleteModal] = useState(false); const [moduleLinkModal, setModuleLinkModal] = useState(false); const router = useRouter(); const { workspaceSlug, projectId, moduleId } = router.query; const { memberRole } = useProjectMyMembership(); const { setToastAlert } = useToast(); const { reset, watch, control } = useForm({ defaultValues, }); const submitChanges = (data: Partial) => { if (!workspaceSlug || !projectId || !moduleId) return; mutate( MODULE_DETAILS(moduleId as string), (prevData) => ({ ...(prevData as IModule), ...data, }), false ); modulesService .patchModule(workspaceSlug as string, projectId as string, moduleId as string, data, user) .then(() => mutate(MODULE_DETAILS(moduleId as string))) .catch((e) => console.log(e)); }; const handleCreateLink = async (formData: ModuleLink) => { if (!workspaceSlug || !projectId || !moduleId) return; const payload = { metadata: {}, ...formData }; await modulesService .createModuleLink(workspaceSlug as string, projectId as string, moduleId as string, payload) .then(() => mutate(MODULE_DETAILS(moduleId as string))) .catch((err) => { if (err.status === 400) setToastAlert({ type: "error", title: "Error!", message: "This URL already exists for this module.", }); else setToastAlert({ type: "error", title: "Error!", message: "Something went wrong. Please try again.", }); }); }; const handleDeleteLink = async (linkId: string) => { if (!workspaceSlug || !projectId || !module) return; const updatedLinks = module.link_module.filter((l) => l.id !== linkId); mutate( MODULE_DETAILS(module.id), (prevData) => ({ ...(prevData as IModule), link_module: updatedLinks }), false ); await modulesService .deleteModuleLink(workspaceSlug as string, projectId as string, module.id, linkId) .then((res) => { mutate(MODULE_DETAILS(module.id)); }) .catch((err) => { console.log(err); }); }; const handleCopyText = () => { const originURL = typeof window !== "undefined" && window.location.origin ? window.location.origin : ""; copyTextToClipboard(`${workspaceSlug}/projects/${projectId}/modules/${module?.id}`) .then(() => { setToastAlert({ type: "success", title: "Module link copied to clipboard", }); }) .catch(() => { setToastAlert({ type: "error", title: "Some error occurred", }); }); }; useEffect(() => { if (module) reset({ ...module, members_list: module.members_list ?? module.members_detail?.map((m) => m.id), }); }, [module, reset]); const isStartValid = new Date(`${module?.start_date}`) <= new Date(); const isEndValid = new Date(`${module?.target_date}`) >= new Date(`${module?.start_date}`); const progressPercentage = module ? Math.round((module.completed_issues / module.total_issues) * 100) : null; return ( <> setModuleLinkModal(false)} onFormSubmit={handleCreateLink} />
{module ? ( <>
( {capitalizeFirstLetter(`${watch("status")}`)} } value={value} onChange={(value: any) => { submitChanges({ status: value }); }} > {MODULE_STATUS.map((option) => ( {option.label} ))} )} />
{({ open }) => ( <> {renderShortDate(new Date(`${module.start_date}`), "Start date")} { submitChanges({ start_date: renderDateFormat(date), }); }} selectsStart startDate={new Date(`${watch("start_date")}`)} endDate={new Date(`${watch("target_date")}`)} maxDate={new Date(`${watch("target_date")}`)} shouldCloseOnSelect inline /> )} {({ open }) => ( <> {renderShortDate(new Date(`${module?.target_date}`), "End date")} { submitChanges({ target_date: renderDateFormat(date), }); }} selectsEnd startDate={new Date(`${watch("start_date")}`)} endDate={new Date(`${watch("target_date")}`)} minDate={new Date(`${watch("start_date")}`)} shouldCloseOnSelect inline /> )}

{module.name}

setModuleDeleteModal(true)}> Delete Copy link
{module.description}
( { submitChanges({ lead: val }); }} /> )} /> ( { submitChanges({ members_list: val }); }} /> )} />
Progress
{module.completed_issues}/{module.total_issues}
{({ open }) => (
Progress {!open && moduleIssues && progressPercentage ? ( {progressPercentage ? `${progressPercentage}%` : ""} ) : ( "" )}
{isStartValid && isEndValid ? ( ) : (
Invalid date. Please enter valid date.
)}
{isStartValid && isEndValid && moduleIssues ? (
Pending Issues -{" "} {module.total_issues - (module.completed_issues + module.cancelled_issues)}{" "}
Ideal
Current
) : ( "" )}
)}
{({ open }) => (
Other Information
{module.total_issues > 0 ? ( ) : (
No issues found. Please add issue.
)}
{module.total_issues > 0 ? ( <>
) : ( "" )}
)}

Links

{memberRole && module.link_module && module.link_module.length > 0 ? ( ) : null}
) : (
)}
); };