Files
hats-app/app/(dashboard)/task/component/client/ClientMilestoneTimeline.tsx
T
Ichsan Kurniawan e67f671983 Enforce assignment permissions and show active milestones
Gate assignment creation and editing by the relevant permissions, show ongoing milestones on the timeline, and restrict the forbidden-page admin link to authorized users. Also use the shared RBAC role type and tighten sidebar active-state matching.
2026-11-10 11:27:05 +07:00

495 lines
29 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"use client";
import React from 'react';
import Link from 'next/link';
import dayjs from 'dayjs';
import isSameOrAfter from 'dayjs/plugin/isSameOrAfter';
import isSameOrBefore from 'dayjs/plugin/isSameOrBefore';
import { Calendar, ChevronRight, Clock } from 'lucide-react';
import { HoverCard, HoverCardContent, HoverCardTrigger } from '@/components/ui/hover-card';
import BadgeStatus from '@/components/ui/badge-status';
import { cn } from '@/lib/utils';
import { IClient, IClientMilestone } from '../../types';
import { resolveTechnicalStatusMeta } from '../../utils/client-overview-helpers';
dayjs.extend(isSameOrAfter);
dayjs.extend(isSameOrBefore);
interface ClientMilestoneTimelineProps {
client: IClient;
variant?: 'list' | 'grid';
}
interface GroupedMilestone {
dateKey: string;
date: dayjs.Dayjs;
percent: number;
diffDays: number;
isOngoing: boolean;
hideDate: boolean;
items: IClientMilestone[];
}
interface GradientSegment {
fromPercent: number;
toPercent: number;
fromHex: string;
toHex: string;
}
// Starting color for active milestone line: Merah rose (Development)
const START_LINE_HEX = '#f43f5e';
export default function ClientMilestoneTimeline({ client, variant = 'list' }: ClientMilestoneTimelineProps) {
const today = dayjs().startOf('day');
const maxDate = today.add(2, 'month').startOf('day');
const totalDays = maxDate.diff(today, 'day') || 60;
// Helper to safely parse and normalize start and end dates (handling edge cases or inverted dates)
const getNormalizedDates = (m: IClientMilestone) => {
const d1 = m.start_date ? dayjs(m.start_date).startOf('day') : null;
const d2 = m.end_date ? dayjs(m.end_date).startOf('day') : null;
if (!d1 && !d2) return null;
if (d1 && !d2) return { startDate: d1, endDate: d1 };
if (!d1 && d2) return { startDate: d2, endDate: d2 };
const startDate = d1!.isBefore(d2!) ? d1! : d2!;
const endDate = d1!.isAfter(d2!) ? d1! : d2!;
return { startDate, endDate };
};
// Filter milestones:
// 1. Ongoing agendas: started in the past (startDate < today), but endDate is still today or in the future (endDate >= today)
// 2. Upcoming agendas: startDate is between today and maxDate (within next 2 months)
const processedMilestones: {
item: IClientMilestone;
isOngoing: boolean;
targetDate: dayjs.Dayjs;
startDate: dayjs.Dayjs;
endDate: dayjs.Dayjs;
}[] = [];
const rawMilestones = client.milestone || [];
rawMilestones.forEach((m) => {
const dates = getNormalizedDates(m);
if (!dates) return;
const { startDate, endDate } = dates;
const isOngoing = startDate.isBefore(today) && (endDate.isAfter(today) || endDate.isSame(today, 'day'));
const isUpcoming = (startDate.isAfter(today) || startDate.isSame(today, 'day')) && (startDate.isBefore(maxDate) || startDate.isSame(maxDate, 'day'));
if (isOngoing) {
processedMilestones.push({
item: m,
isOngoing: true,
targetDate: today, // Position at the start of milestone
startDate,
endDate,
});
} else if (isUpcoming) {
processedMilestones.push({
item: m,
isOngoing: false,
targetDate: startDate,
startDate,
endDate,
});
}
});
// Group milestones by target date / start milestone to handle multiple agendas on the same point
const groupsMap: { [key: string]: GroupedMilestone } = {};
processedMilestones.forEach(({ item, isOngoing, targetDate }) => {
let dateKey: string;
let percent: number;
let diffDays: number;
const isAtStart = isOngoing || targetDate.isSame(today, 'day');
if (isAtStart) {
// Group ongoing agendas at the beginning of milestone (0%)
dateKey = 'start-milestone';
percent = 0;
diffDays = 0;
} else {
dateKey = targetDate.format('YYYY-MM-DD');
diffDays = targetDate.diff(today, 'day');
const rawPercent = (diffDays / totalDays) * 100;
percent = Math.max(0, Math.min(100, rawPercent));
}
if (!groupsMap[dateKey]) {
groupsMap[dateKey] = {
dateKey,
date: targetDate,
percent,
diffDays,
isOngoing: false,
hideDate: false,
items: [],
};
}
groupsMap[dateKey].items.push(item);
if (isOngoing) {
groupsMap[dateKey].isOngoing = true;
// Hide date label underneath start dot because varying start dates in past would confuse users
groupsMap[dateKey].hideDate = true;
}
});
const groups = Object.values(groupsMap).sort((a, b) => a.percent - b.percent);
// Compute sequential line gradient segments:
// Starts at Hari Ini (0%, Merah Rose) -> Agenda 1 -> Agenda 2 -> ... -> Agenda N
const gradientSegments: GradientSegment[] = [];
if (groups.length > 0) {
let currentPercent = 0;
let currentHex = START_LINE_HEX;
// If the first group is at 0%, its status color initiates the line gradient
if (groups[0]?.percent === 0) {
const firstGroup = groups[0];
const firstMeta = resolveTechnicalStatusMeta(firstGroup.items[0]?.project_assignment_status?.name);
currentHex = firstMeta.hexColor;
}
for (let i = 0; i < groups.length; i++) {
const group = groups[i];
const targetPercent = group.percent;
const targetMeta = resolveTechnicalStatusMeta(group.items[0]?.project_assignment_status?.name);
const targetHex = targetMeta.hexColor;
if (targetPercent > currentPercent) {
gradientSegments.push({
fromPercent: currentPercent,
toPercent: targetPercent,
fromHex: currentHex,
toHex: targetHex,
});
currentPercent = targetPercent;
currentHex = targetHex;
}
}
}
// Compute month boundaries for tick lines along the 2-month rail
const nextMonthStart = today.add(1, 'month').startOf('month');
const month2Start = today.add(2, 'month').startOf('month');
const monthTicks: { label: string; percent: number }[] = [];
if (nextMonthStart.isAfter(today) && nextMonthStart.isBefore(maxDate)) {
const diff = nextMonthStart.diff(today, 'day');
monthTicks.push({
label: nextMonthStart.format('1 MMM'),
percent: (diff / totalDays) * 100,
});
}
if (month2Start.isAfter(today) && month2Start.isBefore(maxDate)) {
const diff = month2Start.diff(today, 'day');
monthTicks.push({
label: month2Start.format('1 MMM'),
percent: (diff / totalDays) * 100,
});
}
const isGrid = variant === 'grid';
const hasAgendas = groups.length > 0;
return (
<div className={cn("w-full flex flex-col gap-2 min-w-0", isGrid ? "pt-2" : "")}>
{/* Header: Title + 2-Month Date Span */}
<div className="flex items-center justify-between text-xs px-0.5">
<div className="flex items-center gap-2 flex-wrap">
<span className="font-semibold text-foreground tracking-tight text-xs">
Next 2 Months Milestone
</span>
<span className="text-[10px] text-muted-foreground font-medium hidden sm:inline">
({today.format('DD MMM')} – {maxDate.format('DD MMM YYYY')})
</span>
</div>
<div className="flex items-center gap-1.5">
{hasAgendas ? (
<span className="text-[10px] px-2 py-0.5 rounded-full bg-primary/10 text-primary font-bold">
{processedMilestones.length} {processedMilestones.length === 1 ? 'Agenda' : 'Agendas'}
</span>
) : (
<span className="text-[10px] text-muted-foreground italic">
No milestone scheduled
</span>
)}
</div>
</div>
{/* Timeline Viewport Container with group/rail for sibling hover coordination */}
<div className={cn("w-full min-w-0", isGrid ? "" : "overflow-x-auto scrollbar-hide")}>
<div className={cn("relative pt-3 group/rail", !hasAgendas && !isGrid ? 'pb-6' : '', hasAgendas && !isGrid ? 'mb-20' : 'mb-10', isGrid ? "px-5" : "min-w-105 px-6")}>
{/* Continuous 2-Month Horizontal Rail */}
<div className="relative h-1.5 sm:h-2 w-full bg-zinc-200/70 dark:bg-zinc-700/50 rounded-full">
{/* Gradient Segments connecting Hari Ini -> Agenda 1 -> Agenda 2 -> ... */}
<div className="absolute inset-0 rounded-full overflow-hidden pointer-events-none">
{gradientSegments.map((seg, idx) => (
<div
key={idx}
className="absolute top-0 h-full transition-all duration-300"
style={{
left: `${seg.fromPercent}%`,
width: `${Math.max(0, seg.toPercent - seg.fromPercent)}%`,
background: `linear-gradient(to right, ${seg.fromHex}, ${seg.toHex})`,
}}
/>
))}
</div>
{/* Start Pin (Today) - Rose if active progression, gray if default */}
<div
className={cn(
"absolute -left-1 top-1/2 -translate-y-1/2 size-2.5 rounded-full ring-2 ring-background z-10 transition-colors",
hasAgendas ? "bg-rose-500 shadow-xs" : "bg-muted-foreground/40"
)}
title={`Today: ${today.format('DD MMM YYYY')}`}
/>
{/* End Pin (+2 Months) */}
<div
className="absolute -right-1 top-1/2 -translate-y-1/2 size-2.5 rounded-full bg-muted-foreground/40 ring-2 ring-background z-10"
title={`End: ${maxDate.format('DD MMM YYYY')}`}
/>
{/* Month Boundary Tick Markers */}
{monthTicks.map((tick, idx) => (
<div
key={idx}
className="absolute -top-1 -translate-x-1/2 flex flex-col items-center pointer-events-none select-none z-0"
style={{ left: `${tick.percent}%` }}
>
<div className="w-px h-3.5 bg-border/80 dark:bg-zinc-600" />
<span className="text-[9px] text-zinc-600 dark:text-zinc-300 font-mono mt-0.5 whitespace-nowrap">
{tick.label}
</span>
</div>
))}
{/* If no milestones in range, show gentle notice */}
{!hasAgendas && (
<div className="absolute inset-0 flex items-center justify-center pointer-events-none">
<span className={`text-[10px] text-muted-foreground/70 italic mt-20 select-none whitespace-nowrap`}>
No upcoming milestones in the next 2 months
</span>
</div>
)}
{/* Agenda Milestone Markers */}
{groups.map((group) => {
const isMulti = group.items.length > 1;
const firstItem = group.items[0];
const primaryMeta = resolveTechnicalStatusMeta(firstItem.project_assignment_status?.name);
return (
<div
key={group.dateKey}
className={cn(
"absolute -translate-x-1/2 -top-1 flex flex-col items-center group/node",
"transition-all duration-200",
// Stacking order: default z-20, leaps to z-50 on hover
"z-20 hover:z-50 focus-within:z-50",
// When any node is hovered, soften non-hovered siblings
"group-hover/rail:opacity-40 group-hover/rail:scale-95",
// Actively hovered node is fully opaque, prominent, and scaled up
"hover:opacity-100!",
"focus-within:opacity-100! "
)}
style={{ left: `${group.percent}%` }}
>
{/* Vertical Tick Line connecting Rail to Dot */}
<div
className={cn(
"w-0.5 h-3.5 sm:h-4 rounded-full transition-all duration-200",
"group-hover/node:w-1 group-hover/node:h-4.5 group-hover/node:shadow-sm",
isMulti ? "bg-amber-400 dark:bg-amber-500" : primaryMeta.tickLine
)}
/>
{/* HoverCard Trigger (Dot + Short Badge + Date) */}
<HoverCard openDelay={30} closeDelay={150}>
<HoverCardTrigger asChild>
<Link
href={`/task/client-detail/${client.id}/${firstItem.project_assignment_id}`}
className={cn(
"flex flex-col items-center cursor-pointer focus:outline-none",
"px-2 py-1 rounded-xl transition-all duration-200",
// Normal state: transparent
"bg-transparent border border-transparent",
// Hover state: solid high-contrast backdrop card with shadow
// Completely covers any adjacent date text underneath it
"group-hover/node:bg-card/95 dark:group-hover/node:bg-zinc-900/10",
"group-hover/node:backdrop-blur-md"
)}
aria-label={`Milestones on ${group.date.format('DD MMM YYYY')}`}
>
{/* Dot / Multi-Dot Indicator */}
{isMulti ? (
<div
className={cn(
"relative size-4 sm:size-4.5 rounded-full p-[1.5px] shadow-sm ring-2 ring-background transition-all duration-200",
"group-hover/node:size-5 group-hover/node:ring-4 group-hover/node:ring-amber-500/40 group-hover/node:shadow-md",
"bg-linear-to-br from-amber-400 via-rose-500 to-violet-600"
)}
title={`${group.items.length} agendas on this date`}
>
<div className="w-full h-full rounded-full bg-background flex items-center justify-center">
<span className="text-[9px] group-hover/node:text-[10px] font-black text-foreground leading-none">
{group.items.length}
</span>
</div>
</div>
) : (
<div
className={cn(
"size-3 sm:size-3.5 rounded-full ring-2 ring-background shadow-xs transition-all duration-200",
"group-hover/node:size-4.5 group-hover/node:ring-4 group-hover/node:ring-offset-2 group-hover/node:ring-offset-background group-hover/node:shadow-md",
primaryMeta.dotBg,
primaryMeta.ringColor
)}
title={`${primaryMeta.fullName} on ${group.date.format('DD MMM YYYY')}`}
/>
)}
{/* Short Badge underneath dot */}
<div
className={cn(
"mt-1 px-1.5 py-0.5 rounded text-[9px] font-bold uppercase tracking-wider border whitespace-nowrap shadow-2xs leading-none transition-all duration-200",
"group-hover/node:px-2 group-hover/node:py-0.5 group-hover/node:text-[10px] group-hover/node:font-black group-hover/node:shadow-xs",
isMulti
? "bg-amber-500/15 dark:bg-amber-950/60 text-amber-700 dark:text-amber-300 border-amber-500/40 group-hover/node:bg-amber-500 group-hover/node:text-white dark:group-hover/node:text-zinc-950"
: cn(
primaryMeta.badgeBg,
primaryMeta.badgeText,
primaryMeta.badgeBorder,
"group-hover/node:brightness-110"
)
)}
>
{isMulti ? `${group.items.length} Agendas` : primaryMeta.shortName}
</div>
{/* Date Label strictly underneath (hidden for ongoing agendas with varying start dates) */}
{!group.hideDate ? (
<span
className={cn(
"text-[9px] sm:text-[10px] text-zinc-600 dark:text-zinc-300 font-medium whitespace-nowrap mt-0.5 select-none transition-all duration-200",
"group-hover/node:text-foreground group-hover/node:font-bold"
)}
>
{group.date.format('DD MMM')}
</span>
) : null}
</Link>
</HoverCardTrigger>
{/* Rich Hover Card Content */}
<HoverCardContent
side="top"
align="center"
sideOffset={8}
className="w-[calc(100vw-3rem)] max-w-sm sm:w-96 p-3.5 z-50 shadow-xl border border-border/80 bg-popover/95 backdrop-blur-md rounded-xl"
>
{/* Header */}
<div className="flex items-center justify-between pb-2 mb-2.5 border-b border-border/60">
<div className="flex items-center gap-1.5 text-foreground font-semibold text-xs">
<Calendar className="w-3.5 h-3.5 text-primary shrink-0" />
<span>
{group.isOngoing
? 'Ongoing Milestones (Active Today)'
: group.date.format('dddd, DD MMMM YYYY')}
</span>
</div>
<span className="text-[10px] font-medium px-2 py-0.5 rounded-md bg-muted text-muted-foreground">
{group.isOngoing
? 'Currently Active'
: group.diffDays === 0
? 'Today'
: group.diffDays === 1
? 'Tomorrow'
: `In ${group.diffDays} days`}
</span>
</div>
{/* Subtitle / Counter */}
<div className="text-[11px] text-muted-foreground mb-2">
{group.items.length === 1
? (group.isOngoing ? '1 ongoing milestone agenda currently active:' : '1 milestone agenda on this date:')
: (group.isOngoing ? `${group.items.length} ongoing milestone agendas currently active:` : `${group.items.length} milestone agendas on this date:`)}
</div>
{/* List of Assignment Milestones */}
<div className="space-y-2 max-h-64 overflow-y-auto pr-1">
{group.items.map((item, itemIdx) => (
<Link
key={item.id || itemIdx}
href={`/task/client-detail/${client.id}/${item.project_assignment_id}`}
className="group/item block p-2.5 rounded-lg border border-border/70 bg-muted/30 hover:bg-muted/60 hover:border-his/60 transition-all duration-200"
>
<div className="flex items-center justify-between gap-2">
<BadgeStatus status={item.project_assignment_status?.name} />
<span className="text-[10px] text-muted-foreground font-medium flex items-center gap-0.5 group-hover/item:text-foreground transition-colors">
<span>View Assignment</span>
<ChevronRight className="w-3 h-3 group-hover/item:translate-x-0.5 transition-transform" />
</span>
</div>
<div className="mt-2 space-y-1">
{item.project_name && (
<div className="text-xs font-semibold text-foreground truncate">
{item.project_name}
{item.project_code && (
<span className="ml-1 text-[10px] font-mono font-normal text-muted-foreground">
({item.project_code})
</span>
)}
</div>
)}
{item.wo_name && (
<div className="text-[11px] text-muted-foreground truncate">
WO: <span className="font-medium text-foreground">{item.wo_name}</span>
{item.wo_code && (
<span className="ml-1 text-[10px] font-mono text-muted-foreground/80">
[{item.wo_code}]
</span>
)}
</div>
)}
{item.description && (
<p className="text-[11px] text-muted-foreground italic line-clamp-2 mt-1">
&ldquo;{item.description}&rdquo;
</p>
)}
<div className="pt-1 flex items-center gap-1.5 text-[10px] text-muted-foreground">
<Clock className="w-3 h-3 shrink-0" />
<span>
{dayjs(item.start_date).format('DD MMM YYYY')}
{item.end_date
? ` – ${dayjs(item.end_date).format('DD MMM YYYY')}`
: ''}
</span>
</div>
</div>
</Link>
))}
</div>
</HoverCardContent>
</HoverCard>
</div>
);
})}
</div>
</div>
</div>
</div>
);
}