Files
hats-app/app/(dashboard)/task/client-detail/[client_id]/project-assignments/ProjectAssignmentForm.tsx
T
2026-04-20 17:13:49 +07:00

595 lines
39 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 } 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 { Textarea } from '@/components/ui/textarea';
import { Card, 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 } from '../../../types';
import { serverApiCall } from '@/lib/server-api';
import dayjs from 'dayjs';
import PageLoading from '@/components/loader/PageLoading';
import { IProjectAssignment } from '../../../type.assignment';
type IStep = 'type' | 'details' | 'work-orders' | 'review';
export const assignmentSchema = yup.object({
type: yup.string().oneOf(['Project', 'IM']).required('Project type is required'),
// Details Step
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().nullable().min(yup.ref('startDate'), 'End date cannot be before start date').default(null),
description: yup.string().optional().nullable().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().nullable().default(null),
description: yup.string().optional().nullable().default(''),
}),
otherwise: (schema) => schema.nullable().notRequired()
})
});
// Infer the TypeScript type from the Yup schema
export type AssignmentFormValues = yup.InferType<typeof assignmentSchema>;
export default function CreateAssignmentForm({ client, clientId, projectList, isEdit, assignmentId }: { client: IClient, projectList: any[], clientId: string, isEdit?: boolean, assignmentId?: string }) {
const [existAssignment, setIsExistAssignment] = useState<IProjectAssignment | null>(null)
const router = useRouter();
const [step, setStep] = useState<IStep>('type');
const [loading, setIsLoading] = useState(false);
const [isFullLoading, setIsFullLoading] = useState(false)
const [isExistProject, setIsExistProject] = useState(false)
const [openProjectSearch, setOpenProjectSearch] = useState(false);
// 1. Initialize React Hook Form
const form = useForm<AssignmentFormValues>({
resolver: yupResolver(assignmentSchema),
defaultValues: {
type: 'Project',
name: '',
code: '',
year: new Date().getFullYear().toString(),
description: '',
workOrder: {
name: '',
code: '',
description: '',
}
},
mode: "onChange"
});
// Watch values for dynamic UI rendering
const assignmentType = form.watch('type');
const formValues = form.watch();
// 3. Navigation & Validation Logic
const steps: { id: IStep; label: string }[] = [
{ id: 'type', label: 'Type' },
{ 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}`)
setIsFullLoading(false)
if (res.success) {
const data: IProjectAssignment = res.data.data
form.setValue('type', data.project.code ? 'Project' : 'IM')
form.setValue('name', data.project.name || data.im_name)
form.setValue('code', data.project.code || data.im_code)
form.setValue('year', data.project.year || data.im_year)
form.setValue('startDate', data.project.start_date || data.im_start_date)
form.setValue('endDate', data.project.end_date || data.im_end_date)
form.setValue('description', data.project.description || data.im_description)
form.setValue('workOrder.name' as any, data.wo_name)
form.setValue('workOrder.code' as any, data.wo_code)
form.setValue('workOrder.startDate' as any, data.wo_start_date)
form.setValue('workOrder.endDate' as any, data.wo_end_date)
form.setValue('workOrder.description' as any, data.wo_description)
setStep('details')
setIsExistAssignment(res.data.data)
} else {
toast.error('Fail to get detail assignment', {
description: `(${res.code || '-'}) ${res.message}`
})
}
}
getAssignmentDetail()
}, [isEdit, assignmentId])
const handleNext = async () => {
let isStepValid = false;
if (step === 'type') {
isStepValid = await form.trigger(['type']);
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 === 'details') setStep('type');
else if (step === 'work-orders') setStep('details');
else if (step === 'review') setStep(assignmentType === 'Project' ? 'work-orders' : 'details');
};
// 4. Submission
const onSubmit = async (payload: AssignmentFormValues) => {
setIsLoading(true);
const newPayload = {
"client_id": Number(clientId),
"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) : 2026,
"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 : '',
"project_status_id": isEdit ? existAssignment?.project_status.id : 1,
"wo_code": (payload.workOrder as any).code,
"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 : '',
"note": isEdit ? existAssignment?.note : "",
}
console.log(newPayload)
let res: any
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(`${payload.type} saved successfully`);
router.replace(`/task/client-detail/${clientId}`);
} else {
toast.error(`Fail to save assignment`, { description: `(${res.code || '-'}) ${res.message}` })
}
};
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>
<h1 className="text-3xl font-bold">{isEdit ? 'Update' : 'Create Project'} Assignment</h1>
<p className="text-muted-foreground">For {client.name}</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">
<Card onClick={() => field.onChange('Project')}
className={cn("cursor-pointer transition-all hover:border-his dark:hover:border-his duration-400", field.value === 'Project' && "ring-2 ring-his/10 border-his dark:ring-his/10 dark:border-his")}
>
<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>
</Card>
<Card onClick={() => field.onChange('IM')}
className={cn("cursor-pointer transition-all hover:border-his dark:hover:border-his duration-400", field.value === 'IM' && "ring-2 ring-his/10 border-his dark:ring-his/10 dark:border-his")}
>
<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>
</Card>
</div>
<FormMessage />
</FormItem>
)}
/>
)}
{/* STEP 2: DETAILS */}
{step === 'details' && (
<Card900>
<CardHeader>
<CardTitle>{assignmentType === 'IM' ? 'Internal Memo' : 'Project'} Details</CardTitle>
<CardDescription>Provide the basic information for this assignment.</CardDescription>
</CardHeader>
<CardContent className="space-y-6">
<FormField
control={form.control}
name="name"
render={({ field }) => (
<FormItem>
<FormLabel>{assignmentType === 'Project' ? "Project" : "Internal Memo"} Name</FormLabel>
<div className="flex gap-2">
<div className="flex-1 relative">
<FormControl>
<Input placeholder="e.g Software Development Sem 1 PO 4200049718..." {...field} />
</FormControl>
{assignmentType === 'Project' && (
<div className="absolute right-2 top-1/2 -translate-y-1/2">
<Popover open={openProjectSearch} onOpenChange={setOpenProjectSearch}>
<PopoverTrigger asChild>
<Button variant="ghost" size="sm" className="h-7 px-2 text-xs">
<Search className="w-3 h-3 mr-1" /> Existing
</Button>
</PopoverTrigger>
<PopoverContent className="p-0 w-[300px]" align="end">
<Command>
<CommandInput placeholder="Search existing projects..." />
<CommandList>
<CommandEmpty>No projects found.</CommandEmpty>
<CommandGroup heading="Recent Projects">
{projectList.map(p => (
<CommandItem
key={p.id}
onSelect={() => {
form.setValue('name', p.name, { shouldValidate: true });
form.setValue('code', p.code, { shouldValidate: true });
form.setValue('year', p.year, { shouldValidate: true });
form.setValue('startDate', p.startDate, { shouldValidate: true });
form.setValue('endDate', p.endDate, { shouldValidate: true });
form.setValue('description', p.description, { shouldValidate: true });
setOpenProjectSearch(false);
setIsExistProject(true)
toast.info(`Autofilled details from ${p.name}`);
}}
>
<Check className={cn("mr-2 h-4 w-4", field.value === p.name ? "opacity-100" : "opacity-0")} />
{p.name}
</CommandItem>
))}
</CommandGroup>
</CommandList>
</Command>
</PopoverContent>
</Popover>
</div>
)}
</div>
</div>
<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} />
<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} />
<FormMessage />
</FormItem>
)} />
</div>
<FormField control={form.control} name="description" disabled={isExistProject} render={({ field }) => (
<FormItem>
<FormLabel>Description</FormLabel>
<FormControl>
<Textarea placeholder="Describe the scope..." className="min-h-[120px]" {...field} value={field.value || ''} />
</FormControl>
<FormMessage />
</FormItem>
)} />
</CardContent>
</Card900>
)}
{/* STEP 3: WORK ORDERS */}
{step === 'work-orders' && (
<div className="space-y-6">
<div>
<h2 className="text-2xl font-bold">Work Order</h2>
<p className="text-muted-foreground">Define the initial task for this project.</p>
</div>
<Card900>
<CardContent className="p-6 space-y-4">
<div className="grid gap-4 md:grid-cols-2">
<FormField control={form.control} name={"workOrder.name" as any} render={({ field }) => (
<FormItem>
<FormLabel>WO Name</FormLabel>
<FormControl><Input placeholder="e.g. Initial Site Survey" {...field} value={field.value || ''} /></FormControl>
<FormMessage />
</FormItem>
)} />
<FormField control={form.control} name={"workOrder.code" as any} render={({ field }) => (
<FormItem>
<FormLabel>WO Code</FormLabel>
<FormControl><Input placeholder="e.g. WO-24016" {...field} value={field.value || ''} /></FormControl>
<FormMessage />
</FormItem>
)} />
</div>
<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>
<FormField control={form.control} name={"workOrder.description" as any} render={({ field }) => (
<FormItem>
<FormLabel>WO Description</FormLabel>
<FormControl><Textarea placeholder="Briefly describe the task.." className="min-h-[120px]" {...field} value={field.value || ''} /></FormControl>
<FormMessage />
</FormItem>
)} />
</CardContent>
</Card900>
</div>
)}
{/* STEP 4: REVIEW */}
{step === 'review' && (
<div className="space-y-6">
<div>
<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>
<CardHeader>
<CardTitle>Overview</CardTitle>
</CardHeader>
<CardContent className="space-y-6">
<div className="grid grid-cols-2 gap-4">
<div>
<Label className="text-xs text-muted-foreground uppercase">Type</Label>
<div className="mt-1">
<Badge variant={formValues.type === 'Project' ? 'default' : 'info'}>{formValues.type}</Badge>
</div>
</div>
<div>
<Label className="text-xs text-muted-foreground uppercase">Client</Label>
<p className="font-medium mt-1">{client?.name}</p>
</div>
</div>
<div>
<Label className="text-xs text-muted-foreground uppercase">Name</Label>
<p className="text-xl font-bold mt-1">{formValues.name || 'Untitled Assignment'}</p>
</div>
<div className="grid grid-cols-2 gap-4">
<div>
<Label className="text-xs text-muted-foreground uppercase">Code</Label>
<p className="font-medium mt-1">{formValues.code || 'N/A'}</p>
</div>
<div>
<Label className="text-xs text-muted-foreground uppercase">Year</Label>
<p className="font-medium mt-1">{formValues.year || 'N/A'}</p>
</div>
<div>
<Label className="text-xs text-muted-foreground uppercase">Start Date</Label>
<p className="font-medium mt-1">{formValues.startDate ? dayjs(formValues.startDate).format('MMMM DD, YYYY') : 'N/A'}</p>
</div>
<div>
<Label className="text-xs text-muted-foreground uppercase">End Date</Label>
<p className="font-medium mt-1">{formValues.endDate ? dayjs(formValues.endDate).format('MMMM DD, YYYY') : 'N/A'}</p>
</div>
</div>
<div>
<Label className="text-xs text-muted-foreground uppercase">Description</Label>
<p className="text-muted-foreground mt-1">{formValues.description || 'No description provided.'}</p>
</div>
{formValues.type === 'Project' && (formValues.workOrder as any)?.name && (
<>
<Separator />
<div>
<Label className="text-xs text-muted-foreground uppercase mb-3 block">Work Order</Label>
<div className="flex flex-col gap-5 p-5 bg-accent/30 rounded-md text-xs">
<div>
<Label className="text-xs text-muted-foreground uppercase">Name</Label>
<p className="text-sm font-bold mt-1">{(formValues.workOrder as any).name || 'Untitled Work Order'} ({(formValues.workOrder as any).code})</p>
</div>
<div className="grid grid-cols-2 gap-4">
<div>
<Label className="text-xs text-muted-foreground uppercase mb-0.5">Start Date</Label>
<p>{(formValues.workOrder as any).startDate ? dayjs((formValues.workOrder as any).startDate).format('MMMM DD, YYYY') : 'N/A'}</p>
</div>
<div>
<Label className="text-xs text-muted-foreground uppercase mb-0.5">End Date</Label>
<p>{(formValues.workOrder as any).endDate ? dayjs((formValues.workOrder as any).endDate).format('MMMM DD, YYYY') : 'N/A'}</p>
</div>
</div>
<div>
<Label className="text-xs text-muted-foreground uppercase mb-0.5">Description</Label>
<p className="text-muted-foreground">{(formValues.workOrder as any).description || 'No description provided.'}</p>
</div>
</div>
</div>
</>
)}
</CardContent>
</Card900>
</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>
{/* <Button type="button" className="gap-2" onClick={handleNext}>
Next Step <ArrowRight className="w-4 h-4" />
</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>
{isFullLoading ? <PageLoading /> : null}
</>
);
}