mirror of
https://github.com/ichsankurnia/hats-app.git
synced 2026-12-05 10:46:29 +00:00
Merge branch 'project-assignment' of https://github.com/ichsankurnia/hats-app into project-assignment
This commit is contained in:
@@ -1,11 +1,11 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from 'react';
|
||||
import { useState, useMemo } from 'react';
|
||||
import { Briefcase } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Card, CardContent } from '@/components/ui/card';
|
||||
import Link from 'next/link';
|
||||
import { IProjectAssignment } from '../../../type.assignment';
|
||||
import { EndUser, IProjectAssignment } from '../../../type.assignment';
|
||||
import { useRouter, useSearchParams } from 'next/navigation';
|
||||
import dynamic from 'next/dynamic';
|
||||
import FilterComponent from '../../../component/FilterComponent';
|
||||
@@ -89,13 +89,35 @@ export default function ClientDetailComponent({ clientId, assignmentLists }: Pro
|
||||
setAction(undefined);
|
||||
};
|
||||
|
||||
const uniqueEndUsers = useMemo(() => {
|
||||
const seen = new Set<string>();
|
||||
const result: EndUser[] = [];
|
||||
|
||||
for (const item of assignmentLists) {
|
||||
const endUser = item?.end_user;
|
||||
if (!endUser) continue;
|
||||
const key = String(endUser.id ?? endUser.code ?? endUser.name ?? '');
|
||||
if (key && !seen.has(key)) {
|
||||
seen.add(key);
|
||||
result.push(endUser);
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}, [assignmentLists]);
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* --- PROJECT ASSIGNMENT DASHBOARD STATS --- */}
|
||||
<ProjectAssignmentDashboardStats assignments={assignmentLists} />
|
||||
|
||||
{/* --- FILTER & SEARCH TOOLBAR --- */}
|
||||
<FilterComponent showLayoutToggle placeholder="Search projects..." />
|
||||
<FilterComponent
|
||||
hideEndUser={false}
|
||||
showLayoutToggle
|
||||
placeholder="Search projects..."
|
||||
endUserList={uniqueEndUsers}
|
||||
/>
|
||||
|
||||
{/* --- EMPTY STATE --- */}
|
||||
{assignmentLists.length === 0 ? (
|
||||
@@ -199,4 +221,4 @@ export default function ClientDetailComponent({ clientId, assignmentLists }: Pro
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
+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,6 +11,8 @@ import {
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { cn } from '@/lib/utils';
|
||||
import useDebounce from '@/hooks/useDebounce';
|
||||
import { EndUser } from '../type.assignment';
|
||||
import { IEndUser } from '../types';
|
||||
|
||||
const FilterModal = dynamic(
|
||||
() => import('./FilterModal').then((mod) => mod.FilterModal),
|
||||
@@ -26,6 +28,7 @@ const FilterModal = dynamic(
|
||||
);
|
||||
|
||||
type Props = {
|
||||
endUserList?: (EndUser | IEndUser)[]
|
||||
hideClient?: boolean
|
||||
hideEndUser?: boolean
|
||||
hideStatus?: boolean;
|
||||
@@ -41,6 +44,7 @@ type Props = {
|
||||
};
|
||||
|
||||
const FilterComponent: FC<Props> = ({
|
||||
endUserList,
|
||||
hideFilterModal,
|
||||
hideClient,
|
||||
hideEndUser,
|
||||
@@ -52,7 +56,7 @@ const FilterComponent: FC<Props> = ({
|
||||
hideCategory,
|
||||
hideSort,
|
||||
showLayoutToggle,
|
||||
placeholder = "Search client...",
|
||||
placeholder = "Search client or employee...",
|
||||
}) => {
|
||||
const router = useRouter();
|
||||
const pathname = usePathname();
|
||||
@@ -60,6 +64,7 @@ const FilterComponent: FC<Props> = ({
|
||||
|
||||
const currentQuery = searchParams?.get('q') || '';
|
||||
const currentSort = searchParams?.get('sort') || '';
|
||||
const sortValue = (currentSort === 'active_first' || !currentSort) ? 'default' : currentSort;
|
||||
const currentLayout = searchParams?.get('layout') === 'grid' ? 'grid' : 'list';
|
||||
|
||||
const [searchText, setSearchText] = useState(currentQuery);
|
||||
@@ -117,6 +122,7 @@ const FilterComponent: FC<Props> = ({
|
||||
|
||||
{!hideFilterModal ?
|
||||
<FilterModal
|
||||
endUserList={endUserList}
|
||||
hideClient={hideClient} hideEndUser={hideEndUser}
|
||||
hideCategory={hideCategory} hideStatus={hideStatus} hideAssignedTo={hideAssignedTo}
|
||||
hideProjectDateFilter={hideProjectDateFilter} hideWoDateFilter={hideWoDateFilter} hideImDateFilter={hideImDateFilter} />
|
||||
@@ -159,12 +165,11 @@ const FilterComponent: FC<Props> = ({
|
||||
) : null}
|
||||
|
||||
{!hideSort ? (
|
||||
<Select value={currentSort} onValueChange={handleSortChange}>
|
||||
<Select value={sortValue} onValueChange={handleSortChange}>
|
||||
<SelectTrigger className="flex-1 md:flex-none md:w-max min-w-32.5 bg-white dark:bg-zinc-900 h-9 text-xs sm:text-sm">
|
||||
<SelectValue placeholder="Active First" />
|
||||
<SelectValue placeholder="Default" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="active_first">Active First</SelectItem>
|
||||
<SelectItem value="default">Default</SelectItem>
|
||||
<SelectItem value="latest">Latest</SelectItem>
|
||||
<SelectItem value="oldest">Oldest</SelectItem>
|
||||
@@ -178,4 +183,4 @@ const FilterComponent: FC<Props> = ({
|
||||
);
|
||||
}
|
||||
|
||||
export default FilterComponent;
|
||||
export default FilterComponent;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"use client"
|
||||
|
||||
import { useState, useEffect, type FC } from 'react';
|
||||
import { useState, useEffect, useMemo, type FC } from 'react';
|
||||
import { usePathname, useRouter, useSearchParams } from 'next/navigation';
|
||||
import { format, parseISO } from 'date-fns';
|
||||
import { ListFilter } from 'lucide-react';
|
||||
@@ -23,11 +23,12 @@ import { DatePickerMultiMode } from '@/components/ui/datepicker-multi-mode';
|
||||
import { MultiSelect } from '@/components/ui/multi-select';
|
||||
import { useFetchWithAxios } from '@/lib/axios/useFetch';
|
||||
|
||||
import { ProjectStatus } from '../type.assignment';
|
||||
import { EndUser, ProjectStatus } from '../type.assignment';
|
||||
import { IUser } from '@/app/admin/administration/user/component/type';
|
||||
import { IClient, IEndUser } from '../types';
|
||||
|
||||
interface Props {
|
||||
endUserList?: (EndUser | IEndUser)[]
|
||||
hideClient?: boolean
|
||||
hideEndUser?: boolean
|
||||
hideStatus?: boolean;
|
||||
@@ -38,16 +39,15 @@ interface Props {
|
||||
hideCategory?: boolean;
|
||||
}
|
||||
|
||||
export const FilterModal: FC<Props> = ({ hideClient = true, hideEndUser = true, hideStatus, hideAssignedTo, hideProjectDateFilter, hideWoDateFilter, hideImDateFilter, hideCategory }) => {
|
||||
export const FilterModal: FC<Props> = ({ hideClient = true, hideEndUser = true, endUserList, hideStatus, hideAssignedTo, hideProjectDateFilter, hideWoDateFilter, hideImDateFilter, hideCategory }) => {
|
||||
const [open, setOpen] = useState(false);
|
||||
const router = useRouter();
|
||||
const pathname = usePathname();
|
||||
const searchParams = useSearchParams();
|
||||
|
||||
const { data: clientList } = useFetchWithAxios(!hideClient ? '/client' : null)
|
||||
const { data: endUserList } = useFetchWithAxios(!hideEndUser ? '/end-user' : null)
|
||||
const { data: statusList } = useFetchWithAxios(!hideStatus ? '/project-assignment-status' : null);
|
||||
const { data: userList } = useFetchWithAxios(!hideAssignedTo ? '/user' : null);
|
||||
const { data: statusList } = useFetchWithAxios(!hideStatus ? '/project-assignment-status?type=master' : null);
|
||||
const { data: userList } = useFetchWithAxios(!hideAssignedTo ? '/user/active' : null);
|
||||
|
||||
const [clientFilter, setClientFilter] = useState<any[]>([]);
|
||||
const [enduserFilter, setEnduserFilter] = useState<any[]>([]);
|
||||
@@ -58,6 +58,23 @@ export const FilterModal: FC<Props> = ({ hideClient = true, hideEndUser = true,
|
||||
const [woDate, setWoDate] = useState<DateRange | undefined>();
|
||||
const [imDate, setImDate] = useState<DateRange | undefined>();
|
||||
|
||||
// Deduplicate end users options
|
||||
const endUserOptions = useMemo(() => {
|
||||
if (!endUserList || endUserList.length === 0) return [];
|
||||
const seen = new Set<string>();
|
||||
const options: { label: string; value: string }[] = [];
|
||||
|
||||
for (const item of endUserList) {
|
||||
if (!item || item.id === undefined || item.id === null) continue;
|
||||
const val = String(item.id);
|
||||
if (!seen.has(val)) {
|
||||
seen.add(val);
|
||||
options.push({ label: item.name, value: val });
|
||||
}
|
||||
}
|
||||
return options;
|
||||
}, [endUserList]);
|
||||
|
||||
// Set initial filter if values exist in URL
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
@@ -91,14 +108,13 @@ export const FilterModal: FC<Props> = ({ hideClient = true, hideEndUser = true,
|
||||
}
|
||||
}, [open, searchParams]);
|
||||
|
||||
|
||||
const handleApplyFilters = () => {
|
||||
const params = new URLSearchParams(searchParams?.toString());
|
||||
|
||||
if (clientFilter.length > 0) params.set('client', clientFilter.join(','));
|
||||
if (clientFilter?.length > 0) params.set('client', clientFilter.join(','));
|
||||
else params.delete('client');
|
||||
|
||||
if (endUserList.length > 0) params.set('end_user', endUserList.join(','));
|
||||
if (enduserFilter?.length > 0) params.set('end_user', enduserFilter.join(','));
|
||||
else params.delete('end_user');
|
||||
|
||||
// Single string values
|
||||
@@ -111,7 +127,6 @@ export const FilterModal: FC<Props> = ({ hideClient = true, hideEndUser = true,
|
||||
if (assignedToFilter.length > 0) params.set('users', assignedToFilter.join(','));
|
||||
else params.delete('users');
|
||||
|
||||
|
||||
// Helper to format DateRange into URL params
|
||||
const applyDateRangeToParams = (range: DateRange | undefined, prefix: string) => {
|
||||
if (range?.from) {
|
||||
@@ -152,7 +167,7 @@ export const FilterModal: FC<Props> = ({ hideClient = true, hideEndUser = true,
|
||||
|
||||
// Calculate active filter count for the badge
|
||||
const activeFilterCount = Array.from(searchParams!.keys()).filter(key =>
|
||||
['category', 'status', 'users', 'project_date_from', 'wo_date_from', 'im_date_from'].includes(key)
|
||||
['client', 'end_user', 'category', 'status', 'users', 'project_date_from', 'wo_date_from', 'im_date_from'].includes(key)
|
||||
).length;
|
||||
|
||||
return (
|
||||
@@ -189,17 +204,17 @@ export const FilterModal: FC<Props> = ({ hideClient = true, hideEndUser = true,
|
||||
placeholder='Select end user to filter'
|
||||
value={enduserFilter}
|
||||
onChange={setEnduserFilter}
|
||||
options={endUserList && endUserList.length > 0 ? endUserList.map((item: IEndUser) => ({ label: item.name, value: String(item.id) })) : []}
|
||||
options={endUserOptions}
|
||||
maxCount={1}
|
||||
/>
|
||||
</div> : null
|
||||
}
|
||||
{!hideCategory ?
|
||||
<div className='flex flex-col gap-2'>
|
||||
<Label>Assignment Category</Label>
|
||||
<Label>Assignment Type</Label>
|
||||
<Select value={category} onValueChange={setCategory}>
|
||||
<SelectTrigger className='w-full'>
|
||||
<SelectValue placeholder="Select category" />
|
||||
<SelectValue placeholder="Select type" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="project">Project</SelectItem>
|
||||
@@ -232,7 +247,7 @@ export const FilterModal: FC<Props> = ({ hideClient = true, hideEndUser = true,
|
||||
}
|
||||
{!hideStatus ?
|
||||
<div className='flex flex-col gap-2'>
|
||||
<Label>Status</Label>
|
||||
<Label>Administration Status</Label>
|
||||
<MultiSelect
|
||||
placeholder='Select status'
|
||||
value={statusFilter}
|
||||
@@ -249,7 +264,7 @@ export const FilterModal: FC<Props> = ({ hideClient = true, hideEndUser = true,
|
||||
placeholder='Select user to filter'
|
||||
value={assignedToFilter}
|
||||
onChange={setAssignedToFilter}
|
||||
options={userList && userList.length > 0 ? userList.map((item: IUser) => ({ label: item.name, value: String(item.id) })) : []}
|
||||
options={userList && userList?.user && userList?.user?.length > 0 ? userList?.user?.map((item: IUser) => ({ label: item.fullname, value: String(item.id) })) : []}
|
||||
maxCount={1}
|
||||
/>
|
||||
</div> : null
|
||||
@@ -267,4 +282,4 @@ export const FilterModal: FC<Props> = ({ hideClient = true, hideEndUser = true,
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -31,19 +31,19 @@ export default function HomeTask({ clients = [] }: HomeTaskProps) {
|
||||
trend: null,
|
||||
},
|
||||
{
|
||||
title: 'Active Projects',
|
||||
title: 'Projects',
|
||||
value: stats.activeProjects,
|
||||
icon: FolderGit2,
|
||||
trend: stats.projectsTrend,
|
||||
},
|
||||
{
|
||||
title: 'Active Internal Memos',
|
||||
title: 'Internal Memos',
|
||||
value: stats.activeInternalMemos,
|
||||
icon: ClipboardClock,
|
||||
trend: stats.personnelTrend,
|
||||
},
|
||||
{
|
||||
title: 'Active Work Orders',
|
||||
title: 'Work Orders',
|
||||
value: stats.activeWorkOrders,
|
||||
icon: FileText,
|
||||
trend: stats.workOrdersTrend,
|
||||
@@ -91,16 +91,6 @@ export default function HomeTask({ clients = [] }: HomeTaskProps) {
|
||||
<span className="text-xl md:text-3xl font-extrabold tracking-tight text-foreground">
|
||||
{card.value}
|
||||
</span>
|
||||
{card.trend && (
|
||||
<div className="flex flex-col text-[10px] leading-tight font-medium pl-0.5">
|
||||
<span className="text-emerald-600 dark:text-emerald-400 font-bold flex items-center gap-0.5 whitespace-nowrap">
|
||||
↑ {card.trend}
|
||||
</span>
|
||||
<span className="text-muted-foreground text-[9px] sm:text-[10px] whitespace-nowrap">
|
||||
vs last month
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</Card900>
|
||||
@@ -113,6 +103,7 @@ export default function HomeTask({ clients = [] }: HomeTaskProps) {
|
||||
<FilterComponent
|
||||
hideFilterModal
|
||||
showLayoutToggle={true}
|
||||
placeholder="Search client or employee..."
|
||||
/>
|
||||
|
||||
{showForm && (
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
import { motion } from 'motion/react';
|
||||
import Link from 'next/link';
|
||||
import { ExternalLink, MoreHorizontal, FileText, Users, ClipboardList } from 'lucide-react';
|
||||
import { ExternalLink, MoreHorizontal, FileText, Users, ClipboardList, PencilLine, Trash } from 'lucide-react';
|
||||
import { Card900 } from '@/components/ui/card';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { LazyImage } from '@/components/ui/lazy-image';
|
||||
@@ -122,33 +122,6 @@ export default function ClientGrid({ clients, onEdit, onDelete }: ClientGridProp
|
||||
</HoverCard>
|
||||
</div>
|
||||
|
||||
{/* Dropdown Action Menu */}
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-8 w-8 text-muted-foreground hover:text-foreground"
|
||||
aria-label="Client actions"
|
||||
>
|
||||
<MoreHorizontal className="w-4 h-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuItem asChild>
|
||||
<Link href={`/task/client-detail/${client.id}`}>View Client Detail</Link>
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onSelect={() => onEdit(client)}>
|
||||
Edit Client
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
onSelect={() => onDelete(client)}
|
||||
className="text-destructive focus:text-destructive"
|
||||
>
|
||||
Delete Client
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
|
||||
{/* Client Brand Logo & Corporate Name */}
|
||||
@@ -271,16 +244,35 @@ export default function ClientGrid({ clients, onEdit, onDelete }: ClientGridProp
|
||||
)}
|
||||
</div>
|
||||
|
||||
<Link href={`/task/client-detail/${client.id}`}>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="text-xs h-7.5 px-2.5 gap-1 hover:bg-accent"
|
||||
<div className='flex items-center gap-1.5'>
|
||||
<Link href={`/task/client-detail/${client.id}`}>
|
||||
<Button
|
||||
variant='default'
|
||||
size="sm"
|
||||
className="text-xs h-7.5 px-2.5 gap-1 hover:bg-accent"
|
||||
>
|
||||
<span>Detail</span>
|
||||
<ExternalLink className="w-3 h-3" />
|
||||
</Button>
|
||||
</Link>
|
||||
<Button onClick={() => onEdit(client)}
|
||||
title='Update Client'
|
||||
size='icon-sm'
|
||||
variant='outline'
|
||||
className='text-teal-500'
|
||||
>
|
||||
<span>Detail</span>
|
||||
<ExternalLink className="w-3 h-3" />
|
||||
<PencilLine />
|
||||
</Button>
|
||||
</Link>
|
||||
|
||||
<Button onClick={() => onDelete(client)}
|
||||
title='Delete Client'
|
||||
size='icon-sm'
|
||||
variant='outline'
|
||||
className='text-rose-500'
|
||||
>
|
||||
<Trash />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</Card900>
|
||||
</motion.div>
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
import { motion } from 'motion/react';
|
||||
import Link from 'next/link';
|
||||
import { FileText, Users, ClipboardList, MoreHorizontal, ExternalLink } from 'lucide-react';
|
||||
import { FileText, Users, ClipboardList, MoreHorizontal, ExternalLink, Trash, PencilLine } from 'lucide-react';
|
||||
import { Card900 } from '@/components/ui/card';
|
||||
import { LazyImage } from '@/components/ui/lazy-image';
|
||||
import { Button } from '@/components/ui/button';
|
||||
@@ -21,19 +21,16 @@ import { IClient, CLIENT_FALLBACK_IMAGE } from '../../types';
|
||||
import { getProjectStatusBreakdown } from '../../utils/client-overview-helpers';
|
||||
import dynamic from 'next/dynamic';
|
||||
|
||||
const ClientMilestoneTimeline = dynamic(
|
||||
() => import('./ClientMilestoneTimeline'),
|
||||
{
|
||||
ssr: false,
|
||||
loading: () => (
|
||||
<div className="h-14 sm:h-16 w-full rounded-xl bg-muted/20 border border-border/40 animate-pulse flex items-center justify-between px-4 my-1">
|
||||
<div className="h-2.5 w-16 sm:w-20 rounded bg-muted/60" />
|
||||
<div className="h-1 flex-1 mx-4 sm:mx-8 rounded-full bg-muted/40" />
|
||||
<div className="h-2.5 w-14 sm:w-16 rounded bg-muted/60" />
|
||||
</div>
|
||||
),
|
||||
}
|
||||
);
|
||||
const ClientMilestoneTimeline = dynamic(() => import('./ClientMilestoneTimeline'), {
|
||||
ssr: false,
|
||||
loading: () => (
|
||||
<div className="h-14 sm:h-16 w-full rounded-xl bg-muted/20 border border-border/40 animate-pulse flex items-center justify-between px-4 my-1">
|
||||
<div className="h-2.5 w-16 sm:w-20 rounded bg-muted/60" />
|
||||
<div className="h-1 flex-1 mx-4 sm:mx-8 rounded-full bg-muted/40" />
|
||||
<div className="h-2.5 w-14 sm:w-16 rounded bg-muted/60" />
|
||||
</div>
|
||||
),
|
||||
});
|
||||
|
||||
interface ClientListProps {
|
||||
clients: IClient[];
|
||||
@@ -240,7 +237,7 @@ export default function ClientList({ clients, onEdit, onDelete }: ClientListProp
|
||||
<div className="flex items-center justify-between text-xs py-1 border-b border-border/30">
|
||||
<div className="flex items-center gap-2 text-muted-foreground">
|
||||
<ClipboardList className="w-4 h-4 text-muted-foreground" />
|
||||
<span>Active Work Orders</span>
|
||||
<span>Work Orders</span>
|
||||
</div>
|
||||
<span className="font-bold text-foreground text-sm">{activeWorkOrders}</span>
|
||||
</div>
|
||||
@@ -250,41 +247,32 @@ export default function ClientList({ clients, onEdit, onDelete }: ClientListProp
|
||||
<div className="flex items-center justify-end gap-2 pt-2">
|
||||
<Link href={`/task/client-detail/${client.id}`} className="flex-1">
|
||||
<Button
|
||||
variant="outline"
|
||||
variant='default'
|
||||
size="sm"
|
||||
className="w-full text-xs h-8 gap-1.5 hover:bg-accent"
|
||||
className="w-full text-xs h-8 gap-1.5"
|
||||
>
|
||||
<span>View Detail</span>
|
||||
<ExternalLink className="w-3.5 h-3.5" />
|
||||
</Button>
|
||||
</Link>
|
||||
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-8 w-8 text-muted-foreground hover:text-foreground"
|
||||
aria-label="Client actions"
|
||||
>
|
||||
<MoreHorizontal className="w-4 h-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuItem asChild>
|
||||
<Link href={`/task/client-detail/${client.id}`}>View Client Detail</Link>
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onSelect={() => onEdit(client)}>
|
||||
Edit Client
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
onSelect={() => onDelete(client)}
|
||||
className="text-destructive focus:text-destructive"
|
||||
>
|
||||
Delete Client
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
<Button onClick={() => onEdit(client)}
|
||||
title='Update Client'
|
||||
size='icon-sm'
|
||||
variant='outline'
|
||||
className='text-teal-500'
|
||||
>
|
||||
<PencilLine />
|
||||
</Button>
|
||||
|
||||
<Button onClick={() => onDelete(client)}
|
||||
title='Delete Client'
|
||||
size='icon-sm'
|
||||
variant='outline'
|
||||
className='text-rose-500'
|
||||
>
|
||||
<Trash />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -150,7 +150,7 @@ export default function ClientMilestoneTimeline({ client, variant = 'list' }: Cl
|
||||
|
||||
{/* Timeline Viewport Container with group/rail for sibling hover coordination */}
|
||||
<div className={cn("w-full min-w-0", isGrid ? "" : "overflow-x-auto scrollbar-hide")}>
|
||||
<div className={cn("relative pt-3 group/rail", hasAgendas && !isGrid ? 'mb-20' : 'mb-10', isGrid ? "px-3" : "min-w-105 px-6")}>
|
||||
<div className={cn("relative pt-3 group/rail", !hasAgendas && !isGrid ? 'pb-6' : '', hasAgendas && !isGrid ? 'mb-20' : 'mb-10', isGrid ? "px-3" : "min-w-105 px-6")}>
|
||||
{/* Continuous 2-Month Horizontal Rail */}
|
||||
<div className="relative h-1.5 sm:h-2 w-full bg-zinc-200/70 dark:bg-zinc-700/50 rounded-full">
|
||||
{/* Gradient Segments connecting Hari Ini -> Agenda 1 -> Agenda 2 -> ... */}
|
||||
@@ -200,7 +200,7 @@ export default function ClientMilestoneTimeline({ client, variant = 'list' }: Cl
|
||||
{/* If no milestones in range, show gentle notice */}
|
||||
{!hasAgendas && (
|
||||
<div className="absolute inset-0 flex items-center justify-center pointer-events-none">
|
||||
<span className={`text-[10px] text-muted-foreground/70 italic ${!isGrid ? 'mt-8' : 'mt-18'} select-none whitespace-nowrap`}>
|
||||
<span className={`text-[10px] text-muted-foreground/70 italic mt-20 select-none whitespace-nowrap`}>
|
||||
No upcoming milestones in the next 2 months
|
||||
</span>
|
||||
</div>
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -6,19 +6,48 @@ export const COMPLETE_STATUS_LIST = ['BAST', 'WARRANTY', 'END OF SUPPORT']
|
||||
export const ONPROGRESS_STATUS_LIST = ['ON PROGRESS', 'ON GOING', 'HALTED', 'ISSUE', 'SIT', 'UAT', 'PTR']
|
||||
|
||||
export const getFilteredClients = (clientLists: IClient[], query?: string, sortBy?: string) => {
|
||||
let processedData = clientLists.filter((c) =>
|
||||
c.name.toLowerCase().includes(query!) ||
|
||||
c.code?.toLowerCase().includes(query!) ||
|
||||
c.description?.toLowerCase().includes(query!)
|
||||
);
|
||||
if (!clientLists || !Array.isArray(clientLists) || clientLists.length === 0) return [];
|
||||
|
||||
const q = (query || '').toLowerCase().trim();
|
||||
|
||||
let processedData = clientLists.filter((c) => {
|
||||
if (!q) return true;
|
||||
|
||||
const matchesClientName = c.name?.toLowerCase().includes(q);
|
||||
const matchesClientCode = c.code?.toLowerCase().includes(q);
|
||||
const matchesClientDesc = typeof c.description === 'string' && c.description.toLowerCase().includes(q);
|
||||
|
||||
const matchesEmployee = c.users?.some((u) =>
|
||||
u?.fullname?.toLowerCase().includes(q) ||
|
||||
u?.nickname?.toLowerCase().includes(q) ||
|
||||
u?.name?.toLowerCase().includes(q)
|
||||
);
|
||||
|
||||
return Boolean(matchesClientName || matchesClientCode || matchesClientDesc || matchesEmployee);
|
||||
});
|
||||
|
||||
// If searching by employee, prioritize matching users to the front of avatars
|
||||
if (q) {
|
||||
processedData = processedData.map((c) => {
|
||||
if (!c.users || c.users.length <= 1) return c;
|
||||
const hasMatchingUser = c.users.some((u) =>
|
||||
u?.fullname?.toLowerCase().includes(q) ||
|
||||
u?.nickname?.toLowerCase().includes(q) ||
|
||||
u?.name?.toLowerCase().includes(q)
|
||||
);
|
||||
if (!hasMatchingUser) return c;
|
||||
|
||||
const sortedUsers = [...c.users].sort((a, b) => {
|
||||
const aMatch = (a?.fullname?.toLowerCase().includes(q) || a?.nickname?.toLowerCase().includes(q) || a?.name?.toLowerCase().includes(q)) ? 1 : 0;
|
||||
const bMatch = (b?.fullname?.toLowerCase().includes(q) || b?.nickname?.toLowerCase().includes(q) || b?.name?.toLowerCase().includes(q)) ? 1 : 0;
|
||||
return bMatch - aMatch;
|
||||
});
|
||||
|
||||
return { ...c, users: sortedUsers };
|
||||
});
|
||||
}
|
||||
|
||||
processedData = processedData.sort((a, b) => {
|
||||
if (sortBy === 'active_first') {
|
||||
const aActive = (a.status_name || '').toLowerCase() === 'active' ? 1 : 0;
|
||||
const bActive = (b.status_name || '').toLowerCase() === 'active' ? 1 : 0;
|
||||
return bActive - aActive;
|
||||
}
|
||||
|
||||
if (sortBy === 'latest') {
|
||||
return new Date(b.created_at!).getTime() - new Date(a.created_at!).getTime();
|
||||
}
|
||||
@@ -39,7 +68,8 @@ export const getFilteredClients = (clientLists: IClient[], query?: string, sortB
|
||||
return aCount - bCount; // Lowest count first
|
||||
}
|
||||
|
||||
return 0; // 'default' - keeps original array order
|
||||
// 'default', 'alphabet', or fallback: sort alphabetically by client name (A-Z)
|
||||
return (a.name || '').trim().localeCompare((b.name || '').trim(), undefined, { sensitivity: 'base', numeric: true });
|
||||
});
|
||||
|
||||
return processedData;
|
||||
@@ -48,23 +78,30 @@ export const getFilteredClients = (clientLists: IClient[], query?: string, sortB
|
||||
export const getFilteredAssignments = (assignmentList: IProjectAssignment[], query?: string, sortBy?: string) => {
|
||||
if (assignmentList && assignmentList.length === 0) return []
|
||||
|
||||
// const activeStatuses = status ? status.toLowerCase()?.split(',') : [];
|
||||
const q = (query || '').toLowerCase().trim();
|
||||
|
||||
// 1. FILTERING
|
||||
let processedData = assignmentList?.filter((item) => {
|
||||
const matchesSearch = query === '' || (
|
||||
(item.client.name?.toLowerCase().includes(query!)) ||
|
||||
(item.client.code?.toLowerCase().includes(query!)) ||
|
||||
(item.end_user.name?.toLowerCase().includes(query!)) ||
|
||||
(item.end_user.code?.toLowerCase().includes(query!)) ||
|
||||
(item.im_name?.toLowerCase().includes(query)) ||
|
||||
(item.im_code?.toLowerCase().includes(query)) ||
|
||||
(item.im_description?.toLowerCase().includes(query)) ||
|
||||
(item.project?.name?.toLowerCase().includes(query!)) ||
|
||||
(item.project?.code?.toLowerCase().includes(query!)) ||
|
||||
(item.project?.description?.toLowerCase().includes(query!)) ||
|
||||
(item.wo_name?.toLowerCase().includes(query!)) ||
|
||||
(item.wo_code?.toLowerCase().includes(query!))
|
||||
if (!q) return true;
|
||||
|
||||
const matchesSearch = (
|
||||
(item.client?.name?.toLowerCase().includes(q)) ||
|
||||
(item.client?.code?.toLowerCase().includes(q)) ||
|
||||
(item.end_user?.name?.toLowerCase().includes(q)) ||
|
||||
(item.end_user?.code?.toLowerCase().includes(q)) ||
|
||||
(item.im_name?.toLowerCase().includes(q)) ||
|
||||
(item.im_code?.toLowerCase().includes(q)) ||
|
||||
(item.im_description?.toLowerCase().includes(q)) ||
|
||||
(item.project?.name?.toLowerCase().includes(q)) ||
|
||||
(item.project?.code?.toLowerCase().includes(q)) ||
|
||||
(item.project?.description?.toLowerCase().includes(q)) ||
|
||||
(item.wo_name?.toLowerCase().includes(q)) ||
|
||||
(item.wo_code?.toLowerCase().includes(q)) ||
|
||||
(item.project_assignment_work_order_detail?.some((wo) =>
|
||||
wo.user?.fullname?.toLowerCase().includes(q) ||
|
||||
wo.user?.nickname?.toLowerCase().includes(q) ||
|
||||
wo.user?.name?.toLowerCase().includes(q)
|
||||
))
|
||||
);
|
||||
|
||||
// --- Status Filter ---
|
||||
@@ -72,7 +109,7 @@ export const getFilteredAssignments = (assignmentList: IProjectAssignment[], que
|
||||
// const matchesStatus = activeStatuses.length === 0 || (itemStatus && activeStatuses.includes(itemStatus));
|
||||
|
||||
// return matchesSearch && matchesStatus;
|
||||
return matchesSearch;
|
||||
return Boolean(matchesSearch);
|
||||
});
|
||||
|
||||
// 2. SORTING
|
||||
@@ -97,8 +134,14 @@ export const getFilteredAssignments = (assignmentList: IProjectAssignment[], que
|
||||
return aCount - bCount; // Lowest count first
|
||||
}
|
||||
|
||||
if (sortBy === 'alphabet') {
|
||||
const nameA = a.project?.name || a.wo_name || a.im_name || a.client?.name || '';
|
||||
const nameB = b.project?.name || b.wo_name || b.im_name || b.client?.name || '';
|
||||
return nameA.trim().localeCompare(nameB.trim(), undefined, { sensitivity: 'base', numeric: true });
|
||||
}
|
||||
|
||||
return 0; // 'default' - keeps original array order
|
||||
});
|
||||
|
||||
return processedData;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -356,7 +356,7 @@ export default function TaskError({ error, reset }: TaskErrorProps) {
|
||||
<h3 className="text-xs font-semibold text-foreground">Technical Support</h3>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground leading-relaxed">
|
||||
If this message persists after several retries, copy the diagnostic report below and share it with the dev team.
|
||||
If this message persists after several retries, copy the diagnostic report above and share it with the dev team.
|
||||
</p>
|
||||
</div>
|
||||
</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,
|
||||
|
||||
@@ -13,6 +13,7 @@ import { Toaster } from '@/components/ui/sonner';
|
||||
import AntdConfigProvider from '@/providers/AntdConfigProvider';
|
||||
import ProgressBarProviders from '@/providers/ProgressBarProvider';
|
||||
import { TooltipProvider } from '@/components/ui/tooltip';
|
||||
import ServiceWorkerRegister from '@/components/pwa/ServiceWorkerRegister';
|
||||
|
||||
|
||||
const jakarta = Plus_Jakarta_Sans({ subsets: ['latin'] })
|
||||
@@ -25,13 +26,40 @@ export const metadata: Metadata = {
|
||||
keywords: ["react", "server components", 'rsc', 'nextjs', 'tailwind', 'typescript', 'shadcn', 'presence', 'absence', 'task', 'admin', 'cms', 'dashboard'],
|
||||
authors: [{ name: 'ichsankurnia', url: 'https://ichsankurnia-portfolio.vercel.app' }],
|
||||
creator: 'ichsankurnia',
|
||||
manifest: '/manifest.webmanifest',
|
||||
appleWebApp: {
|
||||
capable: true,
|
||||
statusBarStyle: 'default',
|
||||
title: 'H.A.T.s',
|
||||
},
|
||||
icons: {
|
||||
icon: [
|
||||
{ url: '/assets/logo192.png', sizes: '192x192', type: 'image/png' },
|
||||
{ url: '/assets/logo512.png', sizes: '512x512', type: 'image/png' },
|
||||
],
|
||||
apple: [
|
||||
{ url: '/assets/apple-touch-icon.png', sizes: '180x180', type: 'image/png' },
|
||||
],
|
||||
},
|
||||
formatDetection: {
|
||||
telephone: false,
|
||||
},
|
||||
openGraph: {
|
||||
title: "HIS Attendance Task System (H.A.T.s)",
|
||||
description: "H.A.T.s HIS Attendance Task System (smart absence, task management, work permit and leave mangement, etc).",
|
||||
images: [
|
||||
{
|
||||
url: '/assets/logo512.png',
|
||||
width: 512,
|
||||
height: 512,
|
||||
alt: 'HIS Attendance Task System (H.A.T.s)',
|
||||
},
|
||||
],
|
||||
},
|
||||
twitter: {
|
||||
title: "HIS Attendance Task System (H.A.T.s)",
|
||||
description: "H.A.T.s HIS Attendance Task System (smart absence, task management, work permit and leave mangement, etc).",
|
||||
images: ['/assets/logo512.png'],
|
||||
},
|
||||
pinterest: {
|
||||
richPin: true
|
||||
@@ -57,6 +85,8 @@ export const viewport: Viewport = {
|
||||
{ media: '(prefers-color-scheme: light)', color: '#EA512C' },
|
||||
{ media: '(prefers-color-scheme: dark)', color: '#EA512C' },
|
||||
],
|
||||
width: 'device-width',
|
||||
initialScale: 1,
|
||||
}
|
||||
|
||||
export default async function RootLayout({
|
||||
@@ -74,9 +104,11 @@ export default async function RootLayout({
|
||||
return (
|
||||
<html lang="en" suppressHydrationWarning>
|
||||
<head>
|
||||
<link rel="apple-touch-icon" href="/assets/apple-touch-icon.png" />
|
||||
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@tabler/icons-webfont@3.35.0/dist/tabler-icons.min.css" crossOrigin="anonymous" referrerPolicy="no-referrer"></link>
|
||||
</head>
|
||||
<body className={jakarta.className}>
|
||||
<ServiceWorkerRegister />
|
||||
<SessionProvider session={session} basePath={process.env.BASE_PATH}>
|
||||
|
||||
<ThemeProvider attribute="class" defaultTheme="system" enableSystem>
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
import type { MetadataRoute } from 'next';
|
||||
|
||||
export default function manifest(): MetadataRoute.Manifest {
|
||||
return {
|
||||
name: 'HIS Attendance Task System (H.A.T.s)',
|
||||
short_name: 'H.A.T.s',
|
||||
description: 'H.A.T.s HIS Attendance Task System (smart absence, task management, work permit and leave mangement, etc).',
|
||||
start_url: '/',
|
||||
id: '/',
|
||||
scope: '/',
|
||||
display: 'standalone',
|
||||
background_color: '#ffffff',
|
||||
theme_color: '#EA512C',
|
||||
orientation: 'portrait',
|
||||
icons: [
|
||||
{
|
||||
src: '/assets/logo192.png',
|
||||
sizes: '192x192',
|
||||
type: 'image/png',
|
||||
purpose: 'any',
|
||||
},
|
||||
{
|
||||
src: '/assets/hats-256x256.png',
|
||||
sizes: '256x256',
|
||||
type: 'image/png',
|
||||
purpose: 'any',
|
||||
},
|
||||
{
|
||||
src: '/assets/logo512.png',
|
||||
sizes: '512x512',
|
||||
type: 'image/png',
|
||||
purpose: 'any',
|
||||
},
|
||||
{
|
||||
src: '/assets/logo512.png',
|
||||
sizes: '512x512',
|
||||
type: 'image/png',
|
||||
purpose: 'maskable',
|
||||
},
|
||||
{
|
||||
src: '/assets/apple-touch-icon.png',
|
||||
sizes: '180x180',
|
||||
type: 'image/png',
|
||||
purpose: 'any',
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
'use client';
|
||||
|
||||
import { WifiOff, RefreshCw } from 'lucide-react';
|
||||
import Image from 'next/image';
|
||||
import { Button } from '@/components/ui/button';
|
||||
|
||||
export default function OfflinePage() {
|
||||
return (
|
||||
<div className="min-h-screen flex flex-col items-center justify-center p-6 bg-background text-foreground text-center">
|
||||
<div className="max-w-md w-full flex flex-col items-center space-y-6 rounded-2xl border border-border bg-card p-8 shadow-sm">
|
||||
<div className="relative flex h-20 w-20 items-center justify-center rounded-2xl bg-muted/60 p-3">
|
||||
<Image
|
||||
src="/assets/logo192.png"
|
||||
alt="H.A.T.s Logo"
|
||||
width={64}
|
||||
height={64}
|
||||
className="rounded-xl object-contain"
|
||||
/>
|
||||
<div className="absolute -bottom-1 -right-1 rounded-full bg-destructive/10 p-1.5 text-destructive border border-destructive/20">
|
||||
<WifiOff className="h-4 w-4" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<h1 className="text-xl font-bold tracking-tight sm:text-2xl">
|
||||
You are currently offline
|
||||
</h1>
|
||||
<p className="text-sm text-muted-foreground leading-relaxed">
|
||||
It looks like your internet connection was lost. Please check your network and try again.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<Button
|
||||
onClick={() => window.location.reload()}
|
||||
className="w-full gap-2 font-medium"
|
||||
>
|
||||
<RefreshCw className="h-4 w-4" />
|
||||
Retry Connection
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect } from 'react';
|
||||
|
||||
export default function ServiceWorkerRegister() {
|
||||
useEffect(() => {
|
||||
if (typeof window !== 'undefined' && 'serviceWorker' in navigator) {
|
||||
const registerSW = async () => {
|
||||
try {
|
||||
const registration = await navigator.serviceWorker.register('/sw.js', {
|
||||
scope: '/',
|
||||
});
|
||||
|
||||
// Listen for updates
|
||||
registration.addEventListener('updatefound', () => {
|
||||
const newWorker = registration.installing;
|
||||
if (newWorker) {
|
||||
newWorker.addEventListener('statechange', () => {
|
||||
if (newWorker.state === 'installed' && navigator.serviceWorker.controller) {
|
||||
console.log('[PWA] New content is available; please refresh.');
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('[PWA] Service Worker registration failed:', error);
|
||||
}
|
||||
};
|
||||
|
||||
if (document.readyState === 'complete') {
|
||||
registerSW();
|
||||
} else {
|
||||
window.addEventListener('load', registerSW);
|
||||
return () => window.removeEventListener('load', registerSW);
|
||||
}
|
||||
}
|
||||
}, []);
|
||||
|
||||
return null;
|
||||
}
|
||||
+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"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,7 +13,7 @@ export const config = {
|
||||
* 6. /favicon.ico, /sitemap.xml (static files)
|
||||
* 7. /auth page
|
||||
*/
|
||||
"/((?!api/|_next/|_proxy/|_static|_vercel|auth|terms|privacy-policy|not-found|avatars/|assets/|files/|admin/sourceMap/chrome/css/|admin/administration/sourceMap/chrome/css/|firebase-messaging-sw.js|favicon.ico|sitemap.xml).*)",
|
||||
"/((?!api/|_next/|_proxy/|_static|_vercel|auth|terms|privacy-policy|not-found|avatars/|assets/|files/|admin/sourceMap/chrome/css/|admin/administration/sourceMap/chrome/css/|firebase-messaging-sw.js|sw.js|manifest.json|manifest.webmanifest|offline|favicon.ico|sitemap.xml).*)",
|
||||
],
|
||||
// matcher: [
|
||||
// "/",
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 12 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 13 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 55 KiB |
@@ -0,0 +1,44 @@
|
||||
{
|
||||
"name": "HIS Attendance Task System (H.A.T.s)",
|
||||
"short_name": "H.A.T.s",
|
||||
"description": "H.A.T.s HIS Attendance Task System (smart absence, task management, work permit and leave mangement, etc).",
|
||||
"start_url": "/",
|
||||
"id": "/",
|
||||
"scope": "/",
|
||||
"display": "standalone",
|
||||
"background_color": "#ffffff",
|
||||
"theme_color": "#EA512C",
|
||||
"orientation": "portrait",
|
||||
"icons": [
|
||||
{
|
||||
"src": "/assets/logo192.png",
|
||||
"sizes": "192x192",
|
||||
"type": "image/png",
|
||||
"purpose": "any"
|
||||
},
|
||||
{
|
||||
"src": "/assets/hats-256x256.png",
|
||||
"sizes": "256x256",
|
||||
"type": "image/png",
|
||||
"purpose": "any"
|
||||
},
|
||||
{
|
||||
"src": "/assets/logo512.png",
|
||||
"sizes": "512x512",
|
||||
"type": "image/png",
|
||||
"purpose": "any"
|
||||
},
|
||||
{
|
||||
"src": "/assets/logo512.png",
|
||||
"sizes": "512x512",
|
||||
"type": "image/png",
|
||||
"purpose": "maskable"
|
||||
},
|
||||
{
|
||||
"src": "/assets/apple-touch-icon.png",
|
||||
"sizes": "180x180",
|
||||
"type": "image/png",
|
||||
"purpose": "any"
|
||||
}
|
||||
]
|
||||
}
|
||||
+138
@@ -0,0 +1,138 @@
|
||||
const CACHE_NAME = 'hats-pwa-v1';
|
||||
|
||||
const PRECACHE_ASSETS = [
|
||||
'/',
|
||||
'/offline',
|
||||
'/assets/logo192.png',
|
||||
'/assets/logo512.png',
|
||||
'/assets/apple-touch-icon.png',
|
||||
'/assets/hats-256x256.png',
|
||||
'/assets/illustrations/maintenance.svg',
|
||||
];
|
||||
|
||||
self.addEventListener('install', (event) => {
|
||||
event.waitUntil(
|
||||
caches.open(CACHE_NAME).then(async (cache) => {
|
||||
// Attempt to precache essential assets, ignoring individual failures
|
||||
for (const asset of PRECACHE_ASSETS) {
|
||||
try {
|
||||
await cache.add(asset);
|
||||
} catch (err) {
|
||||
console.warn(`[PWA SW] Precache failed for ${asset}:`, err);
|
||||
}
|
||||
}
|
||||
})
|
||||
);
|
||||
self.skipWaiting();
|
||||
});
|
||||
|
||||
self.addEventListener('activate', (event) => {
|
||||
event.waitUntil(
|
||||
caches.keys().then((keys) => {
|
||||
return Promise.all(
|
||||
keys.map((key) => {
|
||||
if (key !== CACHE_NAME) {
|
||||
return caches.delete(key);
|
||||
}
|
||||
})
|
||||
);
|
||||
})
|
||||
);
|
||||
self.clients.claim();
|
||||
});
|
||||
|
||||
self.addEventListener('fetch', (event) => {
|
||||
const { request } = event;
|
||||
const url = new URL(request.url);
|
||||
|
||||
// Only handle GET requests
|
||||
if (request.method !== 'GET') return;
|
||||
|
||||
// Do not intercept browser extensions, HMR, or internal telemetry
|
||||
if (url.protocol !== 'http:' && url.protocol !== 'https:') return;
|
||||
if (url.pathname.includes('webpack-hmr')) return;
|
||||
|
||||
// Do not cache API requests or authentication endpoints
|
||||
if (
|
||||
url.pathname.startsWith('/api/') ||
|
||||
url.hostname.includes('api') ||
|
||||
url.pathname.startsWith('/auth')
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Navigation requests (HTML pages)
|
||||
if (request.mode === 'navigate') {
|
||||
event.respondWith(
|
||||
fetch(request)
|
||||
.then((response) => {
|
||||
// Only cache successful standard responses
|
||||
if (response && response.status === 200 && response.type === 'basic') {
|
||||
const responseToCache = response.clone();
|
||||
caches.open(CACHE_NAME).then((cache) => {
|
||||
cache.put(request, responseToCache);
|
||||
});
|
||||
}
|
||||
return response;
|
||||
})
|
||||
.catch(async () => {
|
||||
const cachedResponse = await caches.match(request);
|
||||
if (cachedResponse) {
|
||||
return cachedResponse;
|
||||
}
|
||||
const offlineFallback = await caches.match('/offline');
|
||||
if (offlineFallback) {
|
||||
return offlineFallback;
|
||||
}
|
||||
return new Response(
|
||||
`<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<title>Offline - H.A.T.s</title>
|
||||
<style>
|
||||
body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; display: flex; align-items: center; justify-content: center; height: 100vh; margin: 0; background: #fafafa; color: #18181b; text-align: center; padding: 20px; }
|
||||
.card { max-width: 420px; background: white; border: 1px solid #e4e4e7; border-radius: 16px; padding: 32px 24px; box-shadow: 0 4px 12px rgba(0,0,0,0.05); }
|
||||
h1 { font-size: 20px; margin: 16px 0 8px; color: #09090b; }
|
||||
p { font-size: 14px; color: #71717a; margin-bottom: 24px; line-height: 1.5; }
|
||||
button { background: #EA512C; color: white; border: none; padding: 10px 20px; border-radius: 8px; font-weight: 500; cursor: pointer; font-size: 14px; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="card">
|
||||
<img src="/assets/logo192.png" width="64" height="64" alt="H.A.T.s" style="border-radius: 12px;" />
|
||||
<h1>You are currently offline</h1>
|
||||
<p>Please check your internet connection to continue using H.A.T.s.</p>
|
||||
<button onclick="window.location.reload()">Retry Connection</button>
|
||||
</div>
|
||||
</body>
|
||||
</html>`,
|
||||
{ headers: { 'Content-Type': 'text/html; charset=utf-8' } }
|
||||
);
|
||||
})
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
// Static assets (images, icons, fonts) - Cache First, Fallback to Network
|
||||
if (
|
||||
url.pathname.startsWith('/assets/') ||
|
||||
url.pathname.match(/\.(png|jpg|jpeg|svg|webp|gif|ico|woff|woff2|ttf|css)$/)
|
||||
) {
|
||||
event.respondWith(
|
||||
caches.match(request).then((cached) => {
|
||||
if (cached) return cached;
|
||||
return fetch(request).then((response) => {
|
||||
if (response && response.status === 200) {
|
||||
const clone = response.clone();
|
||||
caches.open(CACHE_NAME).then((cache) => {
|
||||
cache.put(request, clone);
|
||||
});
|
||||
}
|
||||
return response;
|
||||
});
|
||||
})
|
||||
);
|
||||
}
|
||||
});
|
||||
Reference in New Issue
Block a user