mirror of
https://github.com/ichsankurnia/hats-app.git
synced 2026-12-05 10:46:29 +00:00
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.
This commit is contained in:
+1
-1
@@ -154,7 +154,7 @@ export default function AddActivityLogModal({
|
||||
</Label>
|
||||
</div>
|
||||
<DateTimePicker
|
||||
placeholder="Pilih tanggal selesai"
|
||||
placeholder="Select datetime"
|
||||
date={date}
|
||||
setDate={setDate}
|
||||
/>
|
||||
|
||||
+220
-15
@@ -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<IClient | null>(client || null);
|
||||
const [selectedEndUser, setSelectedEndUser] = useState<IEndUser | null>(null);
|
||||
const [isSameAsProject, setIsSameAsProject] = useState(false);
|
||||
const [showLeaveConfirmModal, setShowLeaveConfirmModal] = useState(false);
|
||||
const [woCodeStatus, setWoCodeStatus] = useState<'idle' | 'checking' | 'available' | 'unavailable'>('idle');
|
||||
const [woCodeMessage, setWoCodeMessage] = useState<string>('');
|
||||
|
||||
const form = useForm<AssignmentFormValues>({
|
||||
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 (
|
||||
<>
|
||||
<Form {...form}>
|
||||
@@ -351,7 +492,7 @@ export default function ProjectAssignmentForm(
|
||||
{/* --- HEADER --- */}
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-4">
|
||||
<Button type="button" variant="ghost" size="icon" onClick={() => router.back()}>
|
||||
<Button type="button" variant="ghost" size="icon" onClick={handleHeaderBackClick}>
|
||||
<ArrowLeft className="w-5 h-5" />
|
||||
</Button>
|
||||
<div>
|
||||
@@ -585,7 +726,7 @@ export default function ProjectAssignmentForm(
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-6">
|
||||
{/* Existing Project Selector / Linked Hero Card */}
|
||||
{!isPromote && assignmentType === 'Project' && (
|
||||
{assignmentType === 'Project' && (
|
||||
!isExistProject ? (
|
||||
<div className="p-4 rounded-xl border border-border/80 bg-zinc-200/25 dark:bg-zinc-800/90 space-y-3">
|
||||
<div className="space-y-0.5">
|
||||
@@ -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}
|
||||
>
|
||||
<X className="w-3.5 h-3.5" /> Clear / Create New
|
||||
@@ -792,14 +933,22 @@ export default function ProjectAssignmentForm(
|
||||
<FormField control={form.control} name="code" disabled={isExistProject} render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{assignmentType} Code</FormLabel>
|
||||
<FormControl><Input placeholder="e.g. 24016" {...field} /></FormControl>
|
||||
<FormControl><Input placeholder="e.g. 24016" {...field} disabled={isExistProject} /></FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)} />
|
||||
<FormField control={form.control} name="year" disabled={isExistProject} render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{assignmentType} Year</FormLabel>
|
||||
<FormControl><Input placeholder="e.g. 2024" {...field} /></FormControl>
|
||||
<FormControl>
|
||||
<Input placeholder="e.g. 2026" maxLength={4} inputMode="numeric" disabled={isExistProject}
|
||||
{...field}
|
||||
onChange={(e) => {
|
||||
const cleaned = e.target.value.replace(/\D/g, '').slice(0, 4);
|
||||
field.onChange(cleaned);
|
||||
}}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)} />
|
||||
@@ -932,6 +1081,24 @@ export default function ProjectAssignmentForm(
|
||||
<FormLabel className="text-sm font-semibold text-foreground">
|
||||
WO Code
|
||||
</FormLabel>
|
||||
{woCodeStatus === 'checking' && (
|
||||
<span className="inline-flex items-center gap-1.5 text-xs text-muted-foreground">
|
||||
<Loader2 className="w-3.5 h-3.5 animate-spin" />
|
||||
Checking availability...
|
||||
</span>
|
||||
)}
|
||||
{woCodeStatus === 'available' && (
|
||||
<span className="inline-flex items-center gap-1.5 text-xs text-emerald-600 dark:text-emerald-400 font-medium">
|
||||
<CheckCircle2 className="w-3.5 h-3.5" />
|
||||
{woCodeMessage || 'Available'}
|
||||
</span>
|
||||
)}
|
||||
{woCodeStatus === 'unavailable' && (
|
||||
<span className="inline-flex items-center gap-1.5 text-xs text-destructive font-medium">
|
||||
<X className="w-3.5 h-3.5" />
|
||||
{woCodeMessage || 'Already in use'}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<FormControl>
|
||||
<InputGroup>
|
||||
@@ -950,15 +1117,30 @@ export default function ProjectAssignmentForm(
|
||||
field.onChange(val);
|
||||
}}
|
||||
/>
|
||||
{woCodeStatus === 'checking' && (
|
||||
<InputGroupAddon align="inline-end">
|
||||
<Loader2 className="w-4 h-4 animate-spin text-muted-foreground" />
|
||||
</InputGroupAddon>
|
||||
)}
|
||||
{woCodeStatus === 'available' && (
|
||||
<InputGroupAddon align="inline-end">
|
||||
<CheckCircle2 className="w-4 h-4 text-emerald-500" />
|
||||
</InputGroupAddon>
|
||||
)}
|
||||
{woCodeStatus === 'unavailable' && (
|
||||
<InputGroupAddon align="inline-end">
|
||||
<CircleExclamationPoint className="w-4 h-4 text-destructive" />
|
||||
</InputGroupAddon>
|
||||
)}
|
||||
</InputGroup>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
<p className="text-[11px] text-muted-foreground flex items-center gap-1.5">
|
||||
<span>Full work order code will be submitted as:</span>
|
||||
<span className="font-mono font-semibold text-foreground px-1.5 py-0.5 rounded bg-muted/60 dark:bg-zinc-900 border border-border/60">
|
||||
# {projectCode}-{field.value?.trim() || '...'}
|
||||
</span>
|
||||
</p>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
);
|
||||
}}
|
||||
@@ -1185,9 +1367,9 @@ export default function ProjectAssignmentForm(
|
||||
</AnimatePresence>
|
||||
|
||||
{/* --- FOOTER NAVIGATION --- */}
|
||||
<div className="fixed bottom-0 left-0 right-0 p-6 bg-background/80 backdrop-blur-md border-t flex justify-between z-50">
|
||||
<Button type="button" variant="ghost" onClick={handleBack} disabled={step === 'type'}>
|
||||
Back
|
||||
<div className="fixed bottom-0 left-0 right-0 p-6 bg-background/80 backdrop-blur-md border-t flex justify-end gap-3 z-50">
|
||||
<Button type="button" variant='secondary' className='gap-2' onClick={handleBack} disabled={step === 'type'}>
|
||||
<ArrowLeft className="w-4 h-4" />Previous
|
||||
</Button>
|
||||
|
||||
<div className="flex gap-4">
|
||||
@@ -1208,6 +1390,29 @@ export default function ProjectAssignmentForm(
|
||||
{showEndUserForm ? <FormEndUser onCancel={() => setShowEndUserForm(false)} onSuccess={() => { mutateEndUserList(); setShowEndUserForm(false) }} /> : null}
|
||||
{showClientForm ? <FormClient onCancel={() => setShowClientForm(false)} onSuccess={() => { mutateClientList(); setShowClientForm(false) }} /> : null}
|
||||
{isFullLoading ? <PageLoading /> : null}
|
||||
|
||||
<AlertDialog open={showLeaveConfirmModal} onOpenChange={setShowLeaveConfirmModal}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>Discard unsaved changes?</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
You have unsaved changes in this form. If you leave now, your progress will be lost.
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>Keep Editing</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
className={buttonVariants({ variant: "destructive" })}
|
||||
onClick={() => {
|
||||
setShowLeaveConfirmModal(false);
|
||||
router.back();
|
||||
}}
|
||||
>
|
||||
Discard & Leave
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -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({
|
||||
<div className="space-y-2 pt-2 border-t border-border/60">
|
||||
{/* Actual Progress (Real Work) matching detail page styling */}
|
||||
<div className="flex items-center justify-between text-xs font-mono font-medium">
|
||||
<span className="text-[10px] tracking-wider font-semibold text-his bg-his/10 px-1.5 py-0.5 rounded font-sans shrink-0">
|
||||
Actual
|
||||
</span>
|
||||
<div className="flex items-center gap-1.5 shrink-0">
|
||||
<span className="text-[10px] tracking-wider font-semibold text-his bg-his/10 px-1.5 py-0.5 rounded font-sans shrink-0">
|
||||
Actual
|
||||
</span>
|
||||
{item.hasWarning && (
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<span
|
||||
tabIndex={0}
|
||||
role="button"
|
||||
aria-label={item.warningTitle}
|
||||
className={cn(
|
||||
"cursor-help inline-flex items-center justify-center transition-all focus:outline-none",
|
||||
item.isCriticalOrOffTrack
|
||||
? "text-rose-500 hover:text-rose-600 dark:text-rose-400"
|
||||
: "text-amber-500 hover:text-amber-600 dark:text-amber-400"
|
||||
)}
|
||||
>
|
||||
<AlertTriangle className="w-3.5 h-3.5 animate-pulse" />
|
||||
</span>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side="top" className="max-w-xs p-3 space-y-1.5 text-xs shadow-lg border border-border/80">
|
||||
<div className={cn(
|
||||
"flex items-center gap-1.5 font-semibold",
|
||||
item.isCriticalOrOffTrack
|
||||
? "text-rose-600 dark:text-rose-400"
|
||||
: "text-amber-600 dark:text-amber-400"
|
||||
)}>
|
||||
<AlertTriangle className="w-4 h-4 shrink-0" />
|
||||
<span>{item.warningTitle}</span>
|
||||
</div>
|
||||
<p className="text-[11px] text-muted-foreground leading-relaxed">
|
||||
{item.warningReason}
|
||||
</p>
|
||||
{item.warningDetails.length > 0 && (
|
||||
<div className="pt-1.5 border-t border-border/50 space-y-0.5 text-[10px] text-foreground font-mono">
|
||||
{item.warningDetails.map((detail, idx) => (
|
||||
<div key={idx} className="flex items-center gap-1.5">
|
||||
<span className={item.isCriticalOrOffTrack ? "text-rose-500 font-bold" : "text-amber-500 font-bold"}>•</span>
|
||||
<span>{detail}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
)}
|
||||
</div>
|
||||
<div className="h-1.5 rounded-full bg-zinc-200 dark:bg-zinc-700/60 flex-1 mx-2.5 overflow-hidden">
|
||||
<div
|
||||
className="h-full rounded-full bg-his transition-all duration-700 ease-out"
|
||||
@@ -322,13 +367,6 @@ export default function AssignmentGrid({
|
||||
{/* Footer: Delivery Health Badge, Schedule, Latest Activity & Team Avatars */}
|
||||
<div className="pt-3 border-t border-border/60 flex items-center justify-between gap-2 text-xs">
|
||||
<div className="space-y-1 min-w-0 flex-1">
|
||||
<span className={cn(
|
||||
"inline-flex items-center gap-1.5 rounded-full border px-2 py-0.5 text-[11px] font-medium",
|
||||
item.healthBadgeClass
|
||||
)}>
|
||||
<span className={cn("h-1.5 w-1.5 rounded-full", item.healthDotClass)} />
|
||||
<span>{item.healthStatus}</span>
|
||||
</span>
|
||||
<p className="text-[11px] text-muted-foreground truncate">{item.remainingText}</p>
|
||||
<p
|
||||
className="text-[10px] text-muted-foreground/75 truncate flex items-center gap-1 font-sans"
|
||||
|
||||
@@ -11,7 +11,7 @@ import {
|
||||
Tooltip, TooltipContent, TooltipTrigger,
|
||||
} from '@/components/ui/tooltip';
|
||||
import { LazyImage } from '@/components/ui/lazy-image';
|
||||
import { Calendar, MoreVertical, ArrowUpRight, Clock, FolderGit2 } from 'lucide-react';
|
||||
import { Calendar, MoreVertical, ArrowUpRight, Clock, FolderGit2, AlertTriangle } from 'lucide-react';
|
||||
import Link from 'next/link';
|
||||
import { cn } from '@/lib/utils';
|
||||
import ConvertedAssignmentBadge from './ConvertedAssignmentBadge';
|
||||
@@ -155,8 +155,6 @@ export default function AssignmentList({
|
||||
<span>{item.assignmentType}</span>
|
||||
</span>
|
||||
|
||||
{/* Project Status Badge matching technical status badge colors */}
|
||||
<BadgeStatus status={assignment.project_assignment_status.name} />
|
||||
|
||||
{/* 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 */}
|
||||
<div className="w-full xl:w-72 2xl:w-80 shrink-0 space-y-2 pt-2 xl:pt-0 border-t xl:border-t-0 border-border/60">
|
||||
{/* Actual Progress (Real Work) matching detail page styling */}
|
||||
<div className="flex items-center justify-between text-xs font-mono font-medium">
|
||||
<span className="text-[10px] tracking-wider font-semibold text-his bg-his/10 px-1.5 py-0.5 rounded font-sans shrink-0">
|
||||
Actual
|
||||
</span>
|
||||
<div className="flex items-center justify-between text-xs font-mono font-medium relative">
|
||||
<div className="flex items-center gap-1.5 shrink-0">
|
||||
<span className="text-[10px] tracking-wider font-semibold text-his bg-his/10 px-1.5 py-0.5 rounded font-sans shrink-0">
|
||||
Actual
|
||||
</span>
|
||||
{item.hasWarning && (
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<div
|
||||
tabIndex={0}
|
||||
role="button"
|
||||
aria-label={item.warningTitle}
|
||||
className={cn(
|
||||
"cursor-help absolute -right-6 flex items-center justify-center transition-all focus:outline-none",
|
||||
item.isCriticalOrOffTrack
|
||||
? "text-rose-500 hover:text-rose-600 dark:text-rose-400"
|
||||
: "text-amber-500 hover:text-amber-600 dark:text-amber-400"
|
||||
)}
|
||||
>
|
||||
<div className={`absolute rounded-full animate-pulse w-5 h-5 ${item.isCriticalOrOffTrack ? 'bg-rose-600/20 dark:bg-rose-400/20' : 'bg-amber-600/20 dark:bg-amber-400/20'}`}>
|
||||
|
||||
</div>
|
||||
<AlertTriangle className="w-3.5 h-3.5" />
|
||||
</div>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side="top" className="max-w-xs p-3 space-y-1.5 text-xs shadow-lg border border-border/80">
|
||||
<div className={cn(
|
||||
"flex items-center gap-1.5 font-semibold",
|
||||
item.isCriticalOrOffTrack
|
||||
? "text-rose-600 dark:text-rose-400"
|
||||
: "text-amber-600 dark:text-amber-400"
|
||||
)}>
|
||||
<AlertTriangle className="w-4 h-4 shrink-0" />
|
||||
<span>{item.warningTitle}</span>
|
||||
</div>
|
||||
<p className="text-[11px] text-muted-foreground leading-relaxed">
|
||||
{item.warningReason}
|
||||
</p>
|
||||
{item.warningDetails.length > 0 && (
|
||||
<div className="pt-1.5 border-t border-border/50 space-y-0.5 text-[10px] text-foreground font-mono">
|
||||
{item.warningDetails.map((detail, idx) => (
|
||||
<div key={idx} className="flex items-center gap-1.5">
|
||||
<span className={item.isCriticalOrOffTrack ? "text-rose-500 font-bold" : "text-amber-500 font-bold"}>•</span>
|
||||
<span>{detail}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
)}
|
||||
</div>
|
||||
<div className="h-1.5 rounded-full bg-zinc-200 dark:bg-zinc-700/60 flex-1 mx-2.5 overflow-hidden">
|
||||
<div
|
||||
className="h-full rounded-full bg-his transition-all duration-700 ease-out"
|
||||
@@ -317,16 +363,8 @@ export default function AssignmentList({
|
||||
{/* 4. RIGHT: Delivery Health Badge, Schedule, Next Step & Updated */}
|
||||
<div className="flex items-center justify-between xl:justify-end gap-4 w-full xl:w-auto shrink-0 pt-2 xl:pt-0 border-t xl:border-t-0 border-border/60">
|
||||
<div className="space-y-1.5 min-w-0 xl:w-48 2xl:w-56 text-left">
|
||||
{/* Health Badge */}
|
||||
<div>
|
||||
<span className={cn(
|
||||
"inline-flex items-center gap-1.5 rounded-full border px-2.5 py-0 text-[11px] font-semibold",
|
||||
item.healthBadgeClass
|
||||
)}>
|
||||
<span className={cn("h-1.5 w-1.5 rounded-full", item.healthDotClass)} />
|
||||
<span>{item.healthStatus}</span>
|
||||
</span>
|
||||
</div>
|
||||
{/* Project Status Badge matching technical status badge colors */}
|
||||
<BadgeStatus status={assignment.project_assignment_status.name} />
|
||||
|
||||
{/* Remaining days or completion date */}
|
||||
<p className="text-xs text-muted-foreground flex items-center gap-1.5 truncate">
|
||||
|
||||
+11
-35
@@ -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
|
||||
</h2>
|
||||
|
||||
<div className="grid grid-cols-2 sm:grid-cols-3 xl:grid-cols-6 gap-3 sm:gap-4">
|
||||
<div className="grid grid-cols-2 sm:grid-cols-4 xl:grid-cols-4 gap-3 sm:gap-4">
|
||||
{/* 1. Total Projects */}
|
||||
<motion.div initial={{ opacity: 0, y: 6 }} animate={{ opacity: 1, y: 0 }} transition={{ duration: 0.2 }}>
|
||||
<Card900 className="p-3.5 sm:p-5 rounded-2xl border border-border/80 bg-card hover:border-blue-500/30 transition-all flex flex-row items-center gap-3 md:gap-3.5 min-w-0 shadow-2xs">
|
||||
@@ -45,7 +45,7 @@ export default function ProjectAssignmentDashboardStats({
|
||||
<Briefcase className="w-5 h-5" />
|
||||
</div>
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="text-xs text-muted-foreground truncate">Active Work Orders</p>
|
||||
<p className="text-xs text-muted-foreground truncate">Work Orders</p>
|
||||
<p className="text-lg sm:text-xl font-bold tracking-tight text-foreground">{stats.activeWorkOrders}</p>
|
||||
</div>
|
||||
</Card900>
|
||||
@@ -64,41 +64,17 @@ export default function ProjectAssignmentDashboardStats({
|
||||
</Card900>
|
||||
</motion.div>
|
||||
|
||||
{/* 4. Average Progress */}
|
||||
{/* 4. Needs Attention / Behind Schedule (Replaces Average Progress) */}
|
||||
<motion.div initial={{ opacity: 0, y: 6 }} animate={{ opacity: 1, y: 0 }} transition={{ duration: 0.2, delay: 0.09 }}>
|
||||
<Card900 className="p-3.5 sm:p-5 rounded-2xl border border-border/80 bg-card hover:border-orange-500/30 transition-all flex flex-row items-center gap-3 md:gap-3.5 min-w-0 shadow-2xs">
|
||||
<div className="h-10 w-10 sm:h-11 sm:w-11 rounded-xl bg-orange-500/10 dark:bg-orange-500/15 border border-orange-500/20 flex items-center justify-center shrink-0 text-orange-500 dark:text-orange-400">
|
||||
<TrendingUp className="w-5 h-5" />
|
||||
<Card900 className="p-3.5 sm:p-5 rounded-2xl border border-border/80 bg-card hover:border-amber-500/30 transition-all flex flex-row items-center gap-3 md:gap-3.5 min-w-0 shadow-2xs">
|
||||
<div className="h-10 w-10 sm:h-11 sm:w-11 rounded-xl bg-amber-500/10 dark:bg-amber-500/15 border border-amber-500/20 flex items-center justify-center shrink-0 text-amber-500 dark:text-amber-400">
|
||||
<AlertCircle className="w-5 h-5" />
|
||||
</div>
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="text-xs text-muted-foreground truncate">Average Progress</p>
|
||||
<p className="text-lg sm:text-xl font-bold tracking-tight text-foreground">{stats.averageProgress}%</p>
|
||||
</div>
|
||||
</Card900>
|
||||
</motion.div>
|
||||
|
||||
{/* 5. On-Time Projects */}
|
||||
<motion.div initial={{ opacity: 0, y: 6 }} animate={{ opacity: 1, y: 0 }} transition={{ duration: 0.2, delay: 0.12 }}>
|
||||
<Card900 className="p-3.5 sm:p-5 rounded-2xl border border-border/80 bg-card hover:border-emerald-500/30 transition-all flex flex-row items-center gap-3 md:gap-3.5 min-w-0 shadow-2xs">
|
||||
<div className="h-10 w-10 sm:h-11 sm:w-11 rounded-xl bg-emerald-500/10 dark:bg-emerald-500/15 border border-emerald-500/20 flex items-center justify-center shrink-0 text-emerald-500 dark:text-emerald-400">
|
||||
<CheckCircle2 className="w-5 h-5" />
|
||||
</div>
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="text-xs text-muted-foreground truncate">On-Time Projects</p>
|
||||
<p className="text-lg sm:text-xl font-bold tracking-tight text-foreground">{stats.onTimeRatio}</p>
|
||||
</div>
|
||||
</Card900>
|
||||
</motion.div>
|
||||
|
||||
{/* 6. At Risk / Delayed */}
|
||||
<motion.div initial={{ opacity: 0, y: 6 }} animate={{ opacity: 1, y: 0 }} transition={{ duration: 0.2, delay: 0.15 }}>
|
||||
<Card900 className="p-3.5 sm:p-5 rounded-2xl border border-border/80 bg-card hover:border-rose-500/30 transition-all flex flex-row items-center gap-3 md:gap-3.5 min-w-0 shadow-2xs">
|
||||
<div className="h-10 w-10 sm:h-11 sm:w-11 rounded-xl bg-rose-500/10 dark:bg-rose-500/15 border border-rose-500/20 flex items-center justify-center shrink-0 text-rose-500 dark:text-rose-400">
|
||||
<AlertTriangle className="w-5 h-5" />
|
||||
</div>
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="text-xs text-muted-foreground truncate">At Risk / Delayed</p>
|
||||
<p className="text-lg sm:text-xl font-bold tracking-tight text-foreground">{stats.atRiskDelayed}</p>
|
||||
<p className="text-xs text-muted-foreground truncate" title="Assignments with Critical/Off Track status or actual progress lagging behind timeline">
|
||||
Needs Attention
|
||||
</p>
|
||||
<p className="text-lg sm:text-xl font-bold tracking-tight text-foreground">{stats.needsAttention}</p>
|
||||
</div>
|
||||
</Card900>
|
||||
</motion.div>
|
||||
|
||||
@@ -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,
|
||||
|
||||
+2
-2
@@ -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"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user