Files
hats-app/app/(dashboard)/task/component/ManageEmployee.tsx
T
Ichsan Kurniawan 60d1af3758 update UI logic
2026-04-21 19:30:45 +07:00

175 lines
9.3 KiB
TypeScript

"use client"
import { useMemo, useState, type FC } from 'react';
import {
AlertDialog, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle
} from "@/components/ui/alert-dialog"
import { Button } from '@/components/ui/button';
import { Loader2 } from 'lucide-react';
import { useFetchWithAxios } from '@/lib/axios/useFetch';
import { IUser } from '@/app/admin/administration/user/component/type';
import { LazyImage } from '@/components/ui/lazy-image';
import { Skeleton } from '@/components/ui/skeleton';
import { IProjectAssignment } from '../type.assignment';
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage, } from "@/components/ui/form";
import * as Yup from 'yup'
import { yupResolver } from '@hookform/resolvers/yup';
import { useForm } from 'react-hook-form';
import { serverApiCall } from '@/lib/server-api';
import { toast } from 'sonner';
import { DatePicker } from '@/components/ui/datepicker';
import { MultiSelectCustomSelection } from '@/components/ui/multi-select-custom-ui';
import dayjs from 'dayjs';
type Props = {
data: IProjectAssignment
title: string
onCancel?: VoidFunction
onSuccess?: VoidFunction;
};
const validationSchema = Yup.object().shape({
start_date: Yup.date().required('Start date is required'),
end_date: Yup.date().nullable().min(Yup.ref('start_date'), 'End date cannot be before start date').default(null),
users: Yup.array().of(Yup.number().required("Each item must be a number")).min(1, 'One user must be add').required()
});
type FormDataType = Yup.InferType<typeof validationSchema>;
const ManageEmployee: FC<Props> = ({ data, title, onCancel, onSuccess }) => {
const [isLoading, setIsLoading] = useState(false)
const { data: userList, isLoading: isLoadingFetchUser } = useFetchWithAxios('/user')
const form = useForm<FormDataType>({
resolver: yupResolver(validationSchema),
defaultValues: {},
});
const onSubmit = async (payload: FormDataType) => {
setIsLoading(true);
const arrData = payload.users.map(item => (
{
"project_assignment_id": data.id,
"user_id": item,
"start_date": dayjs(payload.start_date).format('YYYY-MM-DD'),
"end_date": dayjs(payload.end_date).format('YYYY-MM-DD')
}
))
const submitPayload = {
data: arrData
}
console.log(submitPayload)
const res = await serverApiCall('POST', '/project-assignment/assign-user', submitPayload)
setIsLoading(false)
if (res.success) {
toast.success('Client saved successfully')
onSuccess!()
} else {
toast.error(`Fail to save client`, { description: `(${res.code || '-'}) ${res.message}` })
}
};
const mappedUsers = useMemo(() => {
return userList?.user?.map((item: IUser) => ({
label: item.fullname,
value: item.id,
originalData: item
})) || []
}, [data])
return (
<>
<AlertDialog open={true}>
<AlertDialogContent className='max-h-[90vh] overflow-y-auto overflow-x-hidden'>
<AlertDialogHeader>
<AlertDialogTitle>Manage Team</AlertDialogTitle>
<AlertDialogDescription>
Assign employees for <strong>{title}</strong>
</AlertDialogDescription>
</AlertDialogHeader>
<div className="grid gap-4 py-4 max-h-[400px] overflow-y-auto pr-2">
{isLoadingFetchUser ?
<div className='space-y-2'>
<Skeleton className='h-10 w-full' />
<Skeleton className='h-10 w-full' />
<Skeleton className='h-10 w-full' />
<Skeleton className='h-10 w-full' />
<Skeleton className='h-10 w-full' />
</div>
:
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)}>
<div className="grid grid-cols-1 gap-4 mb-6">
<FormField control={form.control} name='users'
render={({ field }) => (
<FormItem>
<FormLabel>Employee to Assign <span className='text-red-600 font-bold'>*</span></FormLabel>
<FormControl>
<MultiSelectCustomSelection options={mappedUsers} value={field.value} onChange={field.onChange} placeholder='Select user to assign' maxCount={3}
// --- CUSTOM DROPDOWN OPTIONS ---
renderOption={(option, isSelected) => {
const user = option.originalData as IUser;
return (
<div className="flex items-center justify-between w-full py-1">
<div className="flex items-center gap-3">
<LazyImage className='w-10 h-10 rounded-full border border-border' alt={user.fullname} src={user.avatar ? `${process.env.BASE_URL_IMG}/${user.avatar}` : '/assets/no-avatar.jpg'} />
<div className="flex flex-col">
<span className={`text-sm ${isSelected ? 'font-bold text-primary' : ''}`}>
{user.fullname}
</span>
<span className="text-xs text-muted-foreground">
{user.role.name}
</span>
</div>
</div>
{isSelected && <div className="h-4 w-4 bg-his rounded-full animate-pulse" />}
</div>
);
}}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField control={form.control} name='start_date' 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='end_date' render={({ field }) => (
<FormItem className="flex flex-col">
<FormLabel>End Date</FormLabel>
<DatePicker date={field.value as Date | undefined} setDate={field.onChange} />
<FormMessage />
</FormItem>
)} />
</div>
<AlertDialogFooter>
<AlertDialogCancel onClick={onCancel} disabled={isLoading} type='button'>Cancel</AlertDialogCancel>
<Button type="submit" disabled={isLoading}>
{isLoading && <Loader2 className='animate-spin' />}
Save Changes
</Button>
</AlertDialogFooter>
</form>
</Form>
}
</div>
</AlertDialogContent>
</AlertDialog>
</>
);
}
export default ManageEmployee;