From b71d84db062cdd76245f74ef9704e896e5765275 Mon Sep 17 00:00:00 2001 From: Ichsan Kurniawan <43689091+ichsankurnia@users.noreply.github.com> Date: Thu, 5 Nov 2026 11:27:05 +0700 Subject: [PATCH] Add assignment validation and attention alerts Validate project years and Work Order code availability, confirm before discarding unsaved changes, and surface critical or behind-schedule assignments in dashboard warnings and stats. Also update assignment form and dashboard labels. --- .../[assignment_id]/AddActivityLogModal.tsx | 2 +- .../ProjectAssignmentForm.tsx | 235 ++++++++++++++++-- .../project-assignment/AssignmentGrid.tsx | 60 ++++- .../project-assignment/AssignmentList.tsx | 72 ++++-- .../ProjectAssignmentDashboardStats.tsx | 46 +--- .../task/utils/assignment-overview-helpers.ts | 61 ++++- package.json | 4 +- 7 files changed, 391 insertions(+), 89 deletions(-) diff --git a/app/(dashboard)/task/client-detail/[client_id]/[assignment_id]/AddActivityLogModal.tsx b/app/(dashboard)/task/client-detail/[client_id]/[assignment_id]/AddActivityLogModal.tsx index 1947822..fe8e831 100644 --- a/app/(dashboard)/task/client-detail/[client_id]/[assignment_id]/AddActivityLogModal.tsx +++ b/app/(dashboard)/task/client-detail/[client_id]/[assignment_id]/AddActivityLogModal.tsx @@ -154,7 +154,7 @@ export default function AddActivityLogModal({ diff --git a/app/(dashboard)/task/client-detail/[client_id]/project-assignments/ProjectAssignmentForm.tsx b/app/(dashboard)/task/client-detail/[client_id]/project-assignments/ProjectAssignmentForm.tsx index c6c1301..eba92e1 100644 --- a/app/(dashboard)/task/client-detail/[client_id]/project-assignments/ProjectAssignmentForm.tsx +++ b/app/(dashboard)/task/client-detail/[client_id]/project-assignments/ProjectAssignmentForm.tsx @@ -1,17 +1,17 @@ "use client" -import { useState, useEffect } from 'react'; +import { useState, useEffect, useMemo } from 'react'; import { useRouter } from 'next/navigation'; import { useForm } from 'react-hook-form'; import { yupResolver } from '@hookform/resolvers/yup'; import { motion, AnimatePresence } from 'motion/react'; import { ArrowLeft, ArrowRight, Save, Briefcase, Clock, Search, Check, CheckCircle, - Plus, CheckCircle2, RotateCcw, X, ChevronDown, FolderGit2, ArrowUpRight + Plus, CheckCircle2, RotateCcw, X, ChevronDown, FolderGit2, Loader2, + CircleExclamationPoint } from 'lucide-react'; - import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from '@/components/ui/form'; -import { Button } from '@/components/ui/button'; +import { Button, buttonVariants } from '@/components/ui/button'; import { Input } from '@/components/ui/input'; import { Checkbox } from '@/components/ui/checkbox'; import { @@ -41,6 +41,10 @@ import { ComboboxCustomUI } from '@/components/ui/combobox-custom-ui'; import { LazyImage } from '@/components/ui/lazy-image'; import FormEndUser from '../../../component/FormEndUser'; import { IProject } from '../../../type.project'; +import useDebounce from '@/hooks/useDebounce'; +import { + AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, +} from '@/components/ui/alert-dialog'; import FormClient from '../../../component/client/FormClient'; type IStep = 'type' | 'clients' | 'details' | 'work-orders' | 'review'; @@ -54,7 +58,14 @@ export const assignmentSchema = yup.object({ name: yup.string().required('Assignment name is required'), code: yup.string().required('Project code is required'), - year: yup.string().required('Year is required'), + year: yup.string() + .required('Year is required') + .matches(/^\d{4}$/, 'Year must be a 4-digit number (e.g. 2026)') + .test('valid-year-range', 'Year must be between 1900 and 2099', (val) => { + if (!val) return false; + const y = parseInt(val, 10); + return y >= 1900 && y <= 2099; + }), startDate: yup.date().required('Start date is required'), endDate: yup.date().required('End date is required').min(yup.ref('startDate'), 'End date cannot be before start date'), description: yup.string().optional().nullable().max(500, 'Description cannot exceed 500 characters').default(''), @@ -91,6 +102,9 @@ export default function ProjectAssignmentForm( const [selectedClient, setSelectedClient] = useState(client || null); const [selectedEndUser, setSelectedEndUser] = useState(null); const [isSameAsProject, setIsSameAsProject] = useState(false); + const [showLeaveConfirmModal, setShowLeaveConfirmModal] = useState(false); + const [woCodeStatus, setWoCodeStatus] = useState<'idle' | 'checking' | 'available' | 'unavailable'>('idle'); + const [woCodeMessage, setWoCodeMessage] = useState(''); const form = useForm({ resolver: yupResolver(assignmentSchema), @@ -113,6 +127,44 @@ export default function ProjectAssignmentForm( const assignmentType = form.watch('type'); const formValues = form.watch(); + const projectCodeCandidate = formValues.code?.trim() || ''; + const rawWoCodeCandidate = (formValues.workOrder as any)?.code?.trim() || ''; + const fullWoCodeCandidate = rawWoCodeCandidate + ? (projectCodeCandidate && !rawWoCodeCandidate.startsWith(`${projectCodeCandidate}-`) + ? `${projectCodeCandidate}-${rawWoCodeCandidate}` + : rawWoCodeCandidate) + : ''; + const debouncedWoCode = useDebounce(fullWoCodeCandidate, 500); + + const isFormFilled = useMemo(() => { + if (form.formState.isDirty) return true; + if (!isEdit) { + return Boolean( + formValues.name?.trim() || + formValues.code?.trim() || + formValues.description?.trim() || + formValues.startDate || + formValues.endDate || + formValues.end_user_id || + selectedEndUser || + (formValues.workOrder as any)?.name?.trim() || + ((formValues.workOrder as any)?.code?.trim() && (formValues.workOrder as any)?.code !== 'WO-01') || + (formValues.workOrder as any)?.description?.trim() || + (formValues.workOrder as any)?.startDate || + (formValues.workOrder as any)?.endDate + ); + } + return false; + }, [form.formState.isDirty, formValues, isEdit, selectedEndUser]); + + const handleHeaderBackClick = () => { + if (isFormFilled) { + setShowLeaveConfirmModal(true); + } else { + router.back(); + } + }; + const { data: clientList, mutate: mutateClientList } = useFetchWithAxios('/client') const { data: endUserList, mutate: mutateEndUserList } = useFetchWithAxios('/end-user') const { data: projectList } = useFetchWithAxios(`/client/project/${formValues.client_id}`) @@ -203,6 +255,7 @@ export default function ProjectAssignmentForm( if (defaultWoName?.toLowerCase() === data.project?.name?.toLowerCase()) { setIsSameAsProject(true); } + setStep('details'); } else { setStep(isPromote ? 'details' : 'clients'); } @@ -235,6 +288,18 @@ export default function ProjectAssignmentForm( if (isStepValid) setStep(assignmentType === 'Project' ? 'work-orders' : 'review'); } else if (step === 'work-orders') { + if (woCodeStatus === 'unavailable') { + form.setError('workOrder.code' as any, { + type: 'manual', + message: woCodeMessage || 'Work Order code already exists' + }); + toast.error(woCodeMessage || 'Work Order code already exists'); + return; + } + if (woCodeStatus === 'checking') { + toast.info('Validating Work Order code, please wait...'); + return; + } // Trigger the parent key to validate all nested workOrder fields isStepValid = await form.trigger('workOrder'); if (isStepValid) setStep('review'); @@ -247,6 +312,11 @@ export default function ProjectAssignmentForm( toast.info('Assignment type is locked to Project during promotion'); return; } + + if (isEdit) { + toast.info('Assignment type is locked when updating data'); + return + } setStep('type'); } else if (step === 'details') setStep('clients'); @@ -300,10 +370,14 @@ export default function ProjectAssignmentForm( newPayload['project_id'] = isExistProject?.id || existAssignment?.project?.id } - if (isPromote && existAssignment) { + if (isPromote) { newPayload['im_id'] = existAssignment?.im_id || existAssignment?.id } + if (existAssignment) { + newPayload['project_id'] = existAssignment?.project?.id + } + let res: any; if (isPromote) { res = await serverApiCall('POST', '/project-assignment', newPayload); @@ -328,6 +402,8 @@ export default function ProjectAssignmentForm( } }; + + /* GET WO CODE */ useEffect(() => { if (!isExistProject) return @@ -343,6 +419,71 @@ export default function ProjectAssignmentForm( getWOCode(); }, [isExistProject]) + + /* VALIDATION WO CODE */ + useEffect(() => { + if (assignmentType !== 'Project' || !debouncedWoCode || !rawWoCodeCandidate) { + setWoCodeStatus('idle'); + setWoCodeMessage(''); + return; + } + + if (isEdit && existAssignment?.wo_code && debouncedWoCode.toLowerCase() === existAssignment.wo_code.toLowerCase()) { + setWoCodeStatus('available'); + setWoCodeMessage('Current Work Order code'); + form.clearErrors('workOrder.code' as any); + return; + } + + let isCancelled = false; + + async function checkWoCode() { + setWoCodeStatus('checking'); + setWoCodeMessage('Checking availability...'); + + try { + const res: any = await serverApiCall('POST', `/project-assignment/check-work-order-duplicate`, { + "wo_code": encodeURIComponent(debouncedWoCode) + }); + + console.log(res, debouncedWoCode) + + if (isCancelled) return; + + if (res.success) { + setWoCodeStatus('available'); + setWoCodeMessage('Work Order code is available'); + form.clearErrors('workOrder.code' as any); + } else { + const errorMsg = String(res.message || '').toLowerCase(); + if (res.code === 400 || errorMsg.includes('exist') || errorMsg.includes('already') || errorMsg.includes('duplicate')) { + setWoCodeStatus('unavailable'); + const msg = res.message || 'Work Order code already exists'; + setWoCodeMessage(msg); + form.setError('workOrder.code' as any, { + type: 'manual', + message: msg + }); + } else { + setWoCodeStatus('idle'); + setWoCodeMessage(''); + } + } + } catch { + if (!isCancelled) { + setWoCodeStatus('idle'); + setWoCodeMessage(''); + } + } + } + + checkWoCode(); + + return () => { + isCancelled = true; + }; + }, [debouncedWoCode, rawWoCodeCandidate, assignmentType, isEdit, existAssignment?.wo_code, existAssignment?.id, form]); + return ( <>
@@ -351,7 +492,7 @@ export default function ProjectAssignmentForm( {/* --- HEADER --- */}
-
@@ -585,7 +726,7 @@ export default function ProjectAssignmentForm( {/* Existing Project Selector / Linked Hero Card */} - {!isPromote && assignmentType === 'Project' && ( + {assignmentType === 'Project' && ( !isExistProject ? (
@@ -735,7 +876,7 @@ export default function ProjectAssignmentForm( type="button" variant="ghost" size="sm" - className="h-7 px-2 text-xs text-destructive hover:bg-destructive" + className="h-7 px-2 text-xs text-destructive hover:bg-destructive hover:text-white" onClick={handleClearProject} > Clear / Create New @@ -792,14 +933,22 @@ export default function ProjectAssignmentForm( ( {assignmentType} Code - + )} /> ( {assignmentType} Year - + + { + const cleaned = e.target.value.replace(/\D/g, '').slice(0, 4); + field.onChange(cleaned); + }} + /> + )} /> @@ -932,6 +1081,24 @@ export default function ProjectAssignmentForm( WO Code + {woCodeStatus === 'checking' && ( + + + Checking availability... + + )} + {woCodeStatus === 'available' && ( + + + {woCodeMessage || 'Available'} + + )} + {woCodeStatus === 'unavailable' && ( + + + {woCodeMessage || 'Already in use'} + + )}
@@ -950,15 +1117,30 @@ export default function ProjectAssignmentForm( field.onChange(val); }} /> + {woCodeStatus === 'checking' && ( + + + + )} + {woCodeStatus === 'available' && ( + + + + )} + {woCodeStatus === 'unavailable' && ( + + + + )} +

Full work order code will be submitted as: # {projectCode}-{field.value?.trim() || '...'}

- ); }} @@ -1185,9 +1367,9 @@ export default function ProjectAssignmentForm( {/* --- FOOTER NAVIGATION --- */} -
-
@@ -1208,6 +1390,29 @@ export default function ProjectAssignmentForm( {showEndUserForm ? setShowEndUserForm(false)} onSuccess={() => { mutateEndUserList(); setShowEndUserForm(false) }} /> : null} {showClientForm ? setShowClientForm(false)} onSuccess={() => { mutateClientList(); setShowClientForm(false) }} /> : null} {isFullLoading ? : null} + + + + + Discard unsaved changes? + + You have unsaved changes in this form. If you leave now, your progress will be lost. + + + + Keep Editing + { + setShowLeaveConfirmModal(false); + router.back(); + }} + > + Discard & Leave + + + + ); } \ No newline at end of file diff --git a/app/(dashboard)/task/component/project-assignment/AssignmentGrid.tsx b/app/(dashboard)/task/component/project-assignment/AssignmentGrid.tsx index 1f2e4b0..0920200 100644 --- a/app/(dashboard)/task/component/project-assignment/AssignmentGrid.tsx +++ b/app/(dashboard)/task/component/project-assignment/AssignmentGrid.tsx @@ -11,7 +11,7 @@ import { Tooltip, TooltipContent, TooltipTrigger, } from '@/components/ui/tooltip'; import { LazyImage } from '@/components/ui/lazy-image'; -import { Calendar, MoreVertical, ArrowUpRight, Clock } from 'lucide-react'; +import { Calendar, MoreVertical, ArrowUpRight, Clock, AlertTriangle } from 'lucide-react'; import Link from 'next/link'; import { cn } from '@/lib/utils'; import ConvertedAssignmentBadge from './ConvertedAssignmentBadge'; @@ -289,9 +289,54 @@ export default function AssignmentGrid({
{/* Actual Progress (Real Work) matching detail page styling */}
- - Actual - +
+ + Actual + + {item.hasWarning && ( + + + + + + + +
+ + {item.warningTitle} +
+

+ {item.warningReason} +

+ {item.warningDetails.length > 0 && ( +
+ {item.warningDetails.map((detail, idx) => ( +
+ • + {detail} +
+ ))} +
+ )} +
+
+ )} +
- - - {item.healthStatus} -

{item.remainingText}

{item.assignmentType} - {/* Project Status Badge matching technical status badge colors */} - {/* Code Pill with Tooltip */} {item.code ? ( @@ -245,10 +243,58 @@ export default function AssignmentList({ {/* 2. CENTER: Progress Bars (Actual Progress & Timeline) & 5-Node Stepper Track */}

{/* Actual Progress (Real Work) matching detail page styling */} -
- - Actual - +
+
+ + Actual + + {item.hasWarning && ( + + +
+
+ +
+ +
+
+ +
+ + {item.warningTitle} +
+

+ {item.warningReason} +

+ {item.warningDetails.length > 0 && ( +
+ {item.warningDetails.map((detail, idx) => ( +
+ • + {detail} +
+ ))} +
+ )} +
+
+ )} +
- {/* Health Badge */} -
- - - {item.healthStatus} - -
+ {/* Project Status Badge matching technical status badge colors */} + {/* Remaining days or completion date */}

diff --git a/app/(dashboard)/task/component/project-assignment/ProjectAssignmentDashboardStats.tsx b/app/(dashboard)/task/component/project-assignment/ProjectAssignmentDashboardStats.tsx index 086dbdc..cad2fc7 100644 --- a/app/(dashboard)/task/component/project-assignment/ProjectAssignmentDashboardStats.tsx +++ b/app/(dashboard)/task/component/project-assignment/ProjectAssignmentDashboardStats.tsx @@ -2,7 +2,7 @@ import { useMemo } from 'react'; import { motion } from 'motion/react'; -import { Briefcase, FileText, Users, TrendingUp, CheckCircle2, AlertTriangle } from 'lucide-react'; +import { Briefcase, FileText, Users, AlertCircle, CheckCircle2, AlertTriangle } from 'lucide-react'; import { Card900 } from '@/components/ui/card'; import { IProjectAssignment } from '../../type.assignment'; import { calculateDashboardStats } from '../../utils/assignment-overview-helpers'; @@ -24,7 +24,7 @@ export default function ProjectAssignmentDashboardStats({ Project Assignment Dashboard -

+
{/* 1. Total Projects */} @@ -45,7 +45,7 @@ export default function ProjectAssignmentDashboardStats({
-

Active Work Orders

+

Work Orders

{stats.activeWorkOrders}

@@ -64,41 +64,17 @@ export default function ProjectAssignmentDashboardStats({ - {/* 4. Average Progress */} + {/* 4. Needs Attention / Behind Schedule (Replaces Average Progress) */} - -
- + +
+
-

Average Progress

-

{stats.averageProgress}%

-
-
- - - {/* 5. On-Time Projects */} - - -
- -
-
-

On-Time Projects

-

{stats.onTimeRatio}

-
-
-
- - {/* 6. At Risk / Delayed */} - - -
- -
-
-

At Risk / Delayed

-

{stats.atRiskDelayed}

+

+ Needs Attention +

+

{stats.needsAttention}

diff --git a/app/(dashboard)/task/utils/assignment-overview-helpers.ts b/app/(dashboard)/task/utils/assignment-overview-helpers.ts index eb5551a..f354d7d 100644 --- a/app/(dashboard)/task/utils/assignment-overview-helpers.ts +++ b/app/(dashboard)/task/utils/assignment-overview-helpers.ts @@ -157,6 +157,14 @@ export interface AssignmentOverview { 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) { @@ -705,7 +713,7 @@ export function getAssignmentOverview(assignment: IProjectAssignment, index: num // 2. Resolve Technical Status & Delivery Health const { hasTechnicalStatus, technicalRank } = resolveTechnicalStatus(assignment); const ptrEndDate = getPtrEndDate(assignment); - const { healthStatus, healthBadgeClass, healthDotClass, isCritical } = resolveDeliveryHealth( + const { healthStatus, healthBadgeClass, healthDotClass } = resolveDeliveryHealth( technicalRank, hasTechnicalStatus, progressPercent, @@ -761,12 +769,41 @@ export function getAssignmentOverview(assignment: IProjectAssignment, index: num 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 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, @@ -796,6 +833,12 @@ export function getAssignmentOverview(assignment: IProjectAssignment, index: num nextMilestoneText, updatedAgoText, latestActivityText, + hasWarning, + warningTitle, + warningReason, + warningDetails, + isCriticalOrOffTrack, + isBehindSchedule, }; } @@ -825,10 +868,11 @@ export function calculateDashboardStats(assignments: IProjectAssignment[]) { }); const assignedPeopleCount = uniqueUsers.size; - // Average progress - const avgProgress = overviews.length > 0 - ? Math.round(overviews.reduce((acc, o) => acc + o.progressPercent, 0) / overviews.length) - : 0; + // 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; @@ -838,6 +882,7 @@ export function calculateDashboardStats(assignments: IProjectAssignment[]) { totalProjects: totalProjects || totalAssignments, activeWorkOrders: activeWorkOrders || totalAssignments, assignedPeople: assignedPeopleCount, + needsAttention: needsAttentionCount, averageProgress: avgProgress, onTimeRatio: `${onTimeCount} / ${totalAssignments}`, atRiskDelayed: atRiskCount, diff --git a/package.json b/package.json index 58bd47b..b401e1b 100644 --- a/package.json +++ b/package.json @@ -52,7 +52,7 @@ "framer-motion": "^12.23.25", "get-orientation": "^1.1.2", "heic2any": "^0.0.4", - "lucide-react": "^1.49.0", + "lucide-react": "^1.68.0", "motion": "^12.38.0", "next": "^16.0.10", "next-auth": "^4.24.13", @@ -93,4 +93,4 @@ "tw-animate-css": "^1.4.0", "typescript": "^5" } -} \ No newline at end of file +}