Files
hats-app/app/(dashboard)/task/client-detail/[client_id]/project-assignments/ProjectAssignmentForm.tsx
T
Ichsan Kurniawan e7c6f1b17b Align technical status schedules and UI
This commit updates the technical status flow to support the newer `data` payload format while preserving legacy `date` handling across timelines, overview helpers, and assignment detail views. It also adds per-interval descriptions for date ranges, improves schedule editing/deletion UX, and refreshes status badge colors and default work-order/client fallback values for a more consistent experience.
2026-10-15 13:23:51 +07:00

1213 lines
90 KiB
TypeScript

"use client"
import { useState, useEffect } 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
} from 'lucide-react';
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from '@/components/ui/form';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Checkbox } from '@/components/ui/checkbox';
import {
InputGroup, InputGroupAddon, InputGroupInput, InputGroupText, InputGroupTextarea
} from '@/components/ui/input-group';
import { CardContent, CardHeader, CardTitle, CardDescription, Card900 } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Separator } from '@/components/ui/separator';
import {
Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList,
} from '@/components/ui/command';
import {
Popover, PopoverContent, PopoverTrigger,
} from '@/components/ui/popover';
import { DatePicker } from '@/components/ui/datepicker';
import { toast } from 'sonner';
import { cn } from '@/lib/utils';
import { Label } from '@/components/ui/label';
import * as yup from 'yup';
import { IClient, IEndUser, CLIENT_FALLBACK_IMAGE, END_USER_FALLBACK_IMAGE } from '../../../types';
import { serverApiCall } from '@/lib/server-api';
import dayjs from 'dayjs';
import PageLoading from '@/components/loader/PageLoading';
import { IProjectAssignment } from '../../../type.assignment';
import { useFetchWithAxios } from '@/lib/axios/useFetch';
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 FormClient from '../../../component/client/FormClient';
type IStep = 'type' | 'clients' | 'details' | 'work-orders' | 'review';
export const assignmentSchema = yup.object({
type: yup.string().oneOf(['Project', 'IM']).required('Project type is required'),
// Details Step
client_id: yup.number().required('Client is required'),
end_user_id: yup.number().required('End user is required'),
name: yup.string().required('Assignment name is required'),
code: yup.string().required('Project code is required'),
year: yup.string().required('Year is required'),
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(''),
// Work Orders Step (Conditional based on 'type')
workOrder: yup.object().when('type', {
is: 'Project',
then: (schema) => schema.shape({
name: yup.string().required('Work order name is required'),
code: yup.string().required('Work order code is required'),
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(''),
}),
otherwise: (schema) => schema.nullable().notRequired()
})
});
// Infer the TypeScript type from the Yup schema
export type AssignmentFormValues = yup.InferType<typeof assignmentSchema>;
export default function ProjectAssignmentForm(
{ client, clientId, isEdit, assignmentId, isPromote }: { client?: IClient; clientId?: string; isEdit?: boolean; assignmentId?: string; isPromote?: boolean; }
) {
const router = useRouter();
const [existAssignment, setIsExistAssignment] = useState<IProjectAssignment | null>(null);
const [step, setStep] = useState<IStep>('type');
const [loading, setIsLoading] = useState(false);
const [isFullLoading, setIsFullLoading] = useState(false);
const [isExistProject, setIsExistProject] = useState<any>(null);
const [openProjectSearch, setOpenProjectSearch] = useState(false);
const [showEndUserForm, setShowEndUserForm] = useState(false);
const [showClientForm, setShowClientForm] = useState(false);
const [selectedClient, setSelectedClient] = useState<IClient | null>(client || null);
const [selectedEndUser, setSelectedEndUser] = useState<IEndUser | null>(null);
const [isSameAsProject, setIsSameAsProject] = useState(false);
const form = useForm<AssignmentFormValues>({
resolver: yupResolver(assignmentSchema),
defaultValues: {
client_id: clientId ? Number(clientId) : undefined,
type: 'Project',
name: '',
code: '',
year: new Date().getFullYear().toString(),
description: '',
workOrder: {
name: '',
code: 'WO-01',
description: '',
}
},
mode: "onChange"
});
const assignmentType = form.watch('type');
const formValues = form.watch();
const { data: clientList, mutate: mutateClientList } = useFetchWithAxios('/client')
const { data: endUserList, mutate: mutateEndUserList } = useFetchWithAxios('/end-user')
const { data: projectList } = useFetchWithAxios(`/client/project/${formValues.client_id}`)
// Sync work order name when "Same as Project Name" is enabled
useEffect(() => {
if (isSameAsProject) {
form.setValue('workOrder.name' as any, formValues.name || '', { shouldValidate: true });
}
}, [isSameAsProject, formValues.name, form]);
const handleClearProject = () => {
form.setValue('name', '', { shouldValidate: false });
form.setValue('code', '', { shouldValidate: false });
form.setValue('year', new Date().getFullYear().toString(), { shouldValidate: false });
form.setValue('startDate', undefined as any, { shouldValidate: false });
form.setValue('endDate', undefined as any, { shouldValidate: false });
form.setValue('description', '', { shouldValidate: false });
setIsExistProject(null);
toast.warning('Project form cleared');
};
const handleClearWorkOrder = () => {
setIsSameAsProject(false);
form.setValue('workOrder.name' as any, '', { shouldValidate: false });
form.setValue('workOrder.code' as any, '', { shouldValidate: false });
form.setValue('workOrder.startDate' as any, undefined as any, { shouldValidate: false });
form.setValue('workOrder.endDate' as any, undefined as any, { shouldValidate: false });
form.setValue('workOrder.description' as any, '', { shouldValidate: false });
toast.warning('Work order form cleared');
};
// 3. Navigation & Validation Logic
const steps: { id: IStep; label: string }[] = [
{ id: 'type', label: 'Type' },
{ id: 'clients', label: 'Clients' },
{ id: 'details', label: 'Details' },
...(assignmentType === 'Project' ? [{ id: 'work-orders' as IStep, label: 'Work Orders' }] : []),
{ id: 'review', label: 'Review' },
];
const currentStepIndex = steps.findIndex(s => s.id === step);
useEffect(() => {
if (!isEdit) return;
async function getAssignmentDetail() {
setIsFullLoading(true);
const res: any = await serverApiCall('GET', `/project-assignment/${assignmentId}`);
console.log(res)
if (res.success) {
const data: IProjectAssignment = res.data.data;
form.setValue('type', isPromote ? 'Project' : data.project?.code ? 'Project' : 'IM');
form.setValue('client_id', data.client?.id);
form.setValue('end_user_id', data.end_user?.id);
setSelectedClient(data.client as any);
setSelectedEndUser(data.end_user as any);
if (!isPromote) {
form.setValue('name', data.project?.name || data.im_name || '');
form.setValue('code', data.project?.code || data.im_code || '');
form.setValue('year', String(data.project?.year || data.im_year || new Date().getFullYear()));
const sDate = data.project?.start_date || data.im_start_date;
const eDate = data.project?.end_date || data.im_end_date;
form.setValue('startDate', sDate ? new Date(sDate) : undefined as any);
form.setValue('endDate', eDate ? new Date(eDate) : undefined as any);
form.setValue('description', data.project?.description || data.im_description || '');
const defaultWoName = data.wo_name;
form.setValue('workOrder.name' as any, data.wo_name);
let initialWoCode = data.wo_code || '';
const prjCode = data.project?.code || data.im_code || '';
if (prjCode && initialWoCode.startsWith(`${prjCode}-`)) {
initialWoCode = initialWoCode.slice(prjCode.length + 1);
}
form.setValue('workOrder.code' as any, initialWoCode);
const woSDate = data.wo_start_date;
const woEDate = data.wo_end_date;
form.setValue('workOrder.startDate' as any, woSDate ? new Date(woSDate) : undefined as any);
form.setValue('workOrder.endDate' as any, woEDate ? new Date(woEDate) : undefined as any);
form.setValue('workOrder.description' as any, data.wo_description);
if (defaultWoName?.toLowerCase() === data.project?.name?.toLowerCase()) {
setIsSameAsProject(true);
}
} else {
setStep(isPromote ? 'details' : 'clients');
}
setIsExistAssignment(res.data.data);
} else {
toast.error('Fail to get detail assignment', {
description: `(${res.code || '-'}) ${res.message}`
});
}
setIsFullLoading(false);
}
getAssignmentDetail();
}, [isEdit, assignmentId, isPromote]);
const handleNext = async () => {
let isStepValid = false;
if (step === 'type') {
isStepValid = await form.trigger(['type']);
if (isStepValid) setStep('clients');
}
else if (step === 'clients') {
isStepValid = await form.trigger(['client_id', 'end_user_id']);
if (isStepValid) setStep('details');
}
else if (step === 'details') {
isStepValid = await form.trigger(['name', 'code', 'year', 'startDate', 'endDate', 'description']);
if (isStepValid) setStep(assignmentType === 'Project' ? 'work-orders' : 'review');
}
else if (step === 'work-orders') {
// Trigger the parent key to validate all nested workOrder fields
isStepValid = await form.trigger('workOrder');
if (isStepValid) setStep('review');
}
};
const handleBack = () => {
if (step === 'clients') {
if (isPromote) {
toast.info('Assignment type is locked to Project during promotion');
return;
}
setStep('type');
}
else if (step === 'details') setStep('clients');
else if (step === 'work-orders') setStep('details');
else if (step === 'review') setStep(assignmentType === 'Project' ? 'work-orders' : 'details');
};
const onSubmit = async (payload: AssignmentFormValues) => {
setIsLoading(true);
const projectCode = payload.code?.trim() || '';
const rawWoCode = ((payload.workOrder as any)?.code || '').trim();
let finalWoCode = '';
if (rawWoCode) {
finalWoCode = rawWoCode.startsWith(`${projectCode}-`)
? rawWoCode
: `${projectCode}-${rawWoCode}`;
}
const newPayload: any = {
"client_id": Number(payload.client_id),
"end_user_id": payload.end_user_id ? Number(payload.end_user_id) : null,
"im_code": assignmentType === 'IM' ? payload.code : isEdit ? existAssignment?.im_code : "",
"im_name": assignmentType === 'IM' ? payload.name : isEdit ? existAssignment?.im_name : "",
"im_year": assignmentType === 'IM' ? Number(payload.year) : isEdit ? existAssignment?.im_year : 2026,
"im_start_date": assignmentType === 'IM' ? dayjs(payload.startDate).format('YYYY-MM-DD') : isEdit ? existAssignment?.im_start_date : "",
"im_end_date": assignmentType === 'IM' ? payload.endDate ? dayjs(payload.endDate).format('YYYY-MM-DD') : "" : isEdit ? existAssignment?.im_end_date : "",
"im_description": assignmentType === 'IM' ? payload.description : isEdit ? existAssignment?.im_description : "",
"project_code": assignmentType === 'Project' ? payload.code : '',
"project_name": assignmentType === 'Project' ? payload.name : '',
"project_year": assignmentType === 'Project' ? Number(payload.year) : new Date().getFullYear(),
"project_start_date": assignmentType === 'Project' ? dayjs(payload.startDate).format('YYYY-MM-DD') : '',
"project_end_date": assignmentType === 'Project' ? payload.endDate ? dayjs(payload.endDate).format('YYYY-MM-DD') : '' : '',
"project_description": assignmentType === 'Project' ? payload.description : '',
"wo_code": assignmentType === 'Project' ? finalWoCode : '',
"wo_name": (payload.workOrder as any)?.name || '',
"wo_start_date": (payload.workOrder as any).startDate ? dayjs((payload.workOrder as any).startDate).format('YYYY-MM-DD') : '',
"wo_end_date": (payload.workOrder as any).endDate ? dayjs((payload.workOrder as any).endDate).format('YYYY-MM-DD') : '',
"wo_description": (payload.workOrder as any).description,
"wo_warranty": isEdit ? existAssignment?.wo_warranty : '',
"project_assignment_status_id": isEdit ? existAssignment?.project_assignment_status?.id : 1,
"note": isEdit ? existAssignment?.note : "",
};
if (existAssignment || isExistProject) {
newPayload['project_id'] = isExistProject?.id || existAssignment?.project?.id
}
if (isPromote && existAssignment) {
newPayload['im_id'] = existAssignment?.im_id || existAssignment?.id
}
let res: any;
if (isPromote) {
res = await serverApiCall('POST', '/project-assignment', newPayload);
} else {
if (isEdit) {
res = await serverApiCall('PUT', `/project-assignment/${assignmentId}`, newPayload);
} else {
res = await serverApiCall('POST', '/project-assignment', newPayload);
}
}
setIsLoading(false);
if (res.success) {
toast.success(isPromote ? 'Internal Memo successfully promoted to Project' : `${payload.type} saved successfully`);
if (clientId) {
router.replace(`/task/client-detail/${clientId}`);
} else {
router.replace(`/task?tab=assignments`);
}
} else {
toast.error(`Fail to save assignment`, { description: `(${res.code || '-'}) ${res.message}` });
}
};
useEffect(() => {
if (!isExistProject) return
async function getWOCode() {
const res = await serverApiCall('GET', `/project-assignment/project-sequences?project_id=${isExistProject?.id}`)
if (res.success) {
const squence = (res.data as any)?.data > 9 ? `WO-${(res.data as any)?.data}` : `WO-0${(res.data as any)?.data}`
form.setValue('workOrder.code' as any, squence)
}
else form.setValue('workOrder.code' as any, "WO-01")
}
getWOCode();
}, [isExistProject])
return (
<>
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-8">
{/* --- 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()}>
<ArrowLeft className="w-5 h-5" />
</Button>
<div>
<div className="flex items-center gap-2.5">
<h1 className="text-3xl font-bold">{isPromote ? 'Promote to Project' : isEdit ? 'Update Assignment' : 'Create Project Assignment'}</h1>
{isPromote && (
<Badge className="bg-his text-white font-medium text-xs px-2 py-0.5">
Promote Action
</Badge>
)}
</div>
<p className="text-muted-foreground">
{isPromote
? 'Convert this Internal Memo into a Project with Work Orders'
: clientId
? `For ${client?.name}`
: 'Manage the creation and modification of assignment information'}
</p>
</div>
</div>
</div>
{/* --- STEPPER --- */}
<div className="flex items-center justify-between px-2">
{steps.map((s, i) => (
<div key={s.id} className="flex items-center flex-1 last:flex-none">
<div className="flex flex-col items-center gap-2">
<div className={cn(
"w-10 h-10 rounded-full flex items-center justify-center border-2 transition-all duration-300",
i <= currentStepIndex ? "bg-zinc-900 dark:bg-zinc-100 border-primary text-secondary" : "border-border text-muted-foreground"
)}>
{i < currentStepIndex ? <Check className="w-5 h-5" /> : <span>{i + 1}</span>}
</div>
<span className={cn(
"text-xs font-medium hidden md:block",
i <= currentStepIndex ? "text-primary" : "text-muted-foreground"
)}>{s.label}</span>
</div>
{i < steps.length - 1 && (
<div className={cn(
"h-0.5 flex-1 mx-4 transition-all duration-500",
i < currentStepIndex ? "bg-primary" : "bg-border"
)} />
)}
</div>
))}
</div>
{/* --- FORM CONTENT --- */}
<AnimatePresence mode="wait">
<motion.div
key={step}
initial={{ opacity: 0, x: 20 }}
animate={{ opacity: 1, x: 0 }}
exit={{ opacity: 0, x: -20 }}
transition={{ duration: 0.3 }}
>
{/* STEP 1: TYPE */}
{step === 'type' && (
<FormField control={form.control} name="type" render={({ field }) => (
<FormItem>
<div className="grid md:grid-cols-2 gap-6">
<Card900 onClick={() => field.onChange('Project')}
className={cn("cursor-pointer transition-all hover:border-his dark:hover:border-his duration-400 relative", field.value === 'Project' && "ring-2 ring-his/10 border-his dark:ring-his/10 dark:border-his")}
>
{isPromote && (
<Badge className="absolute top-4 right-4 bg-his text-white text-[11px] font-medium">
Locked for Promotion
</Badge>
)}
<CardContent className="p-8 flex flex-col items-center text-center space-y-4">
<div className="w-16 h-16 rounded-2xl bg-orange-500/10 text-orange-500 flex items-center justify-center">
<Briefcase className="w-8 h-8" />
</div>
<div>
<h3 className="text-xl font-bold">Project</h3>
<p className="text-muted-foreground text-sm mt-2">
Standard project assignment. Requires Work Orders and detailed planning.
</p>
</div>
</CardContent>
</Card900>
<Card900 onClick={() => {
if (isPromote) {
toast.info('Cannot select Internal Memo while promoting to Project');
return;
}
field.onChange('IM');
}}
className={cn(
"cursor-pointer transition-all hover:border-his dark:hover:border-his duration-400 relative",
field.value === 'IM' && "ring-2 ring-his/10 border-his dark:ring-his/10 dark:border-his",
isPromote && "opacity-40 cursor-not-allowed hover:border-border"
)}
>
{isPromote && (
<Badge variant="outline" className="absolute top-4 right-4 text-[10px] text-muted-foreground border-border/80">
Unavailable
</Badge>
)}
<CardContent className="p-8 flex flex-col items-center text-center space-y-4">
<div className="w-16 h-16 rounded-2xl bg-purple-500/10 text-purple-500 flex items-center justify-center">
<Clock className="w-8 h-8" />
</div>
<div>
<h3 className="text-xl font-bold">Internal Memo (IM)</h3>
<p className="text-muted-foreground text-sm mt-2">
Used for Proof of Concept (PoC) stages. Can be converted to a Project later.
</p>
</div>
</CardContent>
</Card900>
</div>
<FormMessage />
</FormItem>
)}
/>
)}
{/* STEP 2: CLIENTS */}
{step === 'clients' && (
<Card900>
<CardHeader>
<CardTitle>Client Details</CardTitle>
<CardDescription>Select the client and end user information for this assignment.</CardDescription>
</CardHeader>
<CardContent className="space-y-6 mb-8">
<FormField control={form.control} name='client_id'
render={({ field }) => (
<FormItem>
<FormLabel>Client</FormLabel>
<FormControl>
<div className="flex gap-4">
<ComboboxCustomUI options={clientList && clientList.length > 0 ? clientList.map((item: IClient) => ({ label: item.name, value: item.id, originalData: item })) : []}
value={field.value} onChange={field.onChange} onSelect={(option) => setSelectedClient(option.originalData as any)} placeholder='Select client' className='shrink' disabled={clientId ? true : false}
// --- CUSTOM DROPDOWN OPTIONS ---
renderOption={(option, isSelected) => {
const item = option.originalData as IClient;
return (
<div className={`flex items-center justify-between w-full py-1 rounded-sm ${isSelected ? 'bg-zinc-800' : ''}`}>
<div className="flex items-center gap-3">
<LazyImage className='w-10 h-10 rounded-md border border-border bg-muted/30 p-1 shrink-0' alt={item.name} src={item.photo || CLIENT_FALLBACK_IMAGE} fallbackSrc={CLIENT_FALLBACK_IMAGE} imgClassName="object-contain" />
<div className="flex flex-col">
<span className={`text-sm ${isSelected ? 'font-bold text-primary' : ''}`}>
{item.name}
</span>
<span className="text-xs text-muted-foreground truncate">
{item.description}
</span>
</div>
</div>
{isSelected && <CheckCircle className="h-5 w-5 -translate-x-2" />}
</div>
);
}}
/>
{clientId ? null :
<Button type="button" variant="outline" size="icon" onClick={() => setShowClientForm(true)}>
<Plus className="w-4 h-4" />
</Button>
}
</div>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField control={form.control} name='end_user_id'
render={({ field }) => (
<FormItem>
<FormLabel>End User</FormLabel>
<FormControl>
<div className="flex gap-4">
<ComboboxCustomUI options={endUserList && endUserList.length > 0 ? endUserList.map((item: IEndUser) => ({ label: item.name, value: item.id, originalData: item })) : []}
value={field.value} onChange={field.onChange} onSelect={(option) => setSelectedEndUser(option.originalData as any)} placeholder='Select end user' className='shrink'
// --- CUSTOM DROPDOWN OPTIONS ---
renderOption={(option, isSelected) => {
const user = option.originalData as IEndUser;
return (
<div className={`flex items-center justify-between w-full py-1 rounded-sm ${isSelected ? 'bg-zinc-200/70 dark:bg-zinc-700/80' : ''}`}>
<div className="flex items-center gap-3">
<LazyImage className='w-10 h-10 rounded-md border border-border bg-muted/30 p-1 shrink-0' alt={user.name} src={user.photo || END_USER_FALLBACK_IMAGE} fallbackSrc={END_USER_FALLBACK_IMAGE} imgClassName="object-contain" />
<div className="flex flex-col">
<span className={`text-sm ${isSelected ? 'font-bold text-primary' : ''}`}>
{user.name}
</span>
<span className="text-xs text-muted-foreground truncate">
{user.description}
</span>
</div>
</div>
{isSelected && <CheckCircle className="h-5 w-5 -translate-x-2" />}
</div>
);
}}
/>
<Button type="button" variant="outline" size="icon" onClick={() => setShowEndUserForm(true)}>
<Plus className="w-4 h-4" />
</Button>
</div>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</CardContent>
</Card900>
)}
{/* STEP 3: DETAILS */}
{step === 'details' && (
<Card900>
<CardHeader className="flex flex-col sm:flex-row sm:items-center justify-between gap-3 pb-4">
<div>
<CardTitle>{assignmentType === 'IM' ? 'Internal Memo' : 'Project'} Details</CardTitle>
<CardDescription>Provide the basic information for this assignment.</CardDescription>
</div>
<Button
type="button"
variant="outline"
size="sm"
className="h-8 gap-1.5 text-xs text-muted-foreground hover:text-destructive hover:border-destructive/30 self-start sm:self-auto"
onClick={handleClearProject}
>
<RotateCcw className="w-3.5 h-3.5" /> Clear Form
</Button>
</CardHeader>
<CardContent className="space-y-6">
{/* Existing Project Selector / Linked Hero Card */}
{!isPromote && 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">
<div className="flex items-center gap-2">
<FolderGit2 className="w-4 h-4 text-primary" />
<span className="text-sm font-semibold text-foreground">Import Existing Project</span>
<Badge variant="outline" className="text-[10px] font-normal py-0 h-5 border-border/70 text-muted-foreground">
Optional
</Badge>
</div>
<p className="text-xs text-muted-foreground">
Select an existing project for {selectedClient?.name || 'this client'} to autofill information, or create a new one below.
</p>
</div>
<Popover open={openProjectSearch} onOpenChange={setOpenProjectSearch}>
<PopoverTrigger asChild>
<Button
type="button"
variant="outline"
className="w-full h-10 px-3 justify-between bg-white dark:bg-zinc-950 border-input text-xs font-normal text-muted-foreground hover:text-foreground hover:bg-muted/40 transition-colors shadow-xs"
>
<span className="flex items-center gap-2 truncate">
<Search className="w-3.5 h-3.5 text-muted-foreground shrink-0" />
<span>Select an existing project from client directory...</span>
</span>
<ChevronDown className="w-4 h-4 opacity-50 shrink-0 ml-2" />
</Button>
</PopoverTrigger>
<PopoverContent className="p-0 w-(--radix-popover-trigger-width) min-w-[320px] max-w-140" align="start">
<Command>
<CommandInput placeholder="Search existing projects by name or code..." className="h-9 text-xs" />
<CommandList className="max-h-72">
<CommandEmpty className="py-6 text-center text-xs text-muted-foreground">No existing projects found.</CommandEmpty>
<CommandGroup heading="Existing Projects">
{projectList?.map((p: IProject) => (
<CommandItem
key={p.id}
value={`${p.name} ${p.code}`}
onSelect={() => {
form.setValue('name', p.name!, { shouldValidate: true });
form.setValue('code', p.code!, { shouldValidate: true });
form.setValue('year', String(p.year), { shouldValidate: true });
form.setValue('startDate', new Date(p.start_date!), { shouldValidate: true });
form.setValue('endDate', new Date(p.end_date!), { shouldValidate: true });
form.setValue('description', p.description || '', { shouldValidate: true });
setOpenProjectSearch(false);
setIsExistProject(p);
toast.info(`Autofilled details from ${p.name}`, { duration: 1200 });
}}
className="cursor-pointer py-2.5 px-3"
>
<div className="flex items-start gap-2.5 w-full min-w-0">
<FolderGit2 className="w-4 h-4 text-primary shrink-0 mt-0.5" />
<div className="flex flex-col min-w-0 flex-1">
<span className="font-medium text-sm text-foreground leading-snug wrap-break-word">
{p.name}
</span>
<div className="flex items-center gap-2 mt-1 text-xs text-muted-foreground font-mono">
<span className="pr-1.5 py-0.2 rounded bg-muted/60 dark:bg-zinc-800">
# {p.code}
</span>
<span>•</span>
<span>Year: {p.year}</span>
</div>
</div>
</div>
</CommandItem>
))}
</CommandGroup>
</CommandList>
</Command>
</PopoverContent>
</Popover>
</div>
) : (
<div className="p-4 rounded-xl border border-primary/30 bg-primary/3 dark:bg-primary/6 space-y-3 transition-all">
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3">
<div className="flex items-center gap-2 flex-wrap">
<span className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-semibold bg-emerald-500/10 text-emerald-600 dark:text-emerald-400 border border-emerald-500/25">
<CheckCircle2 className="w-3.5 h-3.5" />
Existing Project Linked
</span>
<span className="text-xs font-mono px-2 py-0.5 rounded bg-muted/60 dark:bg-zinc-800 text-muted-foreground border border-border/60">
Code: <strong className="text-foreground"># {formValues.code}</strong>
</span>
</div>
<div className="flex items-center gap-2 self-start sm:self-auto">
<Popover open={openProjectSearch} onOpenChange={setOpenProjectSearch}>
<PopoverTrigger asChild>
<Button
type="button"
variant="outline"
size="sm"
className="h-7 px-2.5 text-xs bg-background dark:bg-zinc-950 hover:bg-muted/50"
>
Change Project
</Button>
</PopoverTrigger>
<PopoverContent className="p-0 w-(--radix-popover-trigger-width) min-w-[320px] max-w-140" align="end">
<Command>
<CommandInput placeholder="Search existing projects by name or code..." className="h-9 text-xs" />
<CommandList className="max-h-72">
<CommandEmpty className="py-6 text-center text-xs text-muted-foreground">No existing projects found.</CommandEmpty>
<CommandGroup heading="Existing Projects">
{projectList?.map((p: IProject) => (
<CommandItem
key={p.id}
value={`${p.name} ${p.code}`}
onSelect={() => {
form.setValue('name', p.name!, { shouldValidate: true });
form.setValue('code', p.code!, { shouldValidate: true });
form.setValue('year', String(p.year), { shouldValidate: true });
form.setValue('startDate', new Date(p.start_date!), { shouldValidate: true });
form.setValue('endDate', new Date(p.end_date!), { shouldValidate: true });
form.setValue('description', p.description || '', { shouldValidate: true });
setOpenProjectSearch(false);
setIsExistProject(p);
toast.info(`Switched project to ${p.name}`, { duration: 1200 });
}}
className="cursor-pointer py-2.5 px-3"
>
<div className="flex items-start gap-2.5 w-full min-w-0">
<FolderGit2 className="w-4 h-4 text-primary shrink-0 mt-0.5" />
<div className="flex flex-col min-w-0 flex-1">
<span className="font-mediums text-foreground leading-snug wrap-break-word">
{p.name}
</span>
<div className="flex items-center gap-2 mt-1 text-muted-foreground font-mono text-xs">
<span className="pr-1.5 py-0.2 rounded bg-muted/60 dark:bg-zinc-800">
# {p.code}
</span>
<span>•</span>
<span>Year: {p.year}</span>
</div>
</div>
</div>
</CommandItem>
))}
</CommandGroup>
</CommandList>
</Command>
</PopoverContent>
</Popover>
<Button
type="button"
variant="ghost"
size="sm"
className="h-7 px-2 text-xs text-destructive hover:bg-destructive"
onClick={handleClearProject}
>
<X className="w-3.5 h-3.5" /> Clear / Create New
</Button>
</div>
</div>
<div className="pt-0.5">
<h4 className="text-sm font-semibold text-foreground leading-snug wrap-break-word">
{formValues.name}
</h4>
<div className="flex flex-wrap items-center gap-x-3 gap-y-1 mt-1.5 text-xs text-muted-foreground">
<span>Year: <strong className="text-foreground font-medium">{formValues.year}</strong></span>
{formValues.startDate && (
<>
<span>•</span>
<span>
Timeline:{" "}
<strong className="text-foreground font-medium">
{dayjs(formValues.startDate).format('DD MMM YYYY')} - {formValues.endDate ? dayjs(formValues.endDate).format('DD MMM YYYY') : 'Ongoing'}
</strong>
</span>
</>
)}
</div>
</div>
<p className="text-xs text-muted-foreground border-t border-border/50 pt-2">
Fields below are locked and autofilled from this existing project. Click <strong className="text-foreground font-medium">Clear / Create New</strong> to enter new project details manually.
</p>
</div>
)
)}
<FormField
control={form.control}
name="name"
render={({ field }) => (
<FormItem>
<FormLabel>{assignmentType === 'Project' ? "Project" : "Internal Memo"} Name</FormLabel>
<FormControl>
<Input
placeholder={assignmentType === 'Project' ? "e.g Software Development Sem 1 PO 4200049718..." : "e.g Internal Memo Security Audit..."}
{...field}
disabled={isExistProject}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<div className="grid md:grid-cols-2 gap-4">
<FormField control={form.control} name="code" disabled={isExistProject} render={({ field }) => (
<FormItem>
<FormLabel>{assignmentType} Code</FormLabel>
<FormControl><Input placeholder="e.g. 24016" {...field} /></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>
<FormMessage />
</FormItem>
)} />
</div>
<div className="grid md:grid-cols-2 gap-4">
<FormField control={form.control} name="startDate" disabled={isExistProject} render={({ field }) => (
<FormItem className="flex flex-col">
<FormLabel>Start Date</FormLabel>
<DatePicker date={field.value} setDate={field.onChange} disabled={isExistProject} />
<FormMessage />
</FormItem>
)} />
<FormField control={form.control} name="endDate" disabled={isExistProject} render={({ field }) => (
<FormItem className="flex flex-col">
<FormLabel>End Date</FormLabel>
<DatePicker date={field.value as Date | undefined} setDate={field.onChange} disabled={isExistProject} />
<FormMessage />
</FormItem>
)} />
</div>
<FormField control={form.control} name="description" disabled={isExistProject} render={({ field }) => {
const charCount = field.value?.length || 0;
const maxLen = 500;
return (
<FormItem>
<FormLabel>Description (Optional)</FormLabel>
<FormControl>
<InputGroup className="flex-col h-auto">
<InputGroupTextarea
placeholder="Describe the scope..."
maxLength={maxLen}
className="min-h-24 w-full"
disabled={isExistProject}
{...field}
value={field.value || ''}
/>
<InputGroupAddon align="block-end" className="justify-start border-none py-1.5 px-3 w-full">
<InputGroupText className="text-xs font-mono text-muted-foreground">
{maxLen - charCount} characters left
</InputGroupText>
</InputGroupAddon>
</InputGroup>
</FormControl>
<FormMessage />
</FormItem>
);
}} />
</CardContent>
</Card900>
)}
{/* STEP 4: WORK ORDERS */}
{step === 'work-orders' && (
<Card900>
<CardHeader className="flex flex-col sm:flex-row sm:items-center justify-between gap-3 pb-4">
<div>
<CardTitle>Work Order Details</CardTitle>
<CardDescription>Define the initial task for this project.</CardDescription>
</div>
<Button
type="button"
variant="outline"
size="sm"
className="h-8 gap-1.5 text-xs text-muted-foreground hover:text-destructive hover:border-destructive/30 self-start sm:self-auto"
onClick={handleClearWorkOrder}
>
<RotateCcw className="w-3.5 h-3.5" /> Clear Form
</Button>
</CardHeader>
<CardContent className="space-y-6">
{/* Single column: Work Order Name */}
<FormField
control={form.control}
name={"workOrder.name" as any}
render={({ field }) => (
<FormItem className="space-y-0.5">
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-2">
<FormLabel className="text-sm font-semibold text-foreground">
WO Name
</FormLabel>
<label
htmlFor="same-as-project"
className="inline-flex items-center gap-2 text-xs font-medium cursor-pointer select-none text-muted-foreground hover:text-foreground transition-colors bg-transparent"
>
<Checkbox
id="same-as-project"
className="bg-transparent"
checked={isSameAsProject}
onCheckedChange={(checked) => {
const isChecked = !!checked;
setIsSameAsProject(isChecked);
if (isChecked) {
form.setValue('workOrder.name' as any, formValues.name || '', { shouldValidate: true });
}
}}
/>
<span>Same as Project Name</span>
</label>
</div>
<FormControl>
<Input
placeholder="e.g. Initial Site Survey"
{...field}
value={field.value || ''}
disabled={isSameAsProject}
/>
</FormControl>
{isSameAsProject && (
<p className="text-[11px] text-emerald-600 dark:text-emerald-400 flex items-center gap-1.5">
<Check className="w-3.5 h-3.5" />
Synchronized with project name
</p>
)}
<FormMessage />
</FormItem>
)}
/>
{/* Single column: Work Order Code with cohesive InputGroup */}
<FormField
control={form.control}
name={"workOrder.code" as any}
render={({ field }) => {
const projectCode = formValues.code?.trim() || 'PRJ';
return (
<FormItem className="space-y-2">
<div className="flex items-center justify-between">
<FormLabel className="text-sm font-semibold text-foreground">
WO Code
</FormLabel>
</div>
<FormControl>
<InputGroup>
<InputGroupAddon align="inline-start">
{projectCode}-
</InputGroupAddon>
<InputGroupInput
placeholder="e.g. 01, 65454, or WO-01"
{...field}
value={field.value || ''}
onChange={(e) => {
let val = e.target.value;
if (val.startsWith(`${projectCode}-`)) {
val = val.slice(projectCode.length + 1);
}
field.onChange(val);
}}
/>
</InputGroup>
</FormControl>
<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>
);
}}
/>
{/* Dates (Start and End) */}
<div className="grid gap-4 md:grid-cols-2">
<FormField control={form.control} name={"workOrder.startDate" as any} render={({ field }) => (
<FormItem className="flex flex-col">
<FormLabel>WO Start Date</FormLabel>
<DatePicker date={field.value as Date | undefined} setDate={field.onChange} />
<FormMessage />
</FormItem>
)} />
<FormField control={form.control} name={"workOrder.endDate" as any} render={({ field }) => (
<FormItem className="flex flex-col">
<FormLabel>WO End Date</FormLabel>
<DatePicker date={field.value as Date | undefined} setDate={field.onChange} />
<FormMessage />
</FormItem>
)} />
</div>
{/* Description with character counter */}
<FormField control={form.control} name={"workOrder.description" as any} render={({ field }) => {
const charCount = field.value?.length || 0;
const maxLen = 500;
return (
<FormItem>
<FormLabel>WO Description (Optional)</FormLabel>
<FormControl>
<InputGroup className="flex-col h-auto">
<InputGroupTextarea
placeholder="Briefly describe the task..."
maxLength={maxLen}
className="min-h-24 w-full"
{...field}
value={field.value || ''}
/>
<InputGroupAddon align="block-end" className="justify-start border-none py-1.5 px-3 w-full">
<InputGroupText className="text-xs font-mono text-muted-foreground">
{maxLen - charCount} characters left
</InputGroupText>
</InputGroupAddon>
</InputGroup>
</FormControl>
<FormMessage />
</FormItem>
);
}} />
</CardContent>
</Card900>
)}
{/* STEP 5: REVIEW */}
{step === 'review' && (
<div className="space-y-6">
<div className="flex flex-col gap-2">
<h2 className="text-2xl font-bold">Review Assignment</h2>
<p className="text-muted-foreground">Double check everything before saving.</p>
</div>
<div className="grid gap-6">
<Card900 className="overflow-hidden">
<div className="bg-primary/5 px-6 py-4 border-b flex justify-between items-center">
<CardTitle className="text-lg">Project Assignment Overview</CardTitle>
<Badge variant={formValues.type === 'IM' ? 'info' : 'default'} className="px-3">{formValues.type}</Badge>
</div>
<CardContent className="p-6 space-y-8">
{/* Business Relationship Section */}
<div className="grid md:grid-cols-2 gap-8">
<div className="space-y-3">
<Label className="text-[10px] text-muted-foreground uppercase tracking-widest font-bold">Client Information</Label>
<div className="flex items-center gap-4 p-4 rounded-xl border bg-card/50">
<div className="w-12 h-12 rounded-xl bg-muted/30 border border-border flex items-center justify-center overflow-hidden shrink-0 p-1">
<LazyImage src={selectedClient?.photo || CLIENT_FALLBACK_IMAGE} fallbackSrc={CLIENT_FALLBACK_IMAGE} alt={selectedClient?.name || 'Client'} className="w-full h-full bg-transparent" imgClassName="object-contain" />
</div>
<div className="min-w-0">
<p className="font-bold text-lg truncate">{selectedClient?.name}</p>
<p className="text-xs text-muted-foreground truncate">{selectedClient?.description}</p>
</div>
</div>
</div>
<div className="space-y-3">
<Label className="text-[10px] text-muted-foreground uppercase tracking-widest font-bold">End User Information</Label>
<div className="flex items-center gap-4 p-4 rounded-xl border bg-card/50">
<div className="w-12 h-12 rounded-xl bg-muted/30 border border-border flex items-center justify-center overflow-hidden shrink-0 p-1">
<LazyImage src={selectedEndUser?.photo || END_USER_FALLBACK_IMAGE} fallbackSrc={END_USER_FALLBACK_IMAGE} alt={selectedEndUser?.name || 'End User'} className="w-full h-full bg-transparent" imgClassName="object-contain" />
</div>
<div className="min-w-0">
<p className="font-bold text-lg truncate">{selectedEndUser?.name}</p>
<p className="text-xs text-muted-foreground truncate">{selectedEndUser?.description}</p>
</div>
</div>
</div>
</div>
<Separator />
{/* Assignment Details */}
<div className="grid md:grid-cols-3 gap-6">
<div className="md:col-span-2 space-y-4">
<div className="space-y-1">
<Label className="text-[10px] text-muted-foreground uppercase tracking-wider font-semibold">{formValues.type === 'IM' ? 'Internal Memo' : 'Project'} Name</Label>
<p className="text-xl font-bold">{formValues.name}</p>
</div>
<div className="space-y-1">
<Label className="text-[10px] text-muted-foreground uppercase tracking-wider font-semibold">Description</Label>
<p className="text-sm text-muted-foreground leading-relaxed">
{formValues.description || 'No description provided.'}
</p>
</div>
</div>
<div className="space-y-4 bg-muted/30 p-4 rounded-lg self-start">
<div className="grid grid-cols-2 gap-4">
<div className="space-y-1">
<Label className="text-[10px] text-muted-foreground uppercase tracking-wider">{formValues.type === 'IM' ? 'IM' : 'Project'} Year</Label>
<p className="font-mono text-sm">{formValues.year || '-'}</p>
</div>
<div className="space-y-1">
<Label className="text-[10px] text-muted-foreground uppercase tracking-wider">{formValues.type === 'IM' ? 'IM' : 'Project'} Code</Label>
<p className="font-mono text-sm">{formValues.code || '-'}</p>
</div>
<div className="space-y-1">
<Label className="text-[10px] text-muted-foreground uppercase tracking-wider">Start Date</Label>
<p className="text-sm font-medium">{formValues.startDate ? new Date(formValues.startDate).toLocaleDateString() : 'N/A'}</p>
</div>
<div className="space-y-1">
<Label className="text-[10px] text-muted-foreground uppercase tracking-wider">End Date</Label>
<p className="text-sm font-medium">{formValues.endDate ? new Date(formValues.endDate).toLocaleDateString() : 'N/A'}</p>
</div>
</div>
</div>
</div>
{formValues.type === 'Project' && (formValues.workOrder as any)?.name && (() => {
const rawWoCode = ((formValues.workOrder as any)?.code || '').trim();
const prjCode = formValues.code?.trim() || '';
const fullWoCode = rawWoCode
? (prjCode && !rawWoCode.startsWith(`${prjCode}-`) ? `${prjCode}-${rawWoCode}` : rawWoCode)
: '-';
const woStart = (formValues.workOrder as any)?.startDate
? dayjs((formValues.workOrder as any).startDate).format('DD MMM YYYY')
: null;
const woEnd = (formValues.workOrder as any)?.endDate
? dayjs((formValues.workOrder as any).endDate).format('DD MMM YYYY')
: null;
const scheduleStr = woStart && woEnd
? `${woStart} - ${woEnd}`
: woStart
? `From ${woStart}`
: 'Not specified';
return (
<div className="space-y-3 pt-2">
<div className="flex items-center gap-2">
<Briefcase className="w-4 h-4 text-primary" />
<span className="text-xs font-semibold uppercase tracking-wider text-muted-foreground">
Work Order Detail
</span>
<Separator className="flex-1" />
<Badge variant="outline" className="text-[10px] font-normal py-0 h-5 border-border/70 text-muted-foreground">
Initial Assignment
</Badge>
</div>
<div className="rounded-xl border border-border/70 bg-card/60 dark:bg-zinc-900/40 overflow-hidden divide-y divide-border/50">
{/* Top Section: Badges, Schedule & Title */}
<div className="p-4 sm:p-5 space-y-3">
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-2.5">
<div className="flex items-center gap-2 flex-wrap">
<span className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-medium bg-primary/10 text-primary border border-primary/20">
<CheckCircle2 className="w-3.5 h-3.5" />
Work Order
</span>
<span className="inline-flex items-center text-xs font-mono font-medium px-2.5 py-0.5 rounded-md bg-muted/60 dark:bg-zinc-800 text-foreground border border-border/60">
Code: <strong className="ml-1 text-primary">{fullWoCode}</strong>
</span>
</div>
<div className="inline-flex items-center gap-1.5 text-xs text-muted-foreground bg-muted/40 dark:bg-zinc-800/60 px-2.5 py-1 rounded-md border border-border/50 w-fit">
<Clock className="w-3.5 h-3.5 text-muted-foreground shrink-0" />
<span>Schedule:</span>
<span className="font-medium text-foreground">{scheduleStr}</span>
</div>
</div>
<div>
<Label className="text-[10px] text-muted-foreground uppercase tracking-wider font-semibold">
WO Name
</Label>
<h4 className="text-base sm:text-lg font-bold text-foreground leading-snug mt-0.5 wrap-break-word">
{(formValues.workOrder as any).name}
</h4>
</div>
</div>
{/* Bottom Section: Description (if available) */}
{(formValues.workOrder as any).description && (
<div className="p-4 sm:p-5 bg-muted/10 dark:bg-zinc-950/30 space-y-1">
<Label className="text-[10px] text-muted-foreground uppercase tracking-wider font-semibold">
WO Description
</Label>
<p className="text-xs sm:text-sm text-muted-foreground leading-relaxed whitespace-pre-wrap wrap-break-word">
{(formValues.workOrder as any).description}
</p>
</div>
)}
</div>
</div>
);
})()}
</CardContent>
</Card900>
</div>
<div className="flex items-center justify-center gap-2 text-sm text-muted-foreground">
<CheckCircle2 className="w-4 h-4 text-green-500" />
<span className="italic">Employees can be assigned after the assignment is created.</span>
</div>
</div>
)}
</motion.div>
</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
</Button>
<div className="flex gap-4">
{step !== 'review' ?
<Button key="next-btn" type="button" className="gap-2" onClick={handleNext}>
Next Step <ArrowRight className="w-4 h-4" />
</Button>
:
<Button key="submit-btn" type="submit" className="gap-2" disabled={loading}>
{loading ? 'Saving...' : <><Save className="w-4 h-4" /> Save Assignment</>}
</Button>
}
</div>
</div>
</form>
</Form>
{showEndUserForm ? <FormEndUser onCancel={() => setShowEndUserForm(false)} onSuccess={() => { mutateEndUserList(); setShowEndUserForm(false) }} /> : null}
{showClientForm ? <FormClient onCancel={() => setShowClientForm(false)} onSuccess={() => { mutateClientList(); setShowClientForm(false) }} /> : null}
{isFullLoading ? <PageLoading /> : null}
</>
);
}