Files
hats-app/app/(dashboard)/task/utils/assignment-overview-helpers.ts
T
Ichsan Kurniawan 6f52078aa5 Redesign project assignment list
This commit refreshes the client project assignment UI with a new dashboard summary, streamlined card layouts, and shared assignment overview helpers. It adds phase/progress tracking, delivery health indicators, and improved team/status calculations across the assignment grid and list views. It also updates the project assignment type definitions and bumps the app version.
2026-10-13 20:42:59 +07:00

615 lines
23 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.
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<string, ProgressColorConfig> = {
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<number>()).size;
const activeWorkOrders = assignments.filter(a => !!a.wo_name).length;
// Assigned people strictly from project_assignment_work_order_detail
const uniqueUsers = new Set<string | number>();
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,
};
}