mirror of
https://github.com/ichsankurnia/hats-app.git
synced 2026-12-05 10:56:28 +00:00
230213cd2e
Represent pending assignments with no active phase, show Development as the next milestone, and align the grid and list steppers' rails with their stage dots.
894 lines
36 KiB
TypeScript
894 lines
36 KiB
TypeScript
import dayjs from 'dayjs';
|
|
import { IProjectAssignment, StatusDetailDateEntry } from '../type.assignment';
|
|
|
|
export interface ProgressColorConfig {
|
|
name: 'orange' | 'yellow' | 'green' | 'blue' | 'purple' | 'red' | 'sky' | 'teal';
|
|
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> = {
|
|
sky: {
|
|
name: 'sky',
|
|
label: 'Completed',
|
|
hex: '#0ea5e9',
|
|
barColor: 'bg-sky-500',
|
|
textColor: 'text-sky-500 dark:text-sky-400',
|
|
glowRing: 'ring-4 ring-sky-500/30 shadow-[0_0_12px_rgba(14,165,233,0.6)]',
|
|
activeDot: 'bg-sky-500',
|
|
badgeBg: 'bg-sky-500/10 dark:bg-sky-500/20',
|
|
badgeText: 'text-sky-600 dark:text-sky-400',
|
|
badgeBorder: 'border-sky-500/30',
|
|
},
|
|
teal: {
|
|
name: 'teal',
|
|
label: 'Near Go-live',
|
|
hex: '#14b8a6',
|
|
barColor: 'bg-teal-500',
|
|
textColor: 'text-teal-500 dark:text-teal-400',
|
|
glowRing: 'ring-4 ring-teal-500/30 shadow-[0_0_12px_rgba(20,184,166,0.6)]',
|
|
activeDot: 'bg-teal-500',
|
|
badgeBg: 'bg-teal-500/10 dark:bg-teal-500/20',
|
|
badgeText: 'text-teal-600 dark:text-teal-400',
|
|
badgeBorder: 'border-teal-500/30',
|
|
},
|
|
yellow: {
|
|
name: 'yellow',
|
|
label: 'At Risk',
|
|
hex: '#eab308',
|
|
barColor: 'bg-yellow-500',
|
|
textColor: 'text-yellow-500 dark:text-yellow-400',
|
|
glowRing: 'ring-4 ring-yellow-500/30 shadow-[0_0_12px_rgba(234,179,8,0.6)]',
|
|
activeDot: 'bg-yellow-500',
|
|
badgeBg: 'bg-yellow-500/15 dark:bg-yellow-500/20',
|
|
badgeText: 'text-yellow-700 dark:text-yellow-400',
|
|
badgeBorder: 'border-yellow-500/30',
|
|
},
|
|
red: {
|
|
name: 'red',
|
|
label: 'Critical / Off Track',
|
|
hex: '#ef4444',
|
|
barColor: 'bg-red-500',
|
|
textColor: 'text-red-500 dark:text-red-400',
|
|
glowRing: 'ring-4 ring-red-500/30 shadow-[0_0_12px_rgba(239,68,68,0.6)]',
|
|
activeDot: 'bg-red-500',
|
|
badgeBg: 'bg-red-500/10 dark:bg-red-500/20',
|
|
badgeText: 'text-red-600 dark:text-red-400',
|
|
badgeBorder: 'border-red-500/30',
|
|
},
|
|
green: {
|
|
name: 'green',
|
|
label: 'On Track',
|
|
hex: '#10b981',
|
|
barColor: 'bg-emerald-500',
|
|
textColor: 'text-emerald-500 dark:text-emerald-400',
|
|
glowRing: 'ring-4 ring-emerald-500/30 shadow-[0_0_12px_rgba(16,185,129,0.6)]',
|
|
activeDot: 'bg-emerald-500',
|
|
badgeBg: 'bg-emerald-500/10 dark:bg-emerald-500/20',
|
|
badgeText: 'text-emerald-600 dark:text-emerald-400',
|
|
badgeBorder: 'border-emerald-500/30',
|
|
},
|
|
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',
|
|
},
|
|
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',
|
|
},
|
|
};
|
|
|
|
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;
|
|
actualProgress: 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;
|
|
latestActivityText: string;
|
|
|
|
// Warning status & reasons (Health Critical/Off Track or Actual Progress < Days Elapsed)
|
|
hasWarning: boolean;
|
|
warningTitle: string;
|
|
warningReason: string;
|
|
warningDetails: string[];
|
|
isCriticalOrOffTrack: boolean;
|
|
isBehindSchedule: boolean;
|
|
}
|
|
|
|
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 formatHistoryRelativeTime(dateStr?: string | null): string {
|
|
if (!dateStr) return '';
|
|
const d = dayjs(dateStr);
|
|
if (!d.isValid()) return '';
|
|
const now = dayjs();
|
|
const diffSec = Math.max(0, now.diff(d, 'second'));
|
|
|
|
if (diffSec < 60) return 'just now';
|
|
const diffMin = Math.floor(diffSec / 60);
|
|
if (diffMin < 60) return `${diffMin} ${diffMin === 1 ? 'minute' : 'minutes'} ago`;
|
|
const diffHours = Math.floor(diffMin / 60);
|
|
if (diffHours < 24) return `${diffHours} ${diffHours === 1 ? 'hour' : 'hours'} ago`;
|
|
const diffDays = Math.floor(diffHours / 24);
|
|
if (diffDays < 7) return `${diffDays} ${diffDays === 1 ? 'day' : 'days'} ago`;
|
|
const diffWeeks = Math.floor(diffDays / 7);
|
|
if (diffWeeks < 4) return diffWeeks === 1 ? 'a week ago' : `${diffWeeks} weeks ago`;
|
|
const diffMonths = Math.floor(diffDays / 30);
|
|
if (diffMonths < 12) return diffMonths === 1 ? 'a month ago' : `${diffMonths} months ago`;
|
|
const diffYears = Math.floor(diffDays / 365);
|
|
return diffYears === 1 ? 'a year ago' : `${diffYears} years ago`;
|
|
}
|
|
|
|
export function formatLatestActivityWording(historyList?: any[] | null): string {
|
|
if (!historyList || !Array.isArray(historyList) || historyList.length === 0) {
|
|
return 'No updated activity';
|
|
}
|
|
const latest = historyList[0];
|
|
if (!latest || !latest.created_at) return 'No updated activity';
|
|
|
|
const rel = formatHistoryRelativeTime(latest.created_at);
|
|
if (!rel) return 'No updated activity';
|
|
|
|
const user = latest.user?.nickname || latest.user?.fullname || 'system';
|
|
return `Updated ${rel} by ${user}`;
|
|
}
|
|
|
|
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: safely extracts date entries from a detail object regardless of schema variant
|
|
export const getStatusDetailDateEntries = (d: any): StatusDetailDateEntry[] => {
|
|
if (!d) return [];
|
|
if (Array.isArray(d.data) && d.data.length > 0) return d.data;
|
|
if (Array.isArray(d.date) && d.date.length > 0) return d.date;
|
|
if (d.start_date || d.end_date) {
|
|
return [{ start_date: d.start_date, end_date: d.end_date, description: d.description }];
|
|
}
|
|
return [];
|
|
};
|
|
|
|
// Helper: checks if a detail entry has ANY assigned dates
|
|
export const hasAssignedDates = (d: any): boolean => {
|
|
if (!d) return false;
|
|
const entries = getStatusDetailDateEntries(d);
|
|
if (entries.length > 0) {
|
|
return entries.some((item) => Boolean(item?.start_date || item?.end_date));
|
|
}
|
|
if (typeof d.date === 'string' && d.date.trim().length > 0) return true;
|
|
if (typeof d.data === 'string' && d.data.trim().length > 0) return true;
|
|
return false;
|
|
};
|
|
|
|
/**
|
|
* Checks if today falls within or matches the given start and end date range
|
|
*/
|
|
export const isDateTodayOrInRange = (startDate?: string | null, endDate?: string | null): boolean => {
|
|
if (!startDate && !endDate) return false;
|
|
const today = dayjs().startOf('day');
|
|
const start = startDate && dayjs(startDate).isValid() ? dayjs(startDate).startOf('day') : null;
|
|
const end = endDate && dayjs(endDate).isValid() ? dayjs(endDate).endOf('day') : null;
|
|
|
|
if (start && end) {
|
|
return (today.isSame(start, 'day') || today.isAfter(start)) &&
|
|
(today.isSame(end, 'day') || today.isBefore(end));
|
|
}
|
|
if (start && !end) {
|
|
return today.isSame(start, 'day') || today.isAfter(start);
|
|
}
|
|
if (!start && end) {
|
|
return today.isSame(end, 'day') || today.isBefore(end);
|
|
}
|
|
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;
|
|
}
|
|
|
|
/**
|
|
* Checks if a status detail phase has started based on its scheduled dates.
|
|
* A phase has started if today is on or after its start_date (or end_date if no start_date).
|
|
*/
|
|
export const isDetailStarted = (d: any): boolean => {
|
|
if (!d) return false;
|
|
const entries = getStatusDetailDateEntries(d);
|
|
if (entries.length === 0) return false;
|
|
const today = dayjs().startOf('day');
|
|
return entries.some(entry => {
|
|
const target = entry.start_date || entry.end_date;
|
|
if (!target) return false;
|
|
const dObj = dayjs(target);
|
|
return dObj.isValid() && (today.isSame(dObj.startOf('day')) || today.isAfter(dObj.startOf('day')));
|
|
});
|
|
};
|
|
|
|
/**
|
|
* 1. Derives project status:
|
|
* Priority:
|
|
* 1. project_assignment_status_detail with assigned dates:
|
|
* a. Phase matching today's date (isDateTodayOrInRange)
|
|
* b. Highest phase that has started (start_date <= today)
|
|
* c. If none has started yet (all in future), first scheduled phase (Dev)
|
|
* 2. Fallback when NO details have dates:
|
|
* a. project_assignment_technical_status.name
|
|
* b. project_assignment_status.name
|
|
*/
|
|
export function resolveProjectStatus(assignment: IProjectAssignment, indexFallback = 0): {
|
|
statusName: string;
|
|
isFromDetail: boolean;
|
|
phaseIndex: number;
|
|
} {
|
|
const details = assignment.project_assignment_status_detail || [];
|
|
const detailsWithDates = details.filter(hasAssignedDates);
|
|
|
|
// 1. If details have dates assigned, prioritize date-based progression:
|
|
if (detailsWithDates.length > 0) {
|
|
// A. Check if any detail matches today's date
|
|
let activeDetail: any = null;
|
|
|
|
for (let i = 0; i < detailsWithDates.length; i++) {
|
|
const d = detailsWithDates[i];
|
|
const entries = getStatusDetailDateEntries(d);
|
|
const matchesToday = entries.some(entry => isDateTodayOrInRange(entry.start_date, entry.end_date));
|
|
if (matchesToday) {
|
|
activeDetail = d;
|
|
break;
|
|
}
|
|
}
|
|
|
|
if (activeDetail?.project_assignment_status?.name) {
|
|
const rawName = activeDetail.project_assignment_status.name;
|
|
return {
|
|
statusName: formatShortPhaseName(rawName),
|
|
isFromDetail: true,
|
|
phaseIndex: mapStatusNameToPhaseIndex(rawName),
|
|
};
|
|
}
|
|
|
|
// B. If none matches today, find the highest rank stage that has actually started (start_date <= today)
|
|
const startedDetails = detailsWithDates.filter(isDetailStarted);
|
|
if (startedDetails.length > 0) {
|
|
startedDetails.sort((a, b) => {
|
|
const rankA = getTechnicalStageRank(a.project_assignment_status?.name);
|
|
const rankB = getTechnicalStageRank(b.project_assignment_status?.name);
|
|
return rankA - rankB;
|
|
});
|
|
const latestStarted = startedDetails[startedDetails.length - 1];
|
|
const rawName = latestStarted.project_assignment_status?.name || 'Development';
|
|
return {
|
|
statusName: formatShortPhaseName(rawName),
|
|
isFromDetail: true,
|
|
phaseIndex: mapStatusNameToPhaseIndex(rawName),
|
|
};
|
|
}
|
|
|
|
// C. If NO detail has started yet (all scheduled in the future):
|
|
// Development has not started yet
|
|
const firstStage = detailsWithDates[0];
|
|
const rawName = firstStage?.project_assignment_status?.name || 'Development';
|
|
return {
|
|
statusName: formatShortPhaseName(rawName),
|
|
isFromDetail: true,
|
|
phaseIndex: -1,
|
|
};
|
|
}
|
|
|
|
// 2. Fallback when NO details have dates assigned:
|
|
if (assignment.project_assignment_technical_status?.name) {
|
|
const rawName = assignment.project_assignment_technical_status.name;
|
|
return {
|
|
statusName: formatShortPhaseName(rawName),
|
|
isFromDetail: false,
|
|
phaseIndex: mapStatusNameToPhaseIndex(rawName),
|
|
};
|
|
}
|
|
|
|
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: -1,
|
|
};
|
|
}
|
|
|
|
/**
|
|
* Resolves technical status from either project_assignment_status_detail (with assigned dates that have started)
|
|
* OR fallback to project_assignment_technical_status.name when no dates are scheduled.
|
|
*/
|
|
export function resolveTechnicalStatus(assignment: IProjectAssignment): {
|
|
technicalStatusName: string | null;
|
|
hasTechnicalStatus: boolean;
|
|
technicalRank: number;
|
|
} {
|
|
const details = assignment.project_assignment_status_detail || [];
|
|
const detailsWithDates = details.filter(hasAssignedDates);
|
|
|
|
// 1. If details have assigned dates, technical rank is strictly derived from stages that have started:
|
|
if (detailsWithDates.length > 0) {
|
|
let maxStartedRank = 0;
|
|
let maxStartedName: string | null = null;
|
|
|
|
detailsWithDates.forEach(d => {
|
|
if (isDetailStarted(d) && d.project_assignment_status?.name) {
|
|
const r = getTechnicalStageRank(d.project_assignment_status.name);
|
|
if (r > maxStartedRank) {
|
|
maxStartedRank = r;
|
|
maxStartedName = d.project_assignment_status.name;
|
|
}
|
|
}
|
|
});
|
|
|
|
// Also check if any stage matches today directly
|
|
detailsWithDates.forEach(d => {
|
|
const entries = getStatusDetailDateEntries(d);
|
|
const matchesToday = entries.some(entry => isDateTodayOrInRange(entry.start_date, entry.end_date));
|
|
if (matchesToday && d.project_assignment_status?.name) {
|
|
const r = getTechnicalStageRank(d.project_assignment_status.name);
|
|
if (r > maxStartedRank) {
|
|
maxStartedRank = r;
|
|
maxStartedName = d.project_assignment_status.name;
|
|
}
|
|
}
|
|
});
|
|
|
|
if (maxStartedRank > 0) {
|
|
return {
|
|
technicalStatusName: maxStartedName,
|
|
hasTechnicalStatus: true,
|
|
technicalRank: maxStartedRank,
|
|
};
|
|
}
|
|
|
|
// None has started yet (all dates are future)
|
|
return {
|
|
technicalStatusName: detailsWithDates[0]?.project_assignment_status?.name || null,
|
|
hasTechnicalStatus: false,
|
|
technicalRank: 0,
|
|
};
|
|
}
|
|
|
|
// 2. Fallback when NO details have dates: use project_assignment_technical_status.name
|
|
const techName = assignment.project_assignment_technical_status?.name || null;
|
|
const rankTech = techName ? getTechnicalStageRank(techName) : 0;
|
|
|
|
return {
|
|
technicalStatusName: techName,
|
|
hasTechnicalStatus: rankTech > 0,
|
|
technicalRank: rankTech,
|
|
};
|
|
}
|
|
|
|
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 | null): number {
|
|
if (!name) return -1;
|
|
const lower = name.toLowerCase().trim();
|
|
if (lower.includes('not started') || lower.includes('pending') || lower.includes('unassigned')) return -1;
|
|
if (lower.includes('development') || lower === 'dev') 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 -1;
|
|
}
|
|
|
|
/**
|
|
* 2. Progress / Milestone Color Logic:
|
|
* Warna milestone dan progress disesuaikan dengan 5 rules:
|
|
* - Complete (Sky Blue)
|
|
* - Near Go-live (Warna Teal)
|
|
* - At Risk (Warna Kuning)
|
|
* - Off Track / Critical (Warna Merah)
|
|
* - On Track (Warna Hijau)
|
|
*/
|
|
export function resolveProgressColor(
|
|
healthStatusOrProgress: 'On Track' | 'At Risk' | 'Near Go-live' | 'Completed' | 'Critical' | 'Off Track' | number,
|
|
isNearEndDate?: boolean,
|
|
isPastEndDate?: boolean,
|
|
_isCriticalOffTrack?: boolean
|
|
): ProgressColorConfig {
|
|
if (typeof healthStatusOrProgress === 'string') {
|
|
switch (healthStatusOrProgress) {
|
|
case 'Completed':
|
|
return COLOR_SPECTRUM.sky;
|
|
case 'Near Go-live':
|
|
return COLOR_SPECTRUM.teal;
|
|
case 'At Risk':
|
|
return COLOR_SPECTRUM.yellow;
|
|
case 'Critical':
|
|
case 'Off Track':
|
|
return COLOR_SPECTRUM.red;
|
|
case 'On Track':
|
|
default:
|
|
return COLOR_SPECTRUM.green;
|
|
}
|
|
}
|
|
|
|
// Fallback if called with progressPercent number
|
|
if (isPastEndDate || _isCriticalOffTrack) {
|
|
return COLOR_SPECTRUM.red;
|
|
}
|
|
if (isNearEndDate) {
|
|
return COLOR_SPECTRUM.teal;
|
|
}
|
|
if (healthStatusOrProgress > 75) {
|
|
return COLOR_SPECTRUM.yellow;
|
|
}
|
|
return COLOR_SPECTRUM.green;
|
|
}
|
|
|
|
/**
|
|
* 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();
|
|
};
|
|
|
|
const entries = getStatusDetailDateEntries(ptrDetail);
|
|
entries.forEach((item) => {
|
|
const t = parseTime(item?.end_date || item?.start_date);
|
|
if (t && (!latestTime || t > latestTime)) {
|
|
latestTime = t;
|
|
}
|
|
});
|
|
|
|
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)
|
|
*/
|
|
export function resolveDeliveryHealth(
|
|
technicalRank: number,
|
|
hasTechnicalStatus: boolean,
|
|
progressPercent: number,
|
|
endDate?: string,
|
|
ptrEndDate?: number | null
|
|
): {
|
|
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 status (rank < 5)
|
|
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 (masih dalam rentang end of date)
|
|
|
|
// A. 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,
|
|
};
|
|
}
|
|
|
|
// B. 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
|
|
const isPastPtrDate = typeof ptrEndDate === 'number'
|
|
? now > ptrEndDate
|
|
: (technicalRank >= 4 && progressPercent >= 75);
|
|
|
|
if (technicalRank >= 4 && isPastPtrDate && technicalRank < 5) {
|
|
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,
|
|
};
|
|
}
|
|
|
|
// C. At Risk (Warna Kuning) => progress lewat dari 75% dan namun 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,
|
|
};
|
|
}
|
|
|
|
// D. On Track (Warna Hijau) => Belum lewat deadline dan progres sejalan dengan target (progress <= 75%, atau sudah sampai ke PTR)
|
|
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 = 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';
|
|
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 ptrEndDate = getPtrEndDate(assignment);
|
|
const { healthStatus, healthBadgeClass, healthDotClass } = resolveDeliveryHealth(
|
|
technicalRank,
|
|
hasTechnicalStatus,
|
|
progressPercent,
|
|
endDate,
|
|
ptrEndDate
|
|
);
|
|
|
|
// 3. Resolve Progress / Milestone Color (Complete = Sky Blue, Near Go-live = Teal, At Risk = Kuning, Off Track/Critical = Merah, On Track = Hijau)
|
|
const progressColor = resolveProgressColor(healthStatus);
|
|
|
|
// 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 === '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`;
|
|
nextMilestoneText = 'Next: Accelerate to PTR';
|
|
} else {
|
|
const remDays = Math.max(1, totalDays - elapsedDays);
|
|
remainingText = totalDays > 0 ? `${remDays} days remaining` : 'Schedule pending';
|
|
if (phaseIndex === -1) nextMilestoneText = 'Next: Development';
|
|
else if (phaseIndex === 0) nextMilestoneText = 'Next: SIT Testing';
|
|
else if (phaseIndex === 1) nextMilestoneText = 'Next: UAT Testing';
|
|
else if (phaseIndex === 2) nextMilestoneText = 'Next: Production Trial Run';
|
|
else if (phaseIndex === 3) nextMilestoneText = 'Next: Go-Live';
|
|
else nextMilestoneText = 'Next: Project Handover';
|
|
}
|
|
|
|
const updatedAgoText = formatRelativeTime(assignment.created_at || startDate);
|
|
|
|
const actualProgress = typeof assignment.progress === 'number' && !isNaN(assignment.progress) ? Math.min(100, Math.max(0, assignment.progress)) : 0;
|
|
|
|
const latestActivityText = formatLatestActivityWording(assignment.project_assignment_history);
|
|
|
|
// 5. Warning condition: healthStatus is 'Critical' or 'Off Track' OR actualProgress < progressPercent (days elapsed)
|
|
const isCriticalOrOffTrack = healthStatus === 'Critical' || healthStatus === 'Off Track';
|
|
const isBehindSchedule = healthStatus !== 'Completed' && actualProgress < progressPercent;
|
|
const hasWarning = isCriticalOrOffTrack || isBehindSchedule;
|
|
|
|
let warningTitle = '';
|
|
let warningReason = '';
|
|
const warningDetails: string[] = [];
|
|
|
|
if (isCriticalOrOffTrack && isBehindSchedule) {
|
|
warningTitle = `Attention Needed: ${healthStatus} & Behind Schedule`;
|
|
warningReason = `Project deadline has passed and actual progress (${actualProgress}%) is lagging behind timeline elapsed (${progressPercent}%).`;
|
|
warningDetails.push(`Status: ${healthStatus} (${remainingText || 'Passed deadline'})`);
|
|
warningDetails.push(`Actual: ${actualProgress}% vs Elapsed: ${progressPercent}% (${daysRatioText})`);
|
|
} else if (isCriticalOrOffTrack) {
|
|
warningTitle = `Attention Needed: ${healthStatus}`;
|
|
warningReason = `Project deadline has passed without reaching completion status (${remainingText || 'Passed deadline'}).`;
|
|
warningDetails.push(`Status: ${healthStatus}`);
|
|
if (endDate) {
|
|
warningDetails.push(`Deadline: ${formatAssignmentDate(endDate)}`);
|
|
}
|
|
} else if (isBehindSchedule) {
|
|
warningTitle = 'Attention Needed: Behind Schedule';
|
|
warningReason = `Actual progress (${actualProgress}%) is lagging behind the timeline elapsed (${progressPercent}%).`;
|
|
warningDetails.push(`Actual Progress: ${actualProgress}%`);
|
|
warningDetails.push(`Timeline Elapsed: ${progressPercent}% (${daysRatioText})`);
|
|
if (totalDays > elapsedDays) {
|
|
warningDetails.push(`${totalDays - elapsedDays} days remaining`);
|
|
}
|
|
}
|
|
|
|
return {
|
|
assignmentType,
|
|
isProject,
|
|
title,
|
|
code,
|
|
startDate,
|
|
endDate,
|
|
formattedDateRange,
|
|
endUserName,
|
|
endUserPhoto,
|
|
clientName,
|
|
projectStatusName,
|
|
isFromDetail,
|
|
phaseIndex,
|
|
elapsedDays,
|
|
totalDays,
|
|
daysRatioText,
|
|
progressPercent,
|
|
actualProgress,
|
|
progressColor,
|
|
teamCount,
|
|
teamMembers,
|
|
healthStatus,
|
|
healthBadgeClass,
|
|
healthDotClass,
|
|
remainingText,
|
|
nextMilestoneText,
|
|
updatedAgoText,
|
|
latestActivityText,
|
|
hasWarning,
|
|
warningTitle,
|
|
warningReason,
|
|
warningDetails,
|
|
isCriticalOrOffTrack,
|
|
isBehindSchedule,
|
|
};
|
|
}
|
|
|
|
export const buildAssignmentOverview = getAssignmentOverview;
|
|
|
|
/**
|
|
* 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;
|
|
|
|
// Warning / Needs Attention count: healthStatus is 'Critical' or 'Off Track' OR actualProgress < progressPercent (days elapsed)
|
|
const needsAttentionCount = overviews.filter(o => o.hasWarning).length;
|
|
|
|
// Average progress (kept for backwards compatibility)
|
|
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' || o.healthStatus === 'Near Go-live').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,
|
|
needsAttention: needsAttentionCount,
|
|
averageProgress: avgProgress,
|
|
onTimeRatio: `${onTimeCount} / ${totalAssignments}`,
|
|
atRiskDelayed: atRiskCount,
|
|
};
|
|
}
|