import React, { useEffect, useState } from "react"; import { useRouter } from "next/router"; import { observer } from "mobx-react-lite"; import { mutate } from "swr"; import { useForm } from "react-hook-form"; import { Disclosure, Popover, Transition } from "@headlessui/react"; // mobx store import { useMobxStore } from "lib/mobx/store-provider"; // services import { CycleService } from "services/cycle.service"; // hooks import useToast from "hooks/use-toast"; // components import { SidebarProgressStats } from "components/core"; import ProgressChart from "components/core/sidebar/progress-chart"; import { CycleDeleteModal } from "components/cycles/delete-modal"; // ui import { CustomRangeDatePicker } from "components/ui"; import { Avatar, CustomMenu, Loader, LayersIcon } from "@plane/ui"; // icons import { ChevronDown, LinkIcon, Trash2, UserCircle2, AlertCircle, ChevronRight, MoveRight } from "lucide-react"; // helpers import { copyUrlToClipboard } from "helpers/string.helper"; import { findHowManyDaysLeft, getDateRangeStatus, isDateGreaterThanToday, renderDateFormat, renderShortDate, renderShortMonthDate, } from "helpers/date-time.helper"; // types import { ICycle } from "types"; // fetch-keys import { CYCLE_DETAILS } from "constants/fetch-keys"; import { CYCLE_STATUS } from "constants/cycle"; type Props = { cycleId: string; handleClose: () => void; }; // services const cycleService = new CycleService(); // TODO: refactor the whole component export const CycleDetailsSidebar: React.FC = observer((props) => { const { cycleId, handleClose } = props; const [cycleDeleteModal, setCycleDeleteModal] = useState(false); const router = useRouter(); const { workspaceSlug, projectId, peekCycle } = router.query; const { cycle: cycleDetailsStore } = useMobxStore(); const cycleDetails = cycleDetailsStore.cycle_details[cycleId] ?? undefined; const { setToastAlert } = useToast(); const defaultValues: Partial = { start_date: new Date().toString(), end_date: new Date().toString(), }; const { setValue, reset, watch } = useForm({ defaultValues, }); const submitChanges = (data: Partial) => { if (!workspaceSlug || !projectId || !cycleId) return; mutate(CYCLE_DETAILS(cycleId as string), (prevData) => ({ ...(prevData as ICycle), ...data }), false); cycleService .patchCycle(workspaceSlug as string, projectId as string, cycleId as string, data) .then(() => mutate(CYCLE_DETAILS(cycleId as string))) .catch((e) => console.log(e)); }; const handleCopyText = () => { copyUrlToClipboard(`${workspaceSlug}/projects/${projectId}/cycles/${cycleId}`) .then(() => { setToastAlert({ type: "success", title: "Cycle link copied to clipboard", }); }) .catch(() => { setToastAlert({ type: "error", title: "Some error occurred", }); }); }; useEffect(() => { if (cycleDetails) reset({ ...cycleDetails, }); }, [cycleDetails, reset]); const dateChecker = async (payload: any) => { try { const res = await cycleService.cycleDateCheck(workspaceSlug as string, projectId as string, payload); return res.status; } catch (err) { return false; } }; const handleStartDateChange = async (date: string) => { setValue("start_date", date); if (watch("start_date") && watch("end_date") && watch("start_date") !== "" && watch("start_date") !== "") { if (!isDateGreaterThanToday(`${watch("end_date")}`)) { setToastAlert({ type: "error", title: "Error!", message: "Unable to create cycle in past date. Please enter a valid date.", }); return; } if (cycleDetails?.start_date && cycleDetails?.end_date) { const isDateValidForExistingCycle = await dateChecker({ start_date: `${watch("start_date")}`, end_date: `${watch("end_date")}`, cycle_id: cycleDetails.id, }); if (isDateValidForExistingCycle) { submitChanges({ start_date: renderDateFormat(`${watch("start_date")}`), end_date: renderDateFormat(`${watch("end_date")}`), }); setToastAlert({ type: "success", title: "Success!", message: "Cycle updated successfully.", }); return; } else { setToastAlert({ type: "error", title: "Error!", message: "You have a cycle already on the given dates, if you want to create your draft cycle you can do that by removing dates", }); return; } } const isDateValid = await dateChecker({ start_date: `${watch("start_date")}`, end_date: `${watch("end_date")}`, }); if (isDateValid) { submitChanges({ start_date: renderDateFormat(`${watch("start_date")}`), end_date: renderDateFormat(`${watch("end_date")}`), }); setToastAlert({ type: "success", title: "Success!", message: "Cycle updated successfully.", }); } else { setToastAlert({ type: "error", title: "Error!", message: "You have a cycle already on the given dates, if you want to create your draft cycle you can do that by removing dates", }); } } }; const handleEndDateChange = async (date: string) => { setValue("end_date", date); if (watch("start_date") && watch("end_date") && watch("start_date") !== "" && watch("start_date") !== "") { if (!isDateGreaterThanToday(`${watch("end_date")}`)) { setToastAlert({ type: "error", title: "Error!", message: "Unable to create cycle in past date. Please enter a valid date.", }); return; } if (cycleDetails?.start_date && cycleDetails?.end_date) { const isDateValidForExistingCycle = await dateChecker({ start_date: `${watch("start_date")}`, end_date: `${watch("end_date")}`, cycle_id: cycleDetails.id, }); if (isDateValidForExistingCycle) { submitChanges({ start_date: renderDateFormat(`${watch("start_date")}`), end_date: renderDateFormat(`${watch("end_date")}`), }); setToastAlert({ type: "success", title: "Success!", message: "Cycle updated successfully.", }); return; } else { setToastAlert({ type: "error", title: "Error!", message: "You have a cycle already on the given dates, if you want to create your draft cycle you can do that by removing dates", }); return; } } const isDateValid = await dateChecker({ start_date: `${watch("start_date")}`, end_date: `${watch("end_date")}`, }); if (isDateValid) { submitChanges({ start_date: renderDateFormat(`${watch("start_date")}`), end_date: renderDateFormat(`${watch("end_date")}`), }); setToastAlert({ type: "success", title: "Success!", message: "Cycle updated successfully.", }); } else { setToastAlert({ type: "error", title: "Error!", message: "You have a cycle already on the given dates, if you want to create your draft cycle you can do that by removing dates", }); } } }; const cycleStatus = cycleDetails?.start_date && cycleDetails?.end_date ? getDateRangeStatus(cycleDetails?.start_date, cycleDetails?.end_date) : "draft"; const isCompleted = cycleStatus === "completed"; const isStartValid = new Date(`${cycleDetails?.start_date}`) <= new Date(); const isEndValid = new Date(`${cycleDetails?.end_date}`) >= new Date(`${cycleDetails?.start_date}`); const progressPercentage = cycleDetails ? Math.round((cycleDetails.completed_issues / cycleDetails.total_issues) * 100) : null; if (!cycleDetails) return (
); const endDate = new Date(cycleDetails.end_date ?? ""); const startDate = new Date(cycleDetails.start_date ?? ""); const areYearsEqual = startDate.getFullYear() === endDate.getFullYear(); const currentCycle = CYCLE_STATUS.find((status) => status.value === cycleStatus); const issueCount = cycleDetails.total_issues === 0 ? "0 Issue" : cycleDetails.total_issues === cycleDetails.completed_issues ? cycleDetails.total_issues > 1 ? `${cycleDetails.total_issues}` : `${cycleDetails.total_issues}` : `${cycleDetails.completed_issues}/${cycleDetails.total_issues}`; return ( <> {cycleDetails && workspaceSlug && projectId && ( setCycleDeleteModal(false)} workspaceSlug={workspaceSlug.toString()} projectId={projectId.toString()} /> )} <>
{!isCompleted && ( setCycleDeleteModal(true)}> Delete cycle )}

{cycleDetails.name}

{currentCycle && ( {currentCycle.value === "current" ? `${findHowManyDaysLeft(cycleDetails.end_date ?? new Date())} ${currentCycle.label}` : `${currentCycle.label}`} )}
{areYearsEqual ? renderShortDate(startDate, "_ _") : renderShortMonthDate(startDate, "_ _")} { if (val) { handleStartDateChange(val); } }} startDate={watch("start_date") ? `${watch("start_date")}` : null} endDate={watch("end_date") ? `${watch("end_date")}` : null} maxDate={new Date(`${watch("end_date")}`)} selectsStart /> <> {areYearsEqual ? renderShortDate(endDate, "_ _") : renderShortMonthDate(endDate, "_ _")} { if (val) { handleEndDateChange(val); } }} startDate={watch("start_date") ? `${watch("start_date")}` : null} endDate={watch("end_date") ? `${watch("end_date")}` : null} minDate={new Date(`${watch("start_date")}`)} selectsEnd />
{cycleDetails.description && ( {cycleDetails.description} )}
Lead
{cycleDetails.owned_by.display_name}
Issues
{issueCount}
{({ open }) => (
Progress
{progressPercentage ? ( {progressPercentage ? `${progressPercentage}%` : ""} ) : ( "" )} {isStartValid && isEndValid ? (
{isStartValid && isEndValid ? (
Ideal
Current
) : ( "" )} {cycleDetails.total_issues > 0 && cycleDetails.distribution && (
)}
)}
); });