import React, { useEffect, useState } from "react"; import isEmpty from "lodash/isEmpty"; import { observer } from "mobx-react-lite"; import { useRouter } from "next/router"; import { Controller, useForm } from "react-hook-form"; import { Disclosure, Transition } from "@headlessui/react"; // icons import { ChevronDown, LinkIcon, Trash2, UserCircle2, AlertCircle, ChevronRight, CalendarClock } from "lucide-react"; // ui import { Avatar, CustomMenu, Loader, LayersIcon, TOAST_TYPE, setToast } from "@plane/ui"; // components import { SidebarProgressStats } from "components/core"; import ProgressChart from "components/core/sidebar/progress-chart"; import { CycleDeleteModal } from "components/cycles/delete-modal"; import { DateRangeDropdown } from "components/dropdowns"; // constants import { CYCLE_STATUS } from "constants/cycle"; import { CYCLE_UPDATED } from "constants/event-tracker"; import { EUserWorkspaceRoles } from "constants/workspace"; // helpers import { findHowManyDaysLeft, renderFormattedPayloadDate } from "helpers/date-time.helper"; import { copyUrlToClipboard } from "helpers/string.helper"; // hooks import { useEventTracker, useCycle, useUser, useMember } from "hooks/store"; // services import { CycleService } from "services/cycle.service"; // types import { ICycle } from "@plane/types"; type Props = { cycleId: string; handleClose: () => void; }; const defaultValues: Partial = { start_date: null, end_date: null, }; // services const cycleService = new CycleService(); // TODO: refactor the whole component export const CycleDetailsSidebar: React.FC = observer((props) => { const { cycleId, handleClose } = props; // states const [cycleDeleteModal, setCycleDeleteModal] = useState(false); // router const router = useRouter(); const { workspaceSlug, projectId, peekCycle } = router.query; // store hooks const { setTrackElement, captureCycleEvent } = useEventTracker(); const { membership: { currentProjectRole }, } = useUser(); const { getCycleById, updateCycleDetails } = useCycle(); const { getUserDetails } = useMember(); // derived values const cycleDetails = getCycleById(cycleId); const cycleOwnerDetails = cycleDetails ? getUserDetails(cycleDetails.owned_by_id) : undefined; // form info const { control, reset } = useForm({ defaultValues, }); const submitChanges = (data: Partial, changedProperty: string) => { if (!workspaceSlug || !projectId || !cycleId) return; updateCycleDetails(workspaceSlug.toString(), projectId.toString(), cycleId.toString(), data) .then((res) => { captureCycleEvent({ eventName: CYCLE_UPDATED, payload: { ...res, changed_properties: [changedProperty], element: "Right side-peek", state: "SUCCESS", }, }); }) .catch(() => { captureCycleEvent({ eventName: CYCLE_UPDATED, payload: { ...data, element: "Right side-peek", state: "FAILED", }, }); }); }; const handleCopyText = () => { copyUrlToClipboard(`${workspaceSlug}/projects/${projectId}/cycles/${cycleId}`) .then(() => { setToast({ type: TOAST_TYPE.SUCCESS, title: "Link Copied!", message: "Cycle link copied to clipboard.", }); }) .catch(() => { setToast({ type: TOAST_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 handleDateChange = async (startDate: Date | undefined, endDate: Date | undefined) => { if (!startDate || !endDate) return; let isDateValid = false; const payload = { start_date: renderFormattedPayloadDate(startDate), end_date: renderFormattedPayloadDate(endDate), }; if (cycleDetails && cycleDetails.start_date && cycleDetails.end_date) isDateValid = await dateChecker({ ...payload, cycle_id: cycleDetails.id, }); else isDateValid = await dateChecker(payload); if (isDateValid) { submitChanges(payload, "date_range"); setToast({ type: TOAST_TYPE.SUCCESS, title: "Success!", message: "Cycle updated successfully.", }); } else { setToast({ type: TOAST_TYPE.ERROR, title: "Error!", message: "You already have a cycle on the given dates, if you want to create a draft cycle, you can do that by removing both the dates.", }); reset({ ...cycleDetails }); } }; // TODO: refactor this // const handleFiltersUpdate = useCallback( // (key: keyof IIssueFilterOptions, value: string | string[]) => { // if (!workspaceSlug || !projectId) return; // const newValues = issueFilters?.filters?.[key] ?? []; // if (Array.isArray(value)) { // value.forEach((val) => { // if (!newValues.includes(val)) newValues.push(val); // }); // } else { // if (issueFilters?.filters?.[key]?.includes(value)) newValues.splice(newValues.indexOf(value), 1); // else newValues.push(value); // } // updateFilters(workspaceSlug.toString(), projectId.toString(), EFilterType.FILTERS, { [key]: newValues }, cycleId); // }, // [workspaceSlug, projectId, cycleId, issueFilters, updateFilters] // ); const cycleStatus = cycleDetails?.status.toLocaleLowerCase(); 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 ? isCompleted && cycleDetails?.progress_snapshot ? Math.round( (cycleDetails.progress_snapshot.completed_issues / cycleDetails.progress_snapshot.total_issues) * 100 ) : Math.round((cycleDetails.completed_issues / cycleDetails.total_issues) * 100) : null; if (!cycleDetails) return (
); const currentCycle = CYCLE_STATUS.find((status) => status.value === cycleStatus); const issueCount = isCompleted && !isEmpty(cycleDetails.progress_snapshot) ? cycleDetails.progress_snapshot.total_issues === 0 ? "0 Issue" : `${cycleDetails.progress_snapshot.completed_issues}/${cycleDetails.progress_snapshot.total_issues}` : cycleDetails.total_issues === 0 ? "0 Issue" : `${cycleDetails.completed_issues}/${cycleDetails.total_issues}`; const daysLeft = findHowManyDaysLeft(cycleDetails.end_date); const isEditingAllowed = !!currentProjectRole && currentProjectRole >= EUserWorkspaceRoles.MEMBER; return ( <> {cycleDetails && workspaceSlug && projectId && ( setCycleDeleteModal(false)} workspaceSlug={workspaceSlug.toString()} projectId={projectId.toString()} /> )} <>
{!isCompleted && isEditingAllowed && ( { setTrackElement("CYCLE_PAGE_SIDEBAR"); setCycleDeleteModal(true); }} > Delete cycle )}
{currentCycle && ( {currentCycle.value === "current" && daysLeft !== undefined ? `${daysLeft} ${currentCycle.label}` : `${currentCycle.label}`} )}

{cycleDetails.name}

{cycleDetails.description && ( {cycleDetails.description} )}
Date range
( ( { onChangeStartDate(val?.from ? renderFormattedPayloadDate(val.from) : null); onChangeEndDate(val?.to ? renderFormattedPayloadDate(val.to) : null); handleDateChange(val?.from, val?.to); }} placeholder={{ from: "Start date", to: "End date", }} required={cycleDetails.status !== "draft"} /> )} /> )} />
Lead
{cycleOwnerDetails?.display_name}
Issues
{issueCount}
{({ open }) => (
Progress
{progressPercentage ? ( {progressPercentage ? `${progressPercentage}%` : ""} ) : ( "" )} {isStartValid && isEndValid ? (
{isCompleted && !isEmpty(cycleDetails.progress_snapshot) ? ( <> {cycleDetails.progress_snapshot.distribution?.completion_chart && cycleDetails.start_date && cycleDetails.end_date && (
Ideal
Current
)} ) : ( <> {cycleDetails.distribution?.completion_chart && cycleDetails.start_date && cycleDetails.end_date && (
Ideal
Current
)} )} {/* stats */} {isCompleted && !isEmpty(cycleDetails.progress_snapshot) ? ( <> {cycleDetails.progress_snapshot.total_issues > 0 && cycleDetails.progress_snapshot.distribution && (
)} ) : ( <> {cycleDetails.total_issues > 0 && cycleDetails.distribution && (
)} )}
)}
); });