From f0526e4096b2f71da952e1b1edb7b172cb857261 Mon Sep 17 00:00:00 2001 From: Ichsan Kurniawan Date: Wed, 14 Oct 2026 15:47:50 +0700 Subject: [PATCH] Add assignment timeline and activity log This change adds a milestone timeline and development activity log for assignment detail pages, including a JSON comparison modal for activity history entries. It also extends assignment history types and overview helper logic to surface progress, delivery health, and milestone dates more accurately. --- .../[assignment_id]/ActivityHistoryModal.tsx | 114 ++++ .../AssignmentDetailComponent.tsx | 591 +++++++++--------- .../DevelopmentActivityLog.tsx | 212 +++++++ .../ProjectMilestoneTimeline.tsx | 565 +++++++++++++++++ .../[client_id]/[assignment_id]/page.tsx | 2 - app/(dashboard)/task/type.assignment.ts | 16 + .../task/utils/assignment-overview-helpers.ts | 77 ++- 7 files changed, 1278 insertions(+), 299 deletions(-) create mode 100644 app/(dashboard)/task/client-detail/[client_id]/[assignment_id]/ActivityHistoryModal.tsx create mode 100644 app/(dashboard)/task/client-detail/[client_id]/[assignment_id]/DevelopmentActivityLog.tsx create mode 100644 app/(dashboard)/task/client-detail/[client_id]/[assignment_id]/ProjectMilestoneTimeline.tsx diff --git a/app/(dashboard)/task/client-detail/[client_id]/[assignment_id]/ActivityHistoryModal.tsx b/app/(dashboard)/task/client-detail/[client_id]/[assignment_id]/ActivityHistoryModal.tsx new file mode 100644 index 0000000..cb52b66 --- /dev/null +++ b/app/(dashboard)/task/client-detail/[client_id]/[assignment_id]/ActivityHistoryModal.tsx @@ -0,0 +1,114 @@ +"use client"; + +import { useState } from 'react'; +import { IProjectAssignmentHistory } from '../../../type.assignment'; +import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'; +import { Button } from '@/components/ui/button'; +import { Check, Copy, FileText } from 'lucide-react'; +import dayjs from 'dayjs'; +import { DialogDescription } from '@radix-ui/react-dialog'; + +interface ActivityHistoryModalProps { + historyItem: IProjectAssignmentHistory | null; + open: boolean; + onClose: () => void; +} + +export function ActivityHistoryModal({ historyItem, open, onClose }: ActivityHistoryModalProps) { + const [copied, setCopied] = useState(false); + + if (!historyItem) return null; + + const oldData = historyItem.old_data; + const newData = historyItem.new_data; + + const copyFullJson = () => { + const payload = { + id: historyItem.id, + description: historyItem.description, + created_at: historyItem.created_at, + user: historyItem.user, + old_data: oldData, + new_data: newData, + }; + navigator.clipboard.writeText(JSON.stringify(payload, null, 2)); + setCopied(true); + setTimeout(() => setCopied(false), 2000); + }; + + return ( + !isOpen && onClose()}> + + {/* Header */} + + + + Activity Log Details #{historyItem.id} + + + {historyItem.description} + +
+ By: {historyItem.user?.fullname || historyItem.user?.nickname || 'System'} + · + {dayjs(historyItem.created_at).format('DD MMM YYYY, HH:mm:ss')} +
+
+ + {/* Side-by-Side Comparison Panels */} +
+
+ {/* Old Data Panel */} +
+
+ Old Data +
+
+
+                                    {oldData !== null && oldData !== undefined
+                                        ? JSON.stringify(oldData, null, 2)
+                                        : 'null'}
+                                
+
+
+ + {/* New Data Panel */} +
+
+ New Data +
+
+
+                                    {newData !== null && newData !== undefined
+                                        ? JSON.stringify(newData, null, 2)
+                                        : 'null'}
+                                
+
+
+
+
+ + {/* Footer Actions */} +
+ + +
+
+
+ ); +} diff --git a/app/(dashboard)/task/client-detail/[client_id]/[assignment_id]/AssignmentDetailComponent.tsx b/app/(dashboard)/task/client-detail/[client_id]/[assignment_id]/AssignmentDetailComponent.tsx index 7f41302..e552145 100644 --- a/app/(dashboard)/task/client-detail/[client_id]/[assignment_id]/AssignmentDetailComponent.tsx +++ b/app/(dashboard)/task/client-detail/[client_id]/[assignment_id]/AssignmentDetailComponent.tsx @@ -1,14 +1,4 @@ -"use client" - -/** - * Design read: internal ops detail page for staff, calm Linear-style language, - * existing shadcn + Tailwind stack, brand orange (`his`) as the single accent. - * Dials: VARIANCE 5, MOTION 4, DENSITY 5. - * - * Shape lock: surfaces rounded-2xl, inner tiles rounded-xl, small chips rounded-lg. - * Elevation comes from borders, not shadows. Accent is used only for the current - * timeline node, link hovers and the primary action. - */ +"use client"; import { useState, type ReactNode } from 'react'; import Link from 'next/link'; @@ -19,6 +9,7 @@ import { FolderGit2, History, LayoutGrid, List, Mail, Phone, UserPlus, Users, } from 'lucide-react'; import { Button } from '@/components/ui/button'; +import { Card900 } from '@/components/ui/card'; import { Badge } from '@/components/ui/badge'; import { LazyImage } from '@/components/ui/lazy-image'; import BadgeStatus from '@/components/ui/badge-status'; @@ -28,6 +19,18 @@ import { IClient, CLIENT_FALLBACK_IMAGE, END_USER_FALLBACK_IMAGE } from '../../. import { IProjectAssignment, ProjectAssignmentWorkOrderDetail } from '../../../type.assignment'; import ConvertedAssignmentBadge from '../../../component/project-assignment/ConvertedAssignmentBadge'; import Reveal from '@/components/ui/reveal'; +import { buildAssignmentOverview, formatAssignmentDate } from '../../../utils/assignment-overview-helpers'; + +// Dynamically imported heavy child components +const ProjectMilestoneTimeline = dynamic( + () => import('./ProjectMilestoneTimeline').then((mod) => mod.ProjectMilestoneTimeline), + { ssr: false, loading: () =>
} +); + +const DevelopmentActivityLog = dynamic( + () => import('./DevelopmentActivityLog').then((mod) => mod.DevelopmentActivityLog), + { ssr: false, loading: () =>
} +); const ModalActionLoader = () => (
@@ -60,13 +63,7 @@ interface Props { const TEAM_PREVIEW_LIMIT = 5; -function formatAssignmentDate(dateStr?: string | null) { - if (!dateStr) return 'N/A'; - const d = dayjs(dateStr); - return d.isValid() ? d.format('DD MMM YYYY') : 'N/A'; -} - -/** Human span between two dates, e.g. "2 months 15 days". Null when either date is missing or invalid. */ +/** Human span between two dates, e.g. "5 months" or "2 months 15 days". */ function formatSpan(start?: string | null, end?: string | null) { if (!start || !end) return null; const s = dayjs(start).startOf('day'); @@ -106,46 +103,56 @@ export default function AssignmentDetail({ client, initialAssignment: assignment const visibleTeam = showAllTeam ? team : team.slice(0, TEAM_PREVIEW_LIMIT); const hiddenTeamCount = team.length - visibleTeam.length; - const statusHistory = assignment.project_assignment_status_detail?.filter(s => Boolean(s.start_date || (Array.isArray(s.date) && s.date.length > 0))) ?? []; - const currentEntry = statusHistory.find(s => !s.end_date && !(Array.isArray(s.date) && s.date[s.date.length - 1]?.end_date)) ?? statusHistory[0]; - const duration = formatSpan(assignmentStartDate, assignmentEndDate); const positionCount = new Set(team.map(m => m.user?.position?.name).filter(Boolean)).size; const activeTeamCount = team.filter(m => !m.end_date || !dayjs(m.end_date).endOf('day').isBefore(dayjs())).length; + // Build assignment overview for progress metrics & dynamic 5-spectrum color + const overview = buildAssignmentOverview(assignment); + + // Days metrics + const daysRemaining = assignmentEndDate ? dayjs(assignmentEndDate).diff(dayjs(), 'day') : 0; + const remainingText = daysRemaining >= 0 ? `${daysRemaining} hari sisa` : '0 hari sisa (Overdue)'; + const totalDaysText = `${overview.totalDays} hari total / ${remainingText}`; + const dateRangeText = `${formatAssignmentDate(assignmentStartDate)} - ${formatAssignmentDate(assignmentEndDate)}`; + const handleClose = () => setAction(undefined); return ( <>
+ {/* Back to Client navigation */} - Back to {owner?.name ?? 'tasks'} + Back to: {owner?.name ?? 'PT. TELEKOMUNIKASI SELULAR'} - {/* Header: identity, status, primary action, key facts */} + {/* 1. Header / Hero Card using Card900 */} -
+ + {/* Top Area */}
+ {/* Emblem */}
-
+
+ {/* Top Pills */}
- - {isWorkOrder ? : } + + {isWorkOrder ? : } {assignmentType} @@ -157,24 +164,30 @@ export default function AssignmentDetail({ client, initialAssignment: assignment ) : null}
-

+ {/* Assignment Title */} +

{assignmentName}

+ {/* Assignment Description */} {assignmentDesc ? ( -

+

{assignmentDesc}

) : null}
-
+ {/* Action Buttons: Keep Promote to Project (if IM), Update Technical Status, Update Admin Status */} +
{!isWorkOrder && (
-
+ {/* Progress Project Bar */} +
+
+ + Progress Project + +
+
+
+
+ + {overview.progressPercent}% + +
+
+ +
+
+ + {dateRangeText} +
+
+ + {totalDaysText} +
+
+
+ + {/* Quick Stats */} +
-
+
-
- {/* Main column */} -
- - -
- - + {/* 2. Project Milestone Timeline */} + + + + + {/* 3. Development Activity Log (with pagination & clean modal) */} + + + + + {/* 4. Client and End User + Project in 2-Column Grid (Preserving exact original card style) */} + +
+ {/* Client and End User Card */} + +
+ + +
+
+ + {/* Project Card */} + {assignment.project?.id ? ( + + +
+ +
+
+
+

+ {assignment.project.name} +

+ +
+
+ {assignment.project.code ? ( + + # + {assignment.project.code} + + ) : null} + {assignment.project.year ? ( + + + Year {assignment.project.year} + + ) : null} + {assignment.project.start_date || assignment.project.end_date ? ( + + · + + + {formatAssignmentDate(assignment.project.start_date)} to {formatAssignmentDate(assignment.project.end_date)} + + + ) : null} +
+

+ {assignment.project.description || 'No description available.'} +

+
+ +
+ ) : ( + +
+ + No project associated
- - - {assignment.project?.id ? ( - - - -
- -
-
-
-

- {assignment.project.name} -

- -
-
- {assignment.project.code ? ( - - # - {assignment.project.code} - - ) : null} - {assignment.project.year ? ( - - - Year {assignment.project.year} - - ) : null} - {assignment.project.start_date || assignment.project.end_date ? ( - - · - - - {formatAssignmentDate(assignment.project.start_date)} to {formatAssignmentDate(assignment.project.end_date)} - - - ) : null} -
-

- {assignment.project.description || 'No description available.'} -

-
- -
-
- ) : null} - - {assignment.note ? ( - - -

- {assignment.note} -

-
-
- ) : null} - - - 0 ? `${team.length}` : undefined} - action={ -
- {team.length > 0 ? ( -
- - -
- ) : null} - -
- } - > - {team.length === 0 ? ( -
-
- -
-
-

Nobody is assigned yet

-

- Add people from the team directory to start tracking who works on this assignment. -

-
- -
- ) : ( -
- {/* Team Overview Bar */} -
-
- -
-

- {team.length} {team.length === 1 ? 'member assigned' : 'members assigned'} -

-

- {activeTeamCount} active · {positionCount} {positionCount === 1 ? 'role' : 'roles'} -

-
-
- - Viewing {visibleTeam.length} of {team.length} - -
- - {/* Member Roster Display: Grid or List */} - {teamView === 'grid' ? ( -
    - {visibleTeam.map(member => ( - - ))} -
- ) : ( -
    - {visibleTeam.map(member => ( - - ))} -
- )} - - {team.length > TEAM_PREVIEW_LIMIT ? ( - - ) : null} -
- )} -
-
+ )}
+
- {/* Side rail: status history */} - - - {statusHistory.length === 0 ? ( -

- No status changes recorded yet. Use Update Technical Status to log the first one. -

- ) : ( -
    - {statusHistory.map(entry => { - const isCurrent = entry.id === currentEntry?.id; - const span = formatSpan(entry.start_date, entry.end_date); - return ( -
  1. - -
    - {isCurrent ? ( - - ) : ( - - {entry.project_assignment_status.name} - - )} - {isCurrent ? Current : null} -
    -

    - {formatAssignmentDate(entry.start_date)} - {entry.end_date ? formatAssignmentDate(entry.end_date) : 'Present'} -

    - {span ? ( -

    {span}

    - ) : null} - {entry.description ? ( -

    - {entry.description} -

    - ) : null} -
  2. - ); - })} -
- )} + {/* Optional assignment note */} + {assignment.note ? ( + + +

+ {assignment.note} +

-
+ ) : null} + + {/* 5. Team / Scope Section */} + + 0 ? `${team.length}` : undefined} + action={ +
+ {team.length > 0 ? ( +
+ + +
+ ) : null} + +
+ } + > + {team.length === 0 ? ( +
+
+ +
+
+

Nobody is assigned yet

+

+ Add people from the team directory to start tracking who works on this assignment. +

+
+ +
+ ) : ( +
+
+
+ +
+

+ {team.length} {team.length === 1 ? 'member assigned' : 'members assigned'} +

+

+ {activeTeamCount} active · {positionCount} {positionCount === 1 ? 'role' : 'roles'} +

+
+
+ + Viewing {visibleTeam.length} of {team.length} + +
+ + {teamView === 'grid' ? ( +
    + {visibleTeam.map(member => ( + + ))} +
+ ) : ( +
    + {visibleTeam.map(member => ( + + ))} +
+ )} + + {team.length > TEAM_PREVIEW_LIMIT ? ( + + ) : null} +
+ )} +
+
+ {/* Modals */} {action === 'UPDATE_ADMIN_STATUS' ? ( +

{title} @@ -500,7 +521,7 @@ function Surface({ title, meta, action, children }: { title: string; meta?: stri {action}

{children} - +
); } @@ -508,7 +529,7 @@ function Fact({ label, value }: { label: string; value: string }) { return (
{label}
-
{value}
+
{value}
); } @@ -559,7 +580,6 @@ function memberName(member: ProjectAssignmentWorkOrderDetail) { return member.user?.fullname || member.user?.name || 'Unnamed member'; } -/** Overlapping avatars used in the team summary. */ function AvatarStack({ members }: { members: ProjectAssignmentWorkOrderDetail[] }) { const shown = members.slice(0, 5); const extra = members.length - shown.length; @@ -596,7 +616,6 @@ function ContactButton({ href, label, children }: { href: string; label: string; ); } -/** Grid view card for a team member */ function TeamCard({ member }: { member: ProjectAssignmentWorkOrderDetail }) { const user = member.user; const name = memberName(member); @@ -611,7 +630,6 @@ function TeamCard({ member }: { member: ProjectAssignmentWorkOrderDetail }) { ended && 'bg-muted/10 opacity-75' )} > - {/* Top row: Avatar + Identity + Status */}
- {/* Middle row: Assignment Period & Duration pill */}
@@ -671,7 +688,6 @@ function TeamCard({ member }: { member: ProjectAssignmentWorkOrderDetail }) {
- {/* Bottom row: Direct Actions & Contact */}
{user?.email ? ( import('./ActivityHistoryModal').then((mod) => mod.ActivityHistoryModal), + { ssr: false } +); + +interface DevelopmentActivityLogProps { + history?: IProjectAssignmentHistory[]; +} + +export function DevelopmentActivityLog({ history = [] }: DevelopmentActivityLogProps) { + const [selectedItem, setSelectedItem] = useState(null); + const [currentPage, setCurrentPage] = useState(1); + const [itemsPerPage, setItemsPerPage] = useState(5); + + // Sort newest first + const sortedHistory = [...history].sort((a, b) => { + return dayjs(b.created_at).valueOf() - dayjs(a.created_at).valueOf(); + }); + + const totalItems = sortedHistory.length; + const totalPages = Math.max(1, Math.ceil(totalItems / itemsPerPage)); + const safeCurrentPage = Math.min(currentPage, totalPages); + + const startIndex = (safeCurrentPage - 1) * itemsPerPage; + const paginatedItems = sortedHistory.slice(startIndex, startIndex + itemsPerPage); + + const getDotColor = (index: number, desc: string) => { + const lower = desc.toLowerCase(); + if (lower.includes('create')) return 'bg-emerald-500'; + if (lower.includes('assign')) return 'bg-sky-500'; + if (lower.includes('status to active') || lower.includes('status to completed')) return 'bg-emerald-500'; + if (lower.includes('on hold') || lower.includes('issue')) return 'bg-rose-500'; + if (lower.includes('sit') || lower.includes('uat')) return 'bg-purple-500'; + const colors = ['bg-emerald-500', 'bg-sky-500', 'bg-rose-500', 'bg-amber-500', 'bg-indigo-500']; + return colors[index % colors.length]; + }; + + return ( + <> +
+
+

+ + + + Development Activity Log + {totalItems > 0 && ( + + {totalItems} + + )} +

+
+ + {totalItems === 0 ? ( +
+ +

No development activity logs yet

+

+ Status updates and assignment events will be logged here automatically. +

+
+ ) : ( +
+
+ + + + + + + + + + + {paginatedItems.map((item, idx) => { + const globalIndex = startIndex + idx; + const dotColor = getDotColor(globalIndex, item.description); + const formattedDate = dayjs(item.created_at).isValid() + ? dayjs(item.created_at).format('D MMM YYYY') + : 'N/A'; + + return ( + setSelectedItem(item)} + className="group cursor-pointer hover:bg-muted/40 transition-colors" + title="Click to view JSON comparison" + > + {/* Date Column with dot */} + + + {/* Type Column: Left blank per instruction */} + + + {/* Description Column */} + + + {/* Subtle Arrow Chevron */} + + + ); + })} + +
DateTypeDescription
+
+ + {formattedDate} +
+
+ {item.description} + + +
+
+ + {/* Pagination Bar with Show per page selector */} +
+ {/* Left: Show per page & count summary */} +
+
+ Show + + per page +
+ · +
+ Showing {startIndex + 1} to{' '} + + {Math.min(startIndex + itemsPerPage, totalItems)} + {' '} + of {totalItems} logs +
+
+ + {/* Right: Page navigation buttons */} + {totalPages > 1 && ( +
+ + + {Array.from({ length: totalPages }, (_, i) => i + 1).map((pageNum) => ( + + ))} + + +
+ )} +
+
+ )} +
+ + {/* Modal for JSON comparison on row click */} + setSelectedItem(null)} + /> + + ); +} diff --git a/app/(dashboard)/task/client-detail/[client_id]/[assignment_id]/ProjectMilestoneTimeline.tsx b/app/(dashboard)/task/client-detail/[client_id]/[assignment_id]/ProjectMilestoneTimeline.tsx new file mode 100644 index 0000000..c2ab248 --- /dev/null +++ b/app/(dashboard)/task/client-detail/[client_id]/[assignment_id]/ProjectMilestoneTimeline.tsx @@ -0,0 +1,565 @@ +"use client"; + +import { useMemo } from 'react'; +import { ProjectAssignmentStatusDetail, ProjectAssignmentStatus } from '../../../type.assignment'; +import dayjs from 'dayjs'; +import { TrendingUp, ChevronLeft, ChevronRight } from 'lucide-react'; + +interface ProjectMilestoneTimelineProps { + statusDetails?: ProjectAssignmentStatusDetail[]; + technicalStatus?: ProjectAssignmentStatus | null; + startDate?: string | null; + endDate?: string | null; + warrantyDate?: string | null; +} + +/** Formats date strictly if assigned; returns empty string if not set */ +function formatDetailDate(detail?: ProjectAssignmentStatusDetail | null): string { + if (!detail) return ''; + + if (Array.isArray(detail.date) && detail.date.length > 0) { + const validDates = detail.date.filter((d) => Boolean(d?.start_date || d?.end_date)); + if (validDates.length > 0) { + const first = validDates[0]; + const last = validDates[validDates.length - 1]; + const sStr = first?.start_date || first?.end_date; + const eStr = last?.end_date || last?.start_date; + const s = sStr ? dayjs(sStr) : null; + const e = eStr ? dayjs(eStr) : null; + + if (s && s.isValid() && e && e.isValid()) { + if (s.isSame(e, 'day')) return s.format('D MMM YYYY'); + if (s.isSame(e, 'month') && s.isSame(e, 'year')) { + return `${s.format('D')} - ${e.format('D MMM YYYY')}`; + } + if (s.isSame(e, 'year')) { + return `${s.format('D MMM')} - ${e.format('D MMM YYYY')}`; + } + return `${s.format('D MMM YYYY')} - ${e.format('D MMM YYYY')}`; + } + if (s && s.isValid()) return s.format('D MMM YYYY'); + if (e && e.isValid()) return e.format('D MMM YYYY'); + } + } + + const s = detail.start_date ? dayjs(detail.start_date) : null; + const e = detail.end_date ? dayjs(detail.end_date) : null; + + if (s && s.isValid() && e && e.isValid()) { + if (s.isSame(e, 'day')) return s.format('D MMM YYYY'); + if (s.isSame(e, 'month') && s.isSame(e, 'year')) { + return `${s.format('D')} - ${e.format('D MMM YYYY')}`; + } + if (s.isSame(e, 'year')) { + return `${s.format('D MMM')} - ${e.format('D MMM YYYY')}`; + } + return `${s.format('D MMM YYYY')} - ${e.format('D MMM YYYY')}`; + } + if (s && s.isValid()) return s.format('D MMM YYYY'); + if (e && e.isValid()) return e.format('D MMM YYYY'); + + return ''; +} + +export function ProjectMilestoneTimeline({ + statusDetails = [], + technicalStatus, + startDate, + endDate, + warrantyDate, +}: ProjectMilestoneTimelineProps) { + const findDetail = (keyword: string, id?: number) => { + return statusDetails.find( + (d) => + (id && d.project_assignment_status?.id === id) || + (d.project_assignment_status?.name && + d.project_assignment_status.name.toLowerCase().includes(keyword.toLowerCase())) + ); + }; + + const devDetail = findDetail('dev', 6); + const sitDetail = findDetail('sit', 7); + const uatDetail = findDetail('uat', 8); + const ptrDetail = findDetail('ptr', 9); + const deployDetail = findDetail('deploy'); + const goLiveDetail = findDetail('go-live', 10) || findDetail('live'); + const bastDetail = findDetail('bast', 11) || findDetail('handover'); + const warrantyDetail = findDetail('warranty', 12); + + // Start date (empty if not set) + const effectiveStart = startDate || devDetail?.start_date; + const startFormatted = effectiveStart && dayjs(effectiveStart).isValid() + ? dayjs(effectiveStart).format('D MMM YYYY') + : ''; + + // Development intermediate dates strictly from assigned data + const devDates = useMemo(() => { + const list: string[] = []; + if (devDetail) { + if (Array.isArray(devDetail.date) && devDetail.date.length > 0) { + devDetail.date.forEach((item) => { + if (item?.start_date && dayjs(item.start_date).isValid()) { + const f = dayjs(item.start_date).format('D MMM YYYY'); + if (!list.includes(f)) list.push(f); + } + if (item?.end_date && item.end_date !== item.start_date && dayjs(item.end_date).isValid()) { + const f = dayjs(item.end_date).format('D MMM YYYY'); + if (!list.includes(f)) list.push(f); + } + }); + } + if (list.length === 0) { + if (devDetail.start_date && dayjs(devDetail.start_date).isValid()) { + list.push(dayjs(devDetail.start_date).format('D MMM YYYY')); + } + if (devDetail.end_date && devDetail.end_date !== devDetail.start_date && dayjs(devDetail.end_date).isValid()) { + list.push(dayjs(devDetail.end_date).format('D MMM YYYY')); + } + } + } + return list; + }, [devDetail]); + + // Dates for subsequent phases (strictly empty if not set) + const sitDateFormatted = formatDetailDate(sitDetail); + const uatDateFormatted = formatDetailDate(uatDetail); + const ptrDateFormatted = formatDetailDate(ptrDetail); + const deployDateFormatted = formatDetailDate(deployDetail); + const goLiveDateFormatted = formatDetailDate(goLiveDetail); + const bastDateFormatted = formatDetailDate(bastDetail); + + // Warranty dates (strictly empty if not set) + const warrantyStart = warrantyDetail?.start_date && dayjs(warrantyDetail.start_date).isValid() + ? dayjs(warrantyDetail.start_date).format('D MMM YYYY') + : ''; + const warrantyEnd = (warrantyDetail?.end_date || warrantyDate) && dayjs(warrantyDetail?.end_date || warrantyDate).isValid() + ? dayjs(warrantyDetail?.end_date || warrantyDate).format('D MMM YYYY') + : ''; + + // Today's formatted date + const todayFormatted = dayjs().format('D MMM YYYY'); + const todayVal = dayjs().valueOf(); + + // Technical status rank + const techName = technicalStatus?.name?.toLowerCase() || ''; + const techId = technicalStatus?.id; + + let techRank = 0; + if (techId === 6 || techName.includes('dev')) techRank = 1; + else if (techId === 7 || techName.includes('sit')) techRank = 2; + else if (techId === 8 || techName.includes('uat')) techRank = 3; + else if (techId === 9 || techName.includes('ptr')) techRank = 4; + else if (techName.includes('deploy')) techRank = 5; + else if (techId === 10 || techName.includes('go-live') || techName.includes('live')) techRank = 6; + else if (techId === 11 || techName.includes('bast') || techName.includes('handover')) techRank = 7; + else if (techId === 12 || techName.includes('warranty')) techRank = 8; + + // Checkpoint dates + const sitEndTime = (sitDetail?.end_date || sitDetail?.start_date) ? dayjs(sitDetail?.end_date || sitDetail?.start_date).valueOf() : null; + const uatEndTime = (uatDetail?.end_date || uatDetail?.start_date) ? dayjs(uatDetail?.end_date || uatDetail?.start_date).valueOf() : null; + const ptrEndTime = (ptrDetail?.end_date || ptrDetail?.start_date) ? dayjs(ptrDetail?.end_date || ptrDetail?.start_date).valueOf() : null; + const deployEndTime = (deployDetail?.end_date || deployDetail?.start_date) ? dayjs(deployDetail?.end_date || deployDetail?.start_date).valueOf() : null; + const goLiveEndTime = (goLiveDetail?.end_date || goLiveDetail?.start_date) ? dayjs(goLiveDetail?.end_date || goLiveDetail?.start_date).valueOf() : null; + const bastEndTime = (bastDetail?.end_date || bastDetail?.start_date) ? dayjs(bastDetail?.end_date || bastDetail?.start_date).valueOf() : null; + + /** + * Determine dynamic position of 'Today' + * For assignment 36: SIT ended 12 Oct, Today is 14 Oct, UAT starts 15 Oct -> insertAfter = 'sit'! + */ + const insertTodayAfter = useMemo<'start' | 'dev' | 'sit' | 'uat' | 'ptr' | 'deploy' | 'golive' | 'bast'>(() => { + if (bastEndTime && todayVal >= bastEndTime) return 'bast'; + if (techRank >= 7) return 'golive'; + if (goLiveEndTime && todayVal >= goLiveEndTime) return 'golive'; + if (techRank >= 6) return 'deploy'; + if (deployEndTime && todayVal >= deployEndTime) return 'deploy'; + if (techRank >= 5) return 'ptr'; + if (ptrEndTime && todayVal >= ptrEndTime) return 'ptr'; + if (techRank >= 4) return 'uat'; + if (uatEndTime && todayVal >= uatEndTime) return 'uat'; + if (techRank >= 3 || (sitEndTime && todayVal >= sitEndTime)) return 'sit'; + if (sitEndTime && todayVal >= sitEndTime) return 'sit'; + if (techRank >= 2) return 'dev'; + if (effectiveStart && todayVal < dayjs(effectiveStart).valueOf()) return 'start'; + return 'dev'; + }, [todayVal, techRank, bastEndTime, goLiveEndTime, deployEndTime, ptrEndTime, uatEndTime, sitEndTime, effectiveStart]); + + // Active status highlights + const isDevActive = techRank === 1 || techName.includes('dev'); + const isSitActive = techRank === 2; + const isUatActive = techRank === 3; + const isPtrActive = techRank === 4; + const isDeployActive = techRank === 5; + const isGoLiveActive = techRank === 6; + const isBastActive = techRank === 7; + + return ( +
+ {/* Header */} +
+

+ + Project Milestone Timeline +

+
+ + {/* Continuous Timeline Rail Container with Horizontal Scroll */} +
+
+ {/* 1. START NODE */} +
+
+ Start +
+
+
+ + {startFormatted} + +
+
+ + {insertTodayAfter === 'start' && ( + <> +
+
+
+
+ Today +
+
+
+
+
+ + {todayFormatted} + +
+
+ + )} + + {/* Continuous Red Line connecting Start to Development */} +
+ + {/* 2. DEVELOPMENT SECTION */} + {devDates.length > 0 ? ( + devDates.map((dStr, idx) => ( +
+ {idx > 0 &&
} +
+ {idx === 0 && ( +
+ + Development + +
+ )} +
+
+ + {dStr} + +
+
+
+ )) + ) : ( +
+
+ + Development + +
+
+
+ )} + + {insertTodayAfter === 'dev' && ( + <> +
+
+
+
+ Today +
+
+
+
+
+ + {todayFormatted} + +
+
+ + )} + + {/* Continuous Blue Line connecting to SIT */} +
+ + {/* 3. SIT NODE */} +
+
+ + SIT + +
+
+ {sitDateFormatted && ( +
+ + {sitDateFormatted} + +
+ )} +
+ + {insertTodayAfter === 'sit' && ( + <> +
+
+
+
+ Today +
+
+
+
+
+ + {todayFormatted} + +
+
+ + )} + + {/* Continuous Purple Line connecting to UAT */} +
+ + {/* 4. UAT NODE */} +
+
+ + UAT + +
+
+ {uatDateFormatted && ( +
+ + {uatDateFormatted} + +
+ )} +
+ + {insertTodayAfter === 'uat' && ( + <> +
+
+
+
+ Today +
+
+
+
+
+ + {todayFormatted} + +
+
+ + )} + + {/* Continuous Yellow Line connecting to PTR */} +
+ + {/* 5. PTR NODE */} +
+
+ + PTR + +
+
+ {ptrDateFormatted && ( +
+ + {ptrDateFormatted} + +
+ )} +
+ + {insertTodayAfter === 'ptr' && ( + <> +
+
+
+
+ Today +
+
+
+
+
+ + {todayFormatted} + +
+
+ + )} + + {/* Continuous Cyan Line connecting to Deployment */} +
+ + {/* 6. DEPLOYMENT NODE */} +
+
+ + Deployment + +
+
+ {deployDateFormatted && ( +
+ + {deployDateFormatted} + +
+ )} +
+ + {insertTodayAfter === 'deploy' && ( + <> +
+
+
+
+ Today +
+
+
+
+
+ + {todayFormatted} + +
+
+ + )} + + {/* Continuous Pink Line connecting to Go Live */} +
+ + {/* 7. GO LIVE NODE */} +
+
+ + Go Live + +
+
+ {goLiveDateFormatted && ( +
+ + {goLiveDateFormatted} + +
+ )} +
+ + {insertTodayAfter === 'golive' && ( + <> +
+
+
+
+ Today +
+
+
+
+
+ + {todayFormatted} + +
+
+ + )} + + {/* Continuous Rose Line connecting to BAST */} +
+ + {/* 8. BAST NODE */} +
+
+ + BAST + +
+
+ {bastDateFormatted && ( +
+ + {bastDateFormatted} + +
+ )} +
+ + {insertTodayAfter === 'bast' && ( + <> +
+
+
+
+ Today +
+
+
+
+
+ + {todayFormatted} + +
+
+ + )} + + {/* Vertical Dashed Separator */} +
+ + {/* 9. WARRANTY CAPSULE TRACK */} +
+
+ + Warranty + +
+ {/* Capsule with < ---- > indicator */} +
+ +
+ +
+ {/* Dates below warranty: strictly empty if not set */} + {(warrantyStart || warrantyEnd) && ( +
+ {warrantyStart} + {warrantyEnd} +
+ )} +
+
+
+
+ ); +} diff --git a/app/(dashboard)/task/client-detail/[client_id]/[assignment_id]/page.tsx b/app/(dashboard)/task/client-detail/[client_id]/[assignment_id]/page.tsx index 0cf6fe3..5310544 100644 --- a/app/(dashboard)/task/client-detail/[client_id]/[assignment_id]/page.tsx +++ b/app/(dashboard)/task/client-detail/[client_id]/[assignment_id]/page.tsx @@ -15,8 +15,6 @@ export default async function AssignmentDetailPage({ params }: Props) { const [client, assignment] = await Promise.all([getClientById, getAssignmentById]); - // console.log(assignment) - // 3. Handle 404 Securely on the server if (!assignment) { return ( diff --git a/app/(dashboard)/task/type.assignment.ts b/app/(dashboard)/task/type.assignment.ts index 59cd754..adfbfee 100644 --- a/app/(dashboard)/task/type.assignment.ts +++ b/app/(dashboard)/task/type.assignment.ts @@ -34,10 +34,26 @@ export interface IProjectAssignment { wo_warranty: any project_assignment_status_detail: ProjectAssignmentStatusDetail[] project_assignment_work_order_detail: ProjectAssignmentWorkOrderDetail[] + project_assignment_history?: IProjectAssignmentHistory[] status: Status created_at: string } +export interface IProjectAssignmentHistory { + id: number + project_assignment_id: number + description: string + old_data: any + new_data: any + created_at: string + user?: { + id: number + fullname?: string + nickname?: string + avatar?: string | null + } | null +} + export interface Client { id: number code: string diff --git a/app/(dashboard)/task/utils/assignment-overview-helpers.ts b/app/(dashboard)/task/utils/assignment-overview-helpers.ts index 2a9108f..b40b296 100644 --- a/app/(dashboard)/task/utils/assignment-overview-helpers.ts +++ b/app/(dashboard)/task/utils/assignment-overview-helpers.ts @@ -364,9 +364,50 @@ export function resolveProgressColor( return COLOR_SPECTRUM.orange; } +/** + * Extracts the latest assigned end date for the PTR (Production Trial Run) phase if present. + */ +export function getPtrEndDate(assignment: IProjectAssignment): number | null { + const details = assignment.project_assignment_status_detail || []; + const ptrDetail = details.find(d => { + const name = d.project_assignment_status?.name?.toLowerCase() || ''; + return name.includes('ptr') || name.includes('trial'); + }); + + if (!ptrDetail) return null; + + let latestTime: number | null = null; + + const parseTime = (dateStr: any): number | null => { + if (!dateStr || typeof dateStr !== 'string') return null; + const d = new Date(dateStr); + return isNaN(d.getTime()) ? null : d.getTime(); + }; + + if (ptrDetail.end_date) { + latestTime = parseTime(ptrDetail.end_date); + } + + if (Array.isArray(ptrDetail.date) && ptrDetail.date.length > 0) { + ptrDetail.date.forEach((item: any) => { + const t = parseTime(item?.end_date || item?.start_date); + if (t && (!latestTime || t > latestTime)) { + latestTime = t; + } + }); + } + + if (!latestTime && ptrDetail.start_date) { + latestTime = parseTime(ptrDetail.start_date); + } + + return latestTime; +} + /** * 3. Delivery Health Status (Summary Progress) Logic: * - Complete (Sky Blue) => sama atau lewat deadline, namun project_assignment_technical_status.name atau project_assignment_status_detail sudah sampai ke Go-Live (rank >= 5) + * - Near Go-live (Warna Teal) => technical status sudah lewat PTR dan tanggal hari ini sudah lewat dari tanggal PTR tapi masih dalam rentang end of date dan status belum sampai ke Go-Live * - At Risk (Warna Kuning) => progress lewat dari 75% dan namun project_assignment_technical_status.name atau project_assignment_status_detail belum sampai ke PTR (rank < 4) * - Off Track / Critical (Warna Merah) => sama atau lewat deadline and namun project_assignment_technical_status.name atau project_assignment_status_detail belum sampai ke Go-Live status (rank < 5) * - On Track (Warna Hijau) => Belum lewat deadline dan progres sejalan dengan target (progress <= 75%, atau sudah sampai ke PTR) @@ -375,7 +416,8 @@ export function resolveDeliveryHealth( technicalRank: number, hasTechnicalStatus: boolean, progressPercent: number, - endDate?: string + endDate?: string, + ptrEndDate?: number | null ): { healthStatus: 'On Track' | 'At Risk' | 'Near Go-live' | 'Completed' | 'Critical' | 'Off Track'; healthBadgeClass: string; @@ -412,7 +454,7 @@ export function resolveDeliveryHealth( // KONDISI 2: Belum lewat deadline (atau tidak ada endDate) - // Sudah sampai ke Go-Live sebelum deadline -> Complete (Sky Blue) + // 1. Sudah sampai ke Go-Live sebelum deadline -> Complete (Sky Blue) if (technicalRank >= 5) { return { healthStatus: 'Completed', @@ -422,7 +464,18 @@ export function resolveDeliveryHealth( }; } - // At Risk (Warna Kuning) => progress lewat dari 75% dan belum sampai ke PTR (rank < 4) + // 2. Near Go-live (Warna Teal) => Technical status sudah lewat PTR (rank >= 4), tanggal hari ini sudah lewat dari tanggal PTR tapi masih dalam rentang end of date, dan technical status belum sampai ke Go-Live (rank < 5) + const isPastPtrDate = typeof ptrEndDate === 'number' ? now >= ptrEndDate : (technicalRank >= 4 && progressPercent >= 75); + if (technicalRank >= 4 && isPastPtrDate) { + return { + healthStatus: 'Near Go-live', + healthBadgeClass: 'bg-teal-500/10 text-teal-600 dark:text-teal-400 border-teal-500/30', + healthDotClass: 'bg-teal-500', + isCritical: false, + }; + } + + // 3. At Risk (Warna Kuning) => progress lewat dari 75% dan belum sampai ke PTR (rank < 4) if (progressPercent > 75 && technicalRank < 4) { return { healthStatus: 'At Risk', @@ -432,9 +485,7 @@ export function resolveDeliveryHealth( }; } - // On Track (Warna Hijau) => Belum lewat deadline dan progres sejalan dengan target: - // - Progress <= 75%, ATAU - // - Progress > 75% tapi status teknis sudah mengimbangi dengan mencapai minimal PTR (rank >= 4) + // 4. On Track (Warna Hijau) => Belum lewat deadline dan progres sejalan dengan target return { healthStatus: 'On Track', healthBadgeClass: 'bg-emerald-500/10 text-emerald-600 dark:text-emerald-400 border-emerald-500/30', @@ -446,7 +497,7 @@ export function resolveDeliveryHealth( /** * Calculates complete visual representation for an assignment row */ -export function getAssignmentOverview(assignment: IProjectAssignment, index: number): AssignmentOverview { +export function getAssignmentOverview(assignment: IProjectAssignment, index: number = 0): AssignmentOverview { const isProject = !!assignment.wo_name; const assignmentType = isProject ? 'Work Order' : 'Internal Memo'; const title = assignment.wo_name || assignment.im_name || assignment.project?.name || 'Untitled Assignment'; @@ -493,11 +544,13 @@ export function getAssignmentOverview(assignment: IProjectAssignment, index: num // 2. Resolve Technical Status & Delivery Health const { hasTechnicalStatus, technicalRank } = resolveTechnicalStatus(assignment); + const ptrEndDate = getPtrEndDate(assignment); const { healthStatus, healthBadgeClass, healthDotClass, isCritical } = resolveDeliveryHealth( technicalRank, hasTechnicalStatus, progressPercent, - endDate + endDate, + ptrEndDate ); // 3. Resolve Progress Color (Orange -> Kuning -> Hijau -> Biru -> Ungu) @@ -528,6 +581,10 @@ export function getAssignmentOverview(assignment: IProjectAssignment, index: num } else if (healthStatus === 'Completed') { remainingText = endDate ? `Completed on ${formatAssignmentDate(endDate)}` : 'Completed'; nextMilestoneText = 'Next: -'; + } else if (healthStatus === 'Near Go-live') { + const remDays = Math.max(1, totalDays - elapsedDays); + remainingText = `${remDays} days remaining`; + nextMilestoneText = 'Next: Production Go-Live'; } else if (healthStatus === 'At Risk') { const remDays = Math.max(1, totalDays - elapsedDays); remainingText = `${remDays} days remaining`; @@ -570,6 +627,8 @@ export function getAssignmentOverview(assignment: IProjectAssignment, index: num }; } +export const buildAssignmentOverview = getAssignmentOverview; + /** * Calculates top executive summary metrics for "Project Assignment Dashboard" */ @@ -600,7 +659,7 @@ export function calculateDashboardStats(assignments: IProjectAssignment[]) { : 0; // On-Time projects vs Total - const onTimeCount = overviews.filter(o => o.healthStatus === 'On Track' || o.healthStatus === 'Completed').length; + const onTimeCount = overviews.filter(o => o.healthStatus === 'On Track' || o.healthStatus === 'Completed' || o.healthStatus === 'Near Go-live').length; const atRiskCount = overviews.filter(o => o.healthStatus === 'At Risk' || o.healthStatus === 'Critical' || o.healthStatus === 'Off Track').length; return {