- {/* Title */}
-
+ {/* Middle Section: Title, End User & Date with Tooltips */}
+
+
+ {item.title}
+
- {/* Project Reference */}
- {assignment.project?.name && (
-
-
- Project:
- {projectDetailUrl ? (
-
- {assignment.project.name}
-
-
- ) : (
- {assignment.project.name}
- )}
-
- )}
-
- {/* Origin IM Reference (for converted assignments without project) */}
- {!assignment.project?.name && (assignment.im?.im_name || (assignment.im_id && assignment.im_name)) && (
-
-
-
Origin IM:
- {effectiveClientId && (assignment.im_id || assignment.im?.id) ? (
-
-
{assignment.im?.im_name || assignment.im_name}
-
-
- ) : (
-
{assignment.im?.im_name || assignment.im_name}
- )}
-
- )}
-
- {/* Description */}
- {assignmentDesc && (
-
- {assignmentDesc}
-
- )}
-
- {/* Client & End User Badges */}
-
- {assignment.client?.name && !clientId && (
-
+
+ {item.endUserName &&
+
-
Client:
-
{assignment.client.name}
-
- )}
-
- {assignment.end_user?.name && (
-
-
-
-
-
End User:
-
{assignment.end_user.name}
-
- )}
-
-
-
- {/* Footer: Timeline & Team Members */}
-
-
-
-
-
-
- {formatAssignmentDate(assignmentStartDate)} – {formatAssignmentDate(assignmentEndDate)}
+
+ End User: {item.endUserName}
-
-
- Assignment Timeline
-
- Start: {formatAssignmentDate(assignmentStartDate)}
-
-
- End: {formatAssignmentDate(assignmentEndDate)}
-
-
-
+ }
- {/* Assigned Team */}
-
- {assignment.project_assignment_work_order_detail?.slice(0, 4).map((item, key) => (
-
-
-
-
-
-
-
-
- {item?.user?.fullname || item?.user?.name}
- {item?.user?.position?.name || 'Team Member'}
-
-
-
- ))}
- {assignment.project_assignment_work_order_detail && assignment.project_assignment_work_order_detail.length > 4 && (
-
- +{assignment.project_assignment_work_order_detail.length - 4}
-
- )}
- {(!assignment.project_assignment_work_order_detail || assignment.project_assignment_work_order_detail.length === 0) && (
-
No team
+
+
+
+
+ {item.formattedDateRange}
+
+
+
+ Assignment Timeline
+
+ Start: {item.startDate ? formatAssignmentDate(item.startDate) : 'Start date not set'}
+
+
+ End: {item.endDate ? formatAssignmentDate(item.endDate) : 'End date not set'}
+
+
+
+
+
+
+ {/* Progress & Stepper Section */}
+
+
+
{item.daysRatioText}
+
+
{item.progressPercent}%
+
+
+
+
+
+ {/* Footer: Delivery Health Badge & Team Avatars */}
+
+
+
+
+ {item.healthStatus}
+
+
{item.remainingText}
+
+
+
+ {item.teamMembers.length > 0 ? (
+ <>
+
+ {item.teamMembers.slice(0, 3).map((m, mIdx) => (
+
+
+
+
+
+
+
+ {m.name}
+ {m.position || 'Team Member'}
+
+
+ ))}
+
+
{item.teamCount}p
+ >
+ ) : (
+
None
)}
+
);
@@ -345,3 +351,4 @@ export default function AssignmentGrid({
);
}
+
diff --git a/app/(dashboard)/task/component/project-assignment/AssignmentList.tsx b/app/(dashboard)/task/component/project-assignment/AssignmentList.tsx
index 177cea9..c16acdd 100644
--- a/app/(dashboard)/task/component/project-assignment/AssignmentList.tsx
+++ b/app/(dashboard)/task/component/project-assignment/AssignmentList.tsx
@@ -3,7 +3,6 @@
import { IProjectAssignment } from '../../type.assignment';
import { motion } from 'motion/react';
import { Card900, CardContent } from '@/components/ui/card';
-import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import {
DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger,
@@ -12,21 +11,69 @@ import {
Tooltip, TooltipContent, TooltipTrigger,
} from '@/components/ui/tooltip';
import { LazyImage } from '@/components/ui/lazy-image';
-import { Briefcase, Calendar, MoreVertical, FolderGit2, FileText, BuildingComplex, ArrowUpRight } from 'lucide-react';
+import { Calendar, MoreVertical, ArrowUpRight } from 'lucide-react';
import Link from 'next/link';
-import BadgeStatus from '@/components/ui/badge-status';
+import { cn } from '@/lib/utils';
import ConvertedAssignmentBadge from './ConvertedAssignmentBadge';
+import BadgeStatus from '@/components/ui/badge-status';
+import {
+ getAssignmentOverview,
+ formatAssignmentDate,
+ ProgressColorConfig
+} from '../../utils/assignment-overview-helpers';
+import { END_USER_FALLBACK_IMAGE } from '../../types';
-export const formatAssignmentDate = (dateStr?: string) => {
- if (!dateStr) return 'N/A';
- const d = new Date(dateStr);
- if (isNaN(d.getTime())) return 'N/A';
- const day = String(d.getDate()).padStart(2, '0');
- const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
- const month = months[d.getMonth()];
- const year = d.getFullYear();
- return `${day} ${month} ${year}`;
-};
+export { formatAssignmentDate };
+
+const STEPPER_STAGES = ['Dev', 'SIT', 'UAT', 'PTR', 'Live'] as const;
+
+function PhaseStepper({ phaseIndex, progressColor }: { phaseIndex: number; progressColor: ProgressColorConfig }) {
+ return (
+
+ {/* Background Rail Line */}
+
+
+ {/* Active Colored Fill Line */}
+
+
+ {/* 5 Milestone Stage Nodes */}
+
+ {STEPPER_STAGES.map((stage, i) => {
+ const isCompleted = i < phaseIndex;
+ const isActive = i === phaseIndex;
+
+ return (
+
+ {isActive ? (
+
+ ) : isCompleted ? (
+
+ ) : (
+
+ )}
+
+
+ {stage}
+
+
+ );
+ })}
+
+
+ );
+}
interface AssignmentListProps {
assignments: IProjectAssignment[];
@@ -46,17 +93,9 @@ export default function AssignmentList({
onDelete,
}: AssignmentListProps) {
return (
-
+
{assignments.map((assignment, index) => {
- const isProject = !!assignment.wo_name;
- const assignmentType = isProject ? 'Work Order' : 'Internal Memo';
- const assignmentName = assignment.wo_name || assignment.im_name || assignment.project?.name || 'Untitled Assignment';
- const assignmentCode = assignment.wo_code || assignment.im_code || assignment.project?.code;
- const assignmentStartDate = assignment.wo_start_date || assignment.im_start_date || assignment.project?.start_date;
- const assignmentEndDate = assignment.wo_end_date || assignment.im_end_date || assignment.project?.end_date;
- const assignmentStatus = assignment.project_assignment_status?.name || assignment.project?.status;
-
- const illustrationSrc = isProject ? '/assets/illustrations/work_order.jpg' : '/assets/illustrations/internal_memo.jpg';
+ const item = getAssignmentOverview(assignment, index);
const effectiveClientId = clientId || assignment.client?.id;
const assignmentDetailUrl = effectiveClientId ? `/task/client-detail/${effectiveClientId}/${assignment.id}` : '#';
@@ -64,245 +103,275 @@ export default function AssignmentList({
const editAssignmentUrl = effectiveClientId
? `/task/client-detail/${effectiveClientId}/project-assignments?is_edit=true&assignment_id=${assignment.id}`
: `/task/project-assignment?is_edit=true&assignment_id=${assignment.id}`;
- const promoteAssignmentUrl = !isProject
+ const promoteAssignmentUrl = !item.isProject
? (effectiveClientId
? `/task/client-detail/${effectiveClientId}/project-assignments?is_edit=true&assignment_id=${assignment.id}&promote=true`
: `/task/project-assignment?is_edit=true&assignment_id=${assignment.id}&promote=true`)
: null;
+ const illustrationSrc = item.isProject ? '/assets/illustrations/work_order.jpg' : '/assets/illustrations/internal_memo.jpg';
+
return (
-
-
- {/* Left: Thumbnail & Visual Indicator */}
-
+
+
+
+ {/* 1. LEFT: Thumbnail, Badges & Assignment Details */}
+
+ {/* 3D Dossier Folder Thumbnail */}
- {/* Center Details */}
+ {/* Identity, Badges, Title & Timeline */}
- {/* Line 1: Type Badge, Status, Code, and Project Reference */}
-
-
- {isProject ? : }
- {assignmentType}
-
+ {/* Line 1: Type Pill, Status Pill, Code Pill & Converted Badge */}
+
+ {/* Type pill: Work Order / Internal Memo */}
+
+
+ {item.assignmentType}
+
-
+ {/* Project Status Badge matching technical status badge colors */}
+
- {assignmentStatus &&
}
-
- {assignmentCode ? (
+ {/* Code Pill with Tooltip */}
+ {item.code ? (
-
- # {assignmentCode}
+
+ # {item.code}
- {isProject ? 'Work Order Code' : 'Internal Memo Code'}
- #{assignmentCode}
+ Assignment Code
+ {item.code}
) : null}
+
+ {/* Converted Badge (kept with hover card) */}
+
{/* Line 2: Assignment Title */}
- {assignmentName}
+ {item.title}
- {assignment.project?.name && (
-
-
- Project:
- {projectDetailUrl ? (
-
- {assignment.project.name}
-
- ) : (
- {assignment.project.name}
- )}
-
- )}
- {/* Line 3: Metadata, Client, End User, Timeline, Notes */}
-
- {assignment.client?.name && !clientId && (
-
-
-
Client:
-
{assignment.client.name}
-
- )}
-
- {assignment.end_user?.name && (
-
-
End User:
-
{assignment.end_user.name}
+ {/* Line 3: End User & Timeline with Tooltips */}
+
+ {item.endUserName && (
+
+
+
+ End User: {item.endUserName}
+
)}
-
-
-
- {formatAssignmentDate(assignmentStartDate)} – {formatAssignmentDate(assignmentEndDate)}
-
+
+
+ {item.formattedDateRange}
-
- Assignment Timeline
+
+ Assignment Timeline
- Start: {formatAssignmentDate(assignmentStartDate)}
+ Start: {item.startDate ? formatAssignmentDate(item.startDate) : 'Start date not set'}
- End: {formatAssignmentDate(assignmentEndDate)}
+ End: {item.endDate ? formatAssignmentDate(item.endDate) : 'End date not set'}
-
- {assignment.note && (
-
- Note: {assignment.note}
-
- )}
- {/* Right: Team Stack & Actions */}
-
- {/* Team Avatar Stack */}
-
- {assignment.project_assignment_work_order_detail?.slice(0, 4).map((item, key) => (
-
-
-
-
-
-
-
-
- {item?.user?.fullname || item?.user?.name}
- {item?.user?.position?.name || 'Team Member'}
-
-
-
- ))}
- {assignment.project_assignment_work_order_detail && assignment.project_assignment_work_order_detail.length > 4 && (
-
- +{assignment.project_assignment_work_order_detail.length - 4}
-
- )}
- {(!assignment.project_assignment_work_order_detail || assignment.project_assignment_work_order_detail.length === 0) && (
-
No team assigned
- )}
+ {/* 2. CENTER: Progress Bar & 5-Node Stepper Track */}
+
+ {/* Days ratio, Dynamic color Progress bar & Percentage */}
+
+
{item.daysRatioText}
+
+
{item.progressPercent}%
- {/* Action Buttons */}
-
-
-
-
-
-
- {promoteAssignmentUrl && (
-
-
-
- Promote to Project
-
-
- )}
-
- View Assignment Details
-
- {projectDetailUrl && (
-
- View Project Details
-
- )}
- {!clientId && assignment.client?.id && (
-
- View Client
-
- )}
- {editAssignmentUrl && (
-
- Edit Assignment
-
- )}
- {onManageTeam && (
- onManageTeam(assignment)}>
- Manage Team
-
- )}
- {onUpdateAdministrationStatus && (
- onUpdateAdministrationStatus(assignment)}>
- Update Administration Status
-
- )}
- {onUpdateStatus && (
- onUpdateStatus(assignment)}>
- Update Technical Status
-
- )}
- {onDelete && (
- onDelete(assignment)}
- className="text-destructive focus:text-destructive"
- >
- Delete
-
- )}
-
-
+ {/* 5-Node Milestone Stepper Rail */}
+
+
+
+ {/* 3. TEAM: Assigned People Count & Avatar Stack */}
+
+
+ {item.teamCount} people
+
+
+ {item.teamMembers.length > 0 ? (
+ <>
+ {item.teamMembers.slice(0, 3).map((m, mIdx) => (
+
+
+
+
+
+
+
+ {m.name}
+ {m.position || 'Team Member'}
+
+
+ ))}
+ {item.teamCount > 3 ? (
+
+ +{item.teamCount - 3}
+
+ ) : null}
+ >
+ ) : (
+
None
+ )}
+
+ {/* 4. RIGHT: Delivery Health Badge, Schedule, Next Step & Updated */}
+
+
+ {/* Health Badge */}
+
+
+
+ {item.healthStatus}
+
+
+
+ {/* Remaining days or completion date */}
+
+
+ {item.remainingText}
+
+
+ {/* Next Milestone & Timestamp */}
+
+ {item.nextMilestoneText}
+ {item.updatedAgoText}
+
+
+
+ {/* 5. ACTIONS: Vertical 3-dots Menu */}
+
+
+
+
+
+ {promoteAssignmentUrl && (
+
+
+
+ Promote to Project
+
+
+ )}
+
+ View Assignment Details
+
+ {projectDetailUrl && (
+
+ View Project Details
+
+ )}
+ {!clientId && assignment.client?.id && (
+
+ View Client
+
+ )}
+ {editAssignmentUrl && (
+
+ Edit Assignment
+
+ )}
+ {onManageTeam && (
+ onManageTeam(assignment)}>
+ Manage Team
+
+ )}
+ {onUpdateAdministrationStatus && (
+ onUpdateAdministrationStatus(assignment)}>
+ Update Administration Status
+
+ )}
+ {onUpdateStatus && (
+ onUpdateStatus(assignment)}>
+ Update Technical Status
+
+ )}
+ {onDelete && (
+ onDelete(assignment)}
+ className="text-destructive focus:text-destructive"
+ >
+ Delete
+
+ )}
+
+
+
@@ -311,3 +380,4 @@ export default function AssignmentList({
);
}
+
diff --git a/app/(dashboard)/task/component/project-assignment/ProjectAssignmentDashboardStats.tsx b/app/(dashboard)/task/component/project-assignment/ProjectAssignmentDashboardStats.tsx
new file mode 100644
index 0000000..086dbdc
--- /dev/null
+++ b/app/(dashboard)/task/component/project-assignment/ProjectAssignmentDashboardStats.tsx
@@ -0,0 +1,108 @@
+"use client";
+
+import { useMemo } from 'react';
+import { motion } from 'motion/react';
+import { Briefcase, FileText, Users, TrendingUp, CheckCircle2, AlertTriangle } from 'lucide-react';
+import { Card900 } from '@/components/ui/card';
+import { IProjectAssignment } from '../../type.assignment';
+import { calculateDashboardStats } from '../../utils/assignment-overview-helpers';
+
+interface ProjectAssignmentDashboardStatsProps {
+ assignments: IProjectAssignment[];
+ className?: string;
+}
+
+export default function ProjectAssignmentDashboardStats({
+ assignments,
+ className = '',
+}: ProjectAssignmentDashboardStatsProps) {
+ const stats = useMemo(() => calculateDashboardStats(assignments), [assignments]);
+
+ return (
+
+
+ Project Assignment Dashboard
+
+
+
+ {/* 1. Total Projects */}
+
+
+
+
+
+
+
Total Projects
+
{stats.totalProjects}
+
+
+
+
+ {/* 2. Active Work Orders */}
+
+
+
+
+
+
+
Active Work Orders
+
{stats.activeWorkOrders}
+
+
+
+
+ {/* 3. Assigned People */}
+
+
+
+
+
+
+
Assigned People
+
{stats.assignedPeople} people
+
+
+
+
+ {/* 4. Average Progress */}
+
+
+
+
+
+
+
Average Progress
+
{stats.averageProgress}%
+
+
+
+
+ {/* 5. On-Time Projects */}
+
+
+
+
+
+
+
On-Time Projects
+
{stats.onTimeRatio}
+
+
+
+
+ {/* 6. At Risk / Delayed */}
+
+
+
+
+
At Risk / Delayed
+
{stats.atRiskDelayed}
+
+
+
+
+
+ );
+}
diff --git a/app/(dashboard)/task/type.assignment.ts b/app/(dashboard)/task/type.assignment.ts
index f32781f..59cd754 100644
--- a/app/(dashboard)/task/type.assignment.ts
+++ b/app/(dashboard)/task/type.assignment.ts
@@ -25,6 +25,7 @@ export interface IProjectAssignment {
project?: Project
project_assignment_status: ProjectStatus
project_assignment_status_notes?: string
+ project_assignment_technical_status?: ProjectAssignmentStatus | null
wo_code: string
wo_description: string
wo_name: string
diff --git a/app/(dashboard)/task/utils/assignment-overview-helpers.ts b/app/(dashboard)/task/utils/assignment-overview-helpers.ts
new file mode 100644
index 0000000..2a9108f
--- /dev/null
+++ b/app/(dashboard)/task/utils/assignment-overview-helpers.ts
@@ -0,0 +1,614 @@
+import { IProjectAssignment } from '../type.assignment';
+
+export interface ProgressColorConfig {
+ name: 'orange' | 'yellow' | 'green' | 'blue' | 'purple' | 'red';
+ label: string;
+ hex: string;
+ barColor: string;
+ textColor: string;
+ glowRing: string;
+ activeDot: string;
+ badgeBg: string;
+ badgeText: string;
+ badgeBorder: string;
+}
+
+export const COLOR_SPECTRUM: Record
= {
+ orange: {
+ name: 'orange',
+ label: 'Awal',
+ hex: '#ea512c',
+ barColor: 'bg-[#ea512c]',
+ textColor: 'text-[#ea512c]',
+ glowRing: 'ring-4 ring-[#ea512c]/30 shadow-[0_0_12px_rgba(234,81,44,0.6)]',
+ activeDot: 'bg-[#ea512c]',
+ badgeBg: 'bg-[#ea512c]/15',
+ badgeText: 'text-[#ea512c]',
+ badgeBorder: 'border-[#ea512c]/30',
+ },
+ yellow: {
+ name: 'yellow',
+ label: 'Menuju Pertengahan',
+ hex: '#eab308',
+ barColor: 'bg-[#eab308]',
+ textColor: 'text-[#eab308]',
+ glowRing: 'ring-4 ring-[#eab308]/30 shadow-[0_0_12px_rgba(234,179,8,0.6)]',
+ activeDot: 'bg-[#eab308]',
+ badgeBg: 'bg-[#eab308]/15',
+ badgeText: 'text-[#eab308]',
+ badgeBorder: 'border-[#eab308]/30',
+ },
+ green: {
+ name: 'green',
+ label: 'Pertengahan',
+ hex: '#10b981',
+ barColor: 'bg-[#10b981]',
+ textColor: 'text-[#10b981]',
+ glowRing: 'ring-4 ring-[#10b981]/30 shadow-[0_0_12px_rgba(16,185,129,0.6)]',
+ activeDot: 'bg-[#10b981]',
+ badgeBg: 'bg-[#10b981]/15',
+ badgeText: 'text-[#10b981]',
+ badgeBorder: 'border-[#10b981]/30',
+ },
+ blue: {
+ name: 'blue',
+ label: 'Lanjut',
+ hex: '#3b82f6',
+ barColor: 'bg-[#3b82f6]',
+ textColor: 'text-[#3b82f6]',
+ glowRing: 'ring-4 ring-[#3b82f6]/30 shadow-[0_0_12px_rgba(59,130,246,0.6)]',
+ activeDot: 'bg-[#3b82f6]',
+ badgeBg: 'bg-[#3b82f6]/15',
+ badgeText: 'text-[#3b82f6]',
+ badgeBorder: 'border-[#3b82f6]/30',
+ },
+ purple: {
+ name: 'purple',
+ label: 'Mendekati End of Date',
+ hex: '#a855f7',
+ barColor: 'bg-[#a855f7]',
+ textColor: 'text-[#a855f7]',
+ glowRing: 'ring-4 ring-[#a855f7]/30 shadow-[0_0_12px_rgba(168,85,247,0.6)]',
+ activeDot: 'bg-[#a855f7]',
+ badgeBg: 'bg-[#a855f7]/15',
+ badgeText: 'text-[#a855f7]',
+ badgeBorder: 'border-[#a855f7]/30',
+ },
+ red: {
+ name: 'red',
+ label: 'Critical / Off Track',
+ hex: '#f43f5e',
+ barColor: 'bg-rose-500',
+ textColor: 'text-rose-500 dark:text-rose-400',
+ glowRing: 'ring-4 ring-rose-500/30 shadow-[0_0_12px_rgba(244,63,94,0.6)]',
+ activeDot: 'bg-rose-500',
+ badgeBg: 'bg-rose-500/15 dark:bg-rose-500/20',
+ badgeText: 'text-rose-600 dark:text-rose-400',
+ badgeBorder: 'border-rose-500/30',
+ },
+};
+
+export interface AssignmentOverview {
+ assignmentType: 'Work Order' | 'Internal Memo';
+ isProject: boolean;
+ title: string;
+ code?: string;
+ startDate?: string;
+ endDate?: string;
+ formattedDateRange: string;
+ endUserName?: string;
+ endUserPhoto?: string | null;
+ clientName?: string;
+
+ // Project Status (derived from project_assignment_status_detail or project_assignment_status.name)
+ projectStatusName: string;
+ isFromDetail: boolean;
+
+ // Stepper Phase (0: Dev, 1: SIT, 2: UAT, 3: PTR, 4: Live)
+ phaseIndex: number;
+
+ // Progress metrics & Dynamic Progress Color
+ elapsedDays: number;
+ totalDays: number;
+ daysRatioText: string;
+ progressPercent: number;
+ progressColor: ProgressColorConfig;
+
+ // Team
+ teamCount: number;
+ teamMembers: Array<{
+ id: number | string;
+ name: string;
+ avatar?: string | null;
+ position?: string;
+ }>;
+
+ // Delivery Health & Next Step
+ healthStatus: 'On Track' | 'At Risk' | 'Near Go-live' | 'Completed' | 'Critical' | 'Off Track';
+ healthBadgeClass: string;
+ healthDotClass: string;
+ remainingText: string;
+ nextMilestoneText: string;
+ updatedAgoText: string;
+}
+
+export function formatAssignmentDate(dateStr?: string) {
+ if (!dateStr) return 'N/A';
+ const d = new Date(dateStr);
+ if (isNaN(d.getTime())) return 'N/A';
+ const day = String(d.getDate()).padStart(2, '0');
+ const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
+ const month = months[d.getMonth()];
+ const year = d.getFullYear();
+ return `${day} ${month} ${year}`;
+}
+
+export function formatRelativeTime(dateStr?: string): string {
+ if (!dateStr) return 'Updated 1 day ago';
+ const d = new Date(dateStr);
+ if (isNaN(d.getTime())) return 'Updated 1 day ago';
+ const diffSec = Math.floor((Date.now() - d.getTime()) / 1000);
+ if (diffSec < 3600) return 'Updated just now';
+ const diffHours = Math.floor(diffSec / 3600);
+ if (diffHours < 24) return `Updated ${diffHours} hour${diffHours > 1 ? 's' : ''} ago`;
+ const diffDays = Math.floor(diffHours / 24);
+ if (diffDays < 7) return `Updated ${diffDays} day${diffDays > 1 ? 's' : ''} ago`;
+ const diffWeeks = Math.floor(diffDays / 7);
+ return `Updated ${diffWeeks} week${diffWeeks > 1 ? 's' : ''} ago`;
+}
+
+// Helper: checks if a detail entry has ANY assigned dates
+export const hasAssignedDates = (d: any): boolean => {
+ if (!d) return false;
+ if (d.start_date || d.end_date) return true;
+ if (Array.isArray(d.date) && d.date.length > 0) {
+ return d.date.some((item: any) => Boolean(item?.start_date || item?.end_date));
+ }
+ if (typeof d.date === 'string' && d.date.trim().length > 0) return true;
+ return false;
+};
+
+/**
+ * Urutan technical status:
+ * 1. development -> 2. SIT -> 3. UAT -> 4. PTR -> 5. Go-Live -> 6. BAST -> 7. Warranty
+ */
+export function getTechnicalStageRank(rawName?: string | null): number {
+ if (!rawName) return 0;
+ const lower = rawName.toLowerCase();
+ if (lower.includes('warranty')) return 7;
+ if (lower.includes('bast') || lower.includes('handover')) return 6;
+ if (lower.includes('go-live') || lower.includes('live')) return 5;
+ if (lower.includes('ptr') || lower.includes('trial')) return 4;
+ if (lower.includes('uat') || lower.includes('acceptance')) return 3;
+ if (lower.includes('sit') || lower.includes('integration')) return 2;
+ if (lower.includes('dev') || lower.includes('development')) return 1;
+ if (lower.includes('complete') || lower.includes('done')) return 5;
+ return 0;
+}
+
+/**
+ * 1. Derives project status:
+ * Taken from project_assignment_status_detail, if not present or all dates are null fallback to project_assignment_status.name
+ */
+export function resolveProjectStatus(assignment: IProjectAssignment, indexFallback = 0): {
+ statusName: string;
+ isFromDetail: boolean;
+ phaseIndex: number;
+} {
+ const details = assignment.project_assignment_status_detail || [];
+
+ // Filter only entries that actually have dates assigned
+ const detailsWithDates = details.filter(hasAssignedDates);
+
+ // If NO detail has dates assigned (e.g. all start_date/end_date/date are null)
+ // -> Fallback directly to project_assignment_status.name
+ if (detailsWithDates.length === 0) {
+ if (assignment.project_assignment_status?.name) {
+ const name = assignment.project_assignment_status.name;
+ return {
+ statusName: name,
+ isFromDetail: false,
+ phaseIndex: mapStatusNameToPhaseIndex(name),
+ };
+ }
+ return {
+ statusName: 'Not Started',
+ isFromDetail: false,
+ phaseIndex: 0,
+ };
+ }
+
+ // If there ARE details with assigned dates:
+ // Determine which detail is active right now or the latest assigned stage
+ const now = Date.now();
+ let activeDetail: any = null;
+
+ for (let i = 0; i < detailsWithDates.length; i++) {
+ const d = detailsWithDates[i];
+ const sTime = d.start_date ? new Date(d.start_date).getTime() : null;
+ const eTime = d.end_date ? new Date(d.end_date).getTime() : null;
+
+ if (sTime && eTime) {
+ if (now >= sTime && now <= eTime) {
+ activeDetail = d;
+ break;
+ }
+ } else if (sTime && !eTime) {
+ if (now >= sTime) {
+ activeDetail = d;
+ break;
+ }
+ } else if (Array.isArray(d.date)) {
+ const matchInterval = d.date.some((item: any) => {
+ const s = item?.start_date ? new Date(item.start_date).getTime() : null;
+ const e = item?.end_date ? new Date(item.end_date).getTime() : null;
+ return s && e && now >= s && now <= e;
+ });
+ if (matchInterval) {
+ activeDetail = d;
+ break;
+ }
+ }
+ }
+
+ // If no stage is active today, pick the latest stage with dates (last one in chronological progression)
+ const chosen = activeDetail || detailsWithDates[detailsWithDates.length - 1];
+ const rawName = chosen?.project_assignment_status?.name || assignment.project_assignment_status?.name || 'Active';
+
+ return {
+ statusName: formatShortPhaseName(rawName),
+ isFromDetail: true,
+ phaseIndex: mapStatusNameToPhaseIndex(rawName),
+ };
+}
+
+/**
+ * Resolves technical status from either project_assignment_technical_status.name
+ * OR the highest reached stage in project_assignment_status_detail (with assigned dates).
+ */
+export function resolveTechnicalStatus(assignment: IProjectAssignment): {
+ technicalStatusName: string | null;
+ hasTechnicalStatus: boolean;
+ technicalRank: number;
+} {
+ // 1. Check project_assignment_technical_status
+ const techName = assignment.project_assignment_technical_status?.name || null;
+ const rankTech = techName ? getTechnicalStageRank(techName) : 0;
+
+ // 2. Check project_assignment_status_detail for dated entries
+ const details = assignment.project_assignment_status_detail || [];
+ let maxDetailRank = 0;
+ let maxDetailName: string | null = null;
+
+ details.forEach(d => {
+ if (hasAssignedDates(d) && d.project_assignment_status?.name) {
+ const r = getTechnicalStageRank(d.project_assignment_status.name);
+ if (r > maxDetailRank) {
+ maxDetailRank = r;
+ maxDetailName = d.project_assignment_status.name;
+ }
+ }
+ });
+
+ const technicalRank = Math.max(rankTech, maxDetailRank);
+ const hasTechnicalStatus = technicalRank > 0;
+ const technicalStatusName = (rankTech >= maxDetailRank && techName)
+ ? techName
+ : (maxDetailName || techName || null);
+
+ return {
+ technicalStatusName,
+ hasTechnicalStatus,
+ technicalRank,
+ };
+}
+
+function formatShortPhaseName(raw: string): string {
+ const lower = raw.toLowerCase();
+ if (lower.includes('development') || lower === 'dev') return 'Development';
+ if (lower.includes('system integration') || lower.includes('sit')) return 'SIT';
+ if (lower.includes('user acceptance') || lower.includes('uat')) return 'UAT';
+ if (lower.includes('production trial') || lower.includes('ptr')) return 'PTR';
+ if (lower.includes('go-live') || lower.includes('live')) return 'Go-Live';
+ if (lower.includes('handover') || lower.includes('bast')) return 'BAST';
+ if (lower.includes('warranty')) return 'Warranty';
+ return raw;
+}
+
+function mapStatusNameToPhaseIndex(name: string): number {
+ const lower = name.toLowerCase();
+ if (lower.includes('development') || lower === 'dev' || lower.includes('not started')) return 0;
+ if (lower.includes('sit') || lower.includes('integration')) return 1;
+ if (lower.includes('uat') || lower.includes('acceptance')) return 2;
+ if (lower.includes('ptr') || lower.includes('trial')) return 3;
+ if (lower.includes('go-live') || lower.includes('live') || lower.includes('bast') || lower.includes('warranty') || lower.includes('complete')) return 4;
+ return 0;
+}
+
+/**
+ * 2. Progress Color Logic:
+ * Warna fill progress bar dan stepper rail tetap dipertahankan sesuai logic gradasi 5 spektrum:
+ * - 0% – 18%: Mengarah ke Oranye (#ea512c)
+ * - 18% – 35%: Kuning (#eab308)
+ * - 35% – 65%: Hijau (#10b981) (mencakup titik pertengahan ~50%)
+ * - 65% – 88%: Biru (#3b82f6)
+ * - >= 88% atau mendekati batas akhir deadline (<= 14 hari): Ungu (#a855f7)
+ */
+export function resolveProgressColor(
+ progressPercent: number,
+ isNearEndDate: boolean,
+ isPastEndDate: boolean,
+ _isCriticalOffTrack?: boolean
+): ProgressColorConfig {
+ // >= 88% atau mendekati batas akhir deadline (<= 14 hari) atau lewat deadline -> Ungu (#a855f7)
+ if (isPastEndDate || isNearEndDate || progressPercent >= 88) {
+ return COLOR_SPECTRUM.purple;
+ }
+
+ // 65% – 88%: Biru (#3b82f6)
+ if (progressPercent > 65) {
+ return COLOR_SPECTRUM.blue;
+ }
+
+ // 35% – 65%: Hijau (#10b981) (mencakup titik pertengahan ~50%)
+ if (progressPercent >= 35) {
+ return COLOR_SPECTRUM.green;
+ }
+
+ // 18% – 35%: Kuning (#eab308)
+ if (progressPercent >= 18) {
+ return COLOR_SPECTRUM.yellow;
+ }
+
+ // 0% – 18%: Mengarah ke Oranye (#ea512c)
+ return COLOR_SPECTRUM.orange;
+}
+
+/**
+ * 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)
+ * - 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)
+ */
+export function resolveDeliveryHealth(
+ technicalRank: number,
+ hasTechnicalStatus: boolean,
+ progressPercent: number,
+ endDate?: string
+): {
+ healthStatus: 'On Track' | 'At Risk' | 'Near Go-live' | 'Completed' | 'Critical' | 'Off Track';
+ healthBadgeClass: string;
+ healthDotClass: string;
+ isCritical: boolean;
+} {
+ const now = Date.now();
+ const hasEndDate = Boolean(endDate && !isNaN(new Date(endDate).getTime()));
+ // Sama atau lewat deadline
+ const isPastDeadline = hasEndDate ? now >= new Date(endDate!).getTime() : false;
+
+ // KONDISI 1: Sama atau lewat deadline
+ if (isPastDeadline) {
+ // Complete (Sky Blue) => sama atau lewat deadline, namun sudah sampai ke Go-Live (rank >= 5)
+ if (technicalRank >= 5) {
+ return {
+ healthStatus: 'Completed',
+ healthBadgeClass: 'bg-sky-500/10 text-sky-600 dark:text-sky-400 border-sky-500/30',
+ healthDotClass: 'bg-sky-500',
+ isCritical: false,
+ };
+ }
+
+ // Off Track / Critical (Warna Merah) => sama atau lewat deadline and belum sampai ke Go-Live (rank < 5)
+ // Perhatian: Walaupun progress hari sudah 100%, jika belum Go-Live maka tetap Critical / Off Track!
+ const label = (!hasTechnicalStatus || technicalRank === 0) ? 'Off Track' : 'Critical';
+ return {
+ healthStatus: label,
+ healthBadgeClass: 'bg-red-500/10 text-red-600 dark:text-red-400 border-red-500/30',
+ healthDotClass: 'bg-red-500',
+ isCritical: true,
+ };
+ }
+
+ // KONDISI 2: Belum lewat deadline (atau tidak ada endDate)
+
+ // Sudah sampai ke Go-Live sebelum deadline -> Complete (Sky Blue)
+ if (technicalRank >= 5) {
+ return {
+ healthStatus: 'Completed',
+ healthBadgeClass: 'bg-sky-500/10 text-sky-600 dark:text-sky-400 border-sky-500/30',
+ healthDotClass: 'bg-sky-500',
+ isCritical: false,
+ };
+ }
+
+ // At Risk (Warna Kuning) => progress lewat dari 75% dan belum sampai ke PTR (rank < 4)
+ if (progressPercent > 75 && technicalRank < 4) {
+ return {
+ healthStatus: 'At Risk',
+ healthBadgeClass: 'bg-yellow-500/15 text-yellow-700 dark:text-yellow-400 border-yellow-500/30',
+ healthDotClass: 'bg-yellow-500',
+ isCritical: false,
+ };
+ }
+
+ // 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)
+ return {
+ healthStatus: 'On Track',
+ healthBadgeClass: 'bg-emerald-500/10 text-emerald-600 dark:text-emerald-400 border-emerald-500/30',
+ healthDotClass: 'bg-emerald-500',
+ isCritical: false,
+ };
+}
+
+/**
+ * Calculates complete visual representation for an assignment row
+ */
+export function getAssignmentOverview(assignment: IProjectAssignment, index: number): 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';
+ const code = assignment.wo_code || assignment.im_code || assignment.project?.code;
+ const startDate = assignment.wo_start_date || assignment.im_start_date || assignment.project?.start_date;
+ const endDate = assignment.wo_end_date || assignment.im_end_date || assignment.project?.end_date;
+ const formattedDateRange = `${formatAssignmentDate(startDate)} - ${formatAssignmentDate(endDate)}`;
+ const endUserName = assignment.end_user?.name;
+ const endUserPhoto = assignment.end_user?.photo;
+ const clientName = assignment.client?.name;
+
+ // 1. Resolve Project Status (from status_detail with dates or fallback to project_assignment_status.name)
+ const { statusName: projectStatusName, isFromDetail, phaseIndex } = resolveProjectStatus(assignment, index);
+
+ // Compute duration & progress
+ let totalDays = 0;
+ let elapsedDays = 0;
+ let progressPercent = 0;
+
+ const now = Date.now();
+ let isPastEndDate = false;
+ let isNearEndDate = false;
+
+ if (startDate && endDate) {
+ const sTime = new Date(startDate).getTime();
+ const eTime = new Date(endDate).getTime();
+ if (!isNaN(sTime) && !isNaN(eTime) && eTime >= sTime) {
+ totalDays = Math.max(1, Math.round((eTime - sTime) / (1000 * 60 * 60 * 24)));
+ if (now < sTime) {
+ elapsedDays = 0;
+ } else if (now >= eTime) {
+ elapsedDays = totalDays;
+ isPastEndDate = true;
+ } else {
+ elapsedDays = Math.round((now - sTime) / (1000 * 60 * 60 * 24));
+ const remaining = Math.round((eTime - now) / (1000 * 60 * 60 * 24));
+ if (remaining <= 14) isNearEndDate = true;
+ }
+ progressPercent = Math.min(100, Math.max(0, Math.round((elapsedDays / totalDays) * 100)));
+ }
+ }
+
+ const daysRatioText = `${elapsedDays} / ${totalDays} hari`;
+
+ // 2. Resolve Technical Status & Delivery Health
+ const { hasTechnicalStatus, technicalRank } = resolveTechnicalStatus(assignment);
+ const { healthStatus, healthBadgeClass, healthDotClass, isCritical } = resolveDeliveryHealth(
+ technicalRank,
+ hasTechnicalStatus,
+ progressPercent,
+ endDate
+ );
+
+ // 3. Resolve Progress Color (Orange -> Kuning -> Hijau -> Biru -> Ungu)
+ const progressColor = resolveProgressColor(progressPercent, isNearEndDate, isPastEndDate, isCritical);
+
+ // 4. Team members extraction strictly from project_assignment_work_order_detail
+ const rawTeam = Array.isArray(assignment.project_assignment_work_order_detail)
+ ? assignment.project_assignment_work_order_detail
+ : [];
+ const teamMembers = rawTeam
+ .map(t => ({
+ id: t.user?.id || t.id,
+ name: t.user?.fullname || t.user?.nickname || '',
+ avatar: t.user?.avatar,
+ position: t.user?.position?.name || 'Member',
+ }))
+ .filter(m => Boolean(m.name));
+
+ const teamCount = teamMembers.length;
+
+ // Remaining text & Next milestone
+ let remainingText = '';
+ let nextMilestoneText = '';
+
+ if (healthStatus === 'Critical' || healthStatus === 'Off Track') {
+ remainingText = endDate ? `Passed deadline (${formatAssignmentDate(endDate)})` : 'Past deadline';
+ nextMilestoneText = 'Next: Urgent Follow-up';
+ } else if (healthStatus === 'Completed') {
+ remainingText = endDate ? `Completed on ${formatAssignmentDate(endDate)}` : 'Completed';
+ nextMilestoneText = 'Next: -';
+ } else if (healthStatus === 'At Risk') {
+ const remDays = Math.max(1, totalDays - elapsedDays);
+ remainingText = `${remDays} days remaining`;
+ nextMilestoneText = 'Next: Accelerate to PTR';
+ } else {
+ const remDays = Math.max(1, totalDays - elapsedDays);
+ remainingText = totalDays > 0 ? `${remDays} days remaining` : 'Schedule pending';
+ nextMilestoneText = phaseIndex === 0 ? 'Next: Feature Development' : 'Next: SIT Testing';
+ }
+
+ const updatedAgoText = formatRelativeTime(assignment.created_at || startDate);
+
+ return {
+ assignmentType,
+ isProject,
+ title,
+ code,
+ startDate,
+ endDate,
+ formattedDateRange,
+ endUserName,
+ endUserPhoto,
+ clientName,
+ projectStatusName,
+ isFromDetail,
+ phaseIndex,
+ elapsedDays,
+ totalDays,
+ daysRatioText,
+ progressPercent,
+ progressColor,
+ teamCount,
+ teamMembers,
+ healthStatus,
+ healthBadgeClass,
+ healthDotClass,
+ remainingText,
+ nextMilestoneText,
+ updatedAgoText,
+ };
+}
+
+/**
+ * Calculates top executive summary metrics for "Project Assignment Dashboard"
+ */
+export function calculateDashboardStats(assignments: IProjectAssignment[]) {
+ const totalAssignments = assignments.length;
+ const overviews = assignments.map((a, i) => getAssignmentOverview(a, i));
+
+ const totalProjects = assignments.reduce((acc, a) => {
+ if (a.project?.id) acc.add(a.project.id);
+ else acc.add(a.id);
+ return acc;
+ }, new Set()).size;
+
+ const activeWorkOrders = assignments.filter(a => !!a.wo_name).length;
+
+ // Assigned people strictly from project_assignment_work_order_detail
+ const uniqueUsers = new Set();
+ assignments.forEach(a => {
+ (a.project_assignment_work_order_detail || []).forEach(w => {
+ if (w.user?.id) uniqueUsers.add(w.user.id);
+ });
+ });
+ const assignedPeopleCount = uniqueUsers.size;
+
+ // Average progress
+ const avgProgress = overviews.length > 0
+ ? Math.round(overviews.reduce((acc, o) => acc + o.progressPercent, 0) / overviews.length)
+ : 0;
+
+ // On-Time projects vs Total
+ const onTimeCount = overviews.filter(o => o.healthStatus === 'On Track' || o.healthStatus === 'Completed').length;
+ const atRiskCount = overviews.filter(o => o.healthStatus === 'At Risk' || o.healthStatus === 'Critical' || o.healthStatus === 'Off Track').length;
+
+ return {
+ totalProjects: totalProjects || totalAssignments,
+ activeWorkOrders: activeWorkOrders || totalAssignments,
+ assignedPeople: assignedPeopleCount,
+ averageProgress: avgProgress,
+ onTimeRatio: `${onTimeCount} / ${totalAssignments}`,
+ atRiskDelayed: atRiskCount,
+ };
+}
diff --git a/package.json b/package.json
index 93ceb9f..58bd47b 100644
--- a/package.json
+++ b/package.json
@@ -1,7 +1,7 @@
{
"name": "hats-app",
"description": "H.I.S Super Apps (smart absence, task management, work permit and leave mangement, etc).",
- "version": "1.1.2",
+ "version": "1.2.0",
"private": true,
"author": "ichsankurnia",
"repository": {
@@ -93,4 +93,4 @@
"tw-animate-css": "^1.4.0",
"typescript": "^5"
}
-}
+}
\ No newline at end of file