|
| 1 | +import { Progress } from '@/components/ui/progress'; |
| 2 | +import { formatDistanceToNowStrict } from 'date-fns'; |
| 3 | + |
| 4 | +interface ContractProgressBarProps { |
| 5 | + startDate: string; |
| 6 | + endDate: string; |
| 7 | +} |
| 8 | + |
| 9 | +export default function ContractProgressBar({ startDate, endDate }: Readonly<ContractProgressBarProps>) { |
| 10 | + const startMs = Date.parse(startDate); |
| 11 | + const endMs = Date.parse(endDate); |
| 12 | + const now = Date.now(); |
| 13 | + |
| 14 | + // Guard: if dates are invalid or duration is zero/negative, show empty progress |
| 15 | + if (Number.isNaN(startMs) || Number.isNaN(endMs) || endMs <= startMs) { |
| 16 | + return ( |
| 17 | + <div className="space-y-2"> |
| 18 | + <Progress value={0} className="transition-all" /> |
| 19 | + <div className="flex justify-between text-xs text-muted-foreground"> |
| 20 | + <span>Not Available</span> |
| 21 | + <span>Invalid contract dates</span> |
| 22 | + </div> |
| 23 | + </div> |
| 24 | + ); |
| 25 | + } |
| 26 | + |
| 27 | + const total = endMs - startMs; |
| 28 | + const elapsed = Math.max(0, Math.min(now - startMs, total)); |
| 29 | + const percent = Math.round((elapsed / total) * 100); |
| 30 | + |
| 31 | + const isCompleted = now > endMs; |
| 32 | + const isActive = now >= startMs && now <= endMs; |
| 33 | + |
| 34 | + let displayValue: number; |
| 35 | + if (isCompleted) displayValue = 100; |
| 36 | + else if (isActive) displayValue = percent; |
| 37 | + else displayValue = 0; |
| 38 | + |
| 39 | + let statusText: string; |
| 40 | + if (isCompleted) statusText = 'Completed'; |
| 41 | + else if (isActive) statusText = `${percent}% Complete`; |
| 42 | + else statusText = 'Not Started'; |
| 43 | + |
| 44 | + let detailText: string; |
| 45 | + if (isCompleted) detailText = `Ended ${formatDistanceToNowStrict(endMs, { addSuffix: true })}`; |
| 46 | + else if (isActive) |
| 47 | + detailText = `${percent}% Complete - ${formatDistanceToNowStrict(endMs, { addSuffix: true })} left`; |
| 48 | + else detailText = `Not Started - Starts in ${formatDistanceToNowStrict(startMs, { addSuffix: true })}`; |
| 49 | + |
| 50 | + return ( |
| 51 | + <div className="space-y-2"> |
| 52 | + <Progress value={displayValue} className="transition-all" /> |
| 53 | + <div className="flex justify-between text-xs text-muted-foreground"> |
| 54 | + <span>{statusText}</span> |
| 55 | + <span>{detailText}</span> |
| 56 | + </div> |
| 57 | + </div> |
| 58 | + ); |
| 59 | +} |
0 commit comments