From 3eabe762bf9a87df065d8e8328459b1b8ef8fe39 Mon Sep 17 00:00:00 2001 From: Ichsan Kurniawan Date: Wed, 6 May 2026 18:34:38 +0700 Subject: [PATCH] Add project-assignment admin pages and UI updates Add new admin Project Assignment area with Client, End User, and Project Management pages and components (tables, Export buttons, lazy-loaded pages). Introduce FormProject for creating/editing projects and export utilities to download Excel for each module. Update task types: IEndUser now includes code and a status object. Clean up FormClient by removing unused imports and inline end-user modal usage. Make BadgeStatus robust to missing status values. Add "Project Assignment" entry to the sidebar and import FolderGit2. --- app/(dashboard)/task/component/FormClient.tsx | 13 +- app/(dashboard)/task/types.ts | 6 + .../client/component/Export.tsx | 65 +++++ .../client/component/index.tsx | 202 +++++++++++++++ app/admin/project-assignment/client/page.tsx | 38 +++ .../end-user/component/Export.tsx | 62 +++++ .../end-user/component/index.tsx | 183 ++++++++++++++ .../project-assignment/end-user/page.tsx | 38 +++ .../project-management/component/Export.tsx | 67 +++++ .../component/FormProject.tsx | 231 ++++++++++++++++++ .../project-management/component/index.tsx | 203 +++++++++++++++ .../project-management/page.tsx | 38 +++ components/ui/badge-status.tsx | 2 +- lib/data-sidebar.tsx | 23 +- 14 files changed, 1157 insertions(+), 14 deletions(-) create mode 100644 app/admin/project-assignment/client/component/Export.tsx create mode 100644 app/admin/project-assignment/client/component/index.tsx create mode 100644 app/admin/project-assignment/client/page.tsx create mode 100644 app/admin/project-assignment/end-user/component/Export.tsx create mode 100644 app/admin/project-assignment/end-user/component/index.tsx create mode 100644 app/admin/project-assignment/end-user/page.tsx create mode 100644 app/admin/project-assignment/project-management/component/Export.tsx create mode 100644 app/admin/project-assignment/project-management/component/FormProject.tsx create mode 100644 app/admin/project-assignment/project-management/component/index.tsx create mode 100644 app/admin/project-assignment/project-management/page.tsx diff --git a/app/(dashboard)/task/component/FormClient.tsx b/app/(dashboard)/task/component/FormClient.tsx index 79e46f7..fa1cb5f 100644 --- a/app/(dashboard)/task/component/FormClient.tsx +++ b/app/(dashboard)/task/component/FormClient.tsx @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useRef, useState, type FC } from 'react'; +import { useCallback, useRef, useState, type FC } from 'react'; import { AlertDialog, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from "@/components/ui/alert-dialog" @@ -9,16 +9,13 @@ import { IClient } from '../types'; import { useForm } from 'react-hook-form'; import { toast } from 'sonner'; import { Button } from '@/components/ui/button'; -import { ImageIcon, Loader2, Plus, Upload, UploadIcon } from 'lucide-react'; +import { ImageIcon, Loader2, UploadIcon } from 'lucide-react'; import { Input } from '@/components/ui/input'; import { useRouter } from 'next/navigation'; -import { useFetchWithAxios } from '@/lib/axios/useFetch'; -import { Combobox } from '@/components/ui/combobox'; import Dropzone from 'react-dropzone'; import { LazyImage } from '@/components/ui/lazy-image'; import { Label } from '@/components/ui/label'; import { serverApiCall } from '@/lib/server-api'; -import FormEndUser from './FormEndUser'; import { Textarea } from '@/components/ui/textarea'; const validationSchema = Yup.object().shape({ @@ -37,11 +34,9 @@ type Props = { }; const FormClient: FC = ({ data, onSuccess, onCancel, isRedirectToDetail }) => { - const [showEnduserForm, setShowEndUserForm] = useState(false) const [isLoading, setIsLoading] = useState(false) const [currentFile, setCurrentFile] = useState(undefined); - const { data: endUserList, mutate } = useFetchWithAxios('/end-user') const existFile = data?.photo || null const dropzoneRef = useRef(null); @@ -272,10 +267,6 @@ const FormClient: FC = ({ data, onSuccess, onCancel, isRedirectToDetail } - - {showEnduserForm ? - setShowEndUserForm(false)} onSuccess={() => { mutate(); setShowEndUserForm(false); }} /> : null - } ); } diff --git a/app/(dashboard)/task/types.ts b/app/(dashboard)/task/types.ts index 3a15b2f..9a4013f 100644 --- a/app/(dashboard)/task/types.ts +++ b/app/(dashboard)/task/types.ts @@ -2,9 +2,15 @@ import { IUser } from "@/app/admin/administration/user/component/type"; export type IEndUser = { id?: string; + code?: string name: string; description: string; photo?: string + status: { + id: number + code: string + name: string + } }; export type IClient = { diff --git a/app/admin/project-assignment/client/component/Export.tsx b/app/admin/project-assignment/client/component/Export.tsx new file mode 100644 index 0000000..5e261da --- /dev/null +++ b/app/admin/project-assignment/client/component/Export.tsx @@ -0,0 +1,65 @@ +'use client' + +import { FC, useState } from 'react'; +import { Icons } from '@/components/Icons'; +import { Button } from '@/components/ui/button'; +import { useSession } from 'next-auth/react'; +import { exportTable } from '@/lib/exportExcel'; +import dayjs from 'dayjs'; +import { IExcelJSColumnType } from '@/types/types'; +import { IUser } from '@/app/admin/administration/user/component/type'; + +type Props = { + data: IUser[] +} + +const ExportComponent: FC = ({ data }) => { + const [isLoading, setIsLoading] = useState(false) + + const { data: session } = useSession() + + const handleExport = async () => { + setIsLoading(true) + + const columns: IExcelJSColumnType[] = [ + { header: 'No', key: 'number', width: 5, style: { numFmt: '0;[Red]0' } }, + { header: 'Code', key: 'code', width: 15 }, + { header: 'Name', key: 'name', width: 25 }, + { header: 'Description', key: 'description', width: 25 }, + { header: 'Total Project', key: 'total_project', width: 10 }, + { header: 'Total WO', key: 'total_work_order', width: 10 }, + { header: 'Total User Assigned', key: 'total_user_assigned', width: 10 }, + { header: 'Status', key: 'status_name', width: 15 }, + ] + + const resBlob: any = await exportTable(session?.user.detail as IUser, data, columns, 'List of Clients') + if (resBlob) { + const url = URL.createObjectURL(resBlob); + + // Create a link and trigger a click event to start the download + const a = document.createElement("a"); + a.style.display = "none"; + a.href = url; + a.download = `Client List - Export by ${session?.user.detail.nik} - ${dayjs().format('YYYYMMDD HH:mm:ss')}`; // Set the downloaded filename + document.body.appendChild(a); + a.click(); + + // Clean up by removing the temporary link and URL + document.body.removeChild(a); + URL.revokeObjectURL(url); + } + + setIsLoading(false) + } + + return ( + + ); +} + +export default ExportComponent; \ No newline at end of file diff --git a/app/admin/project-assignment/client/component/index.tsx b/app/admin/project-assignment/client/component/index.tsx new file mode 100644 index 0000000..0a80a3e --- /dev/null +++ b/app/admin/project-assignment/client/component/index.tsx @@ -0,0 +1,202 @@ +'use client' + +import { ChangeEvent, FC, useEffect, useState } from 'react'; +import { MoreHorizontalIcon } from 'lucide-react'; +import { Table } from 'antd'; +import { TableProps, type ColumnsType } from 'antd/es/table'; +import { PlusCircledIcon } from '@radix-ui/react-icons'; +import useAxiosAuth from '@/lib/axios/useAxiosAuth'; +import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from '@/components/ui/dropdown-menu'; +import { Button } from '@/components/ui/button'; +import { AlertDialogTrigger } from '@/components/ui/alert-dialog'; +import { Input } from '@/components/ui/input'; +import { useRouter } from 'next/navigation'; +import Link from 'next/link'; +import Image from 'next/image'; +import { IClient } from '@/app/(dashboard)/task/types'; +import { LazyImage } from '@/components/ui/lazy-image'; +import BadgeStatus from '@/components/ui/badge-status'; +import FormClient from '@/app/(dashboard)/task/component/FormClient'; +import { ConfirmDeleteWithInput } from '@/components/modal/ConfirmDeleteWithInput'; + +type Props = { + data: IClient[] +}; + +const ComponentPage: FC = ({ data }) => { + const [filterData, setFilterData] = useState([]) + const [action, setAction] = useState<'CREATE' | 'EDIT' | 'DELETE' | undefined>(undefined) + const [selectedData, setSelectedData] = useState() + + const router = useRouter() + + useEffect(() => { + if (data) { + setFilterData(data) + } + }, [data]) + + + + const handleSearch = (e: ChangeEvent) => { + const text = e.target.value + if (text) { + const newData = [...data!].filter(item => ( + item.name?.toLowerCase().includes(text.toLowerCase()) || + item.code?.toLowerCase().includes(text.toLowerCase()) || + item.description?.toLowerCase().includes(text.toLowerCase()) || + item.status_name?.toLowerCase().includes(text.toLowerCase()) + )) + setFilterData(newData) + } else { + setFilterData(data) + } + } + + const handleClose = () => { + setAction(undefined) + setSelectedData(undefined) + } + + const Columns: ColumnsType = [ + { + title: 'No', + dataIndex: 'key', + render: (text, record, index) => index + 1 + }, + { + title: 'Code', + dataIndex: 'code', + sorter: (a, b) => a.code.localeCompare(b.code) + }, + { + title: 'Client Name', + dataIndex: 'name', + sorter: (a, b) => a.name.localeCompare(b.name), + render: (text, record) => ( +
+ {record.photo ? + + : + avatar + } +

{text}

+
+ ) + }, + { + title: 'Description', + dataIndex: 'description', + sorter: (a, b) => a.description.localeCompare(b.description) + }, + { + title: 'Total Project', + dataIndex: 'total_project', + align: 'right' + }, + { + title: 'Total WO', + dataIndex: 'total_work_order', + align: 'right' + }, + { + title: 'Total User Assigned', + dataIndex: 'total_user_assigned', + align: 'right' + }, + { + title: 'Status', + dataIndex: 'status_name', + filters: [ + { + text: 'ACTIVE', + value: 'A', + }, + { + text: 'INACTIVE', + value: 'N', + }, + { + text: 'DELETED', + value: 'X', + }, + ], + onFilter: (value, record) => record.status_name.indexOf(value as string) === 0, + align: 'center', + render: (text, record) => ( +
+ +
+ ) + }, + { + title: 'Action', + key: 'action', + fixed: 'right', + render: (_, record) => ( + + + + + e?.stopPropagation()}> + View Details + { setAction('EDIT'); setSelectedData(record) }}>Edit Client + { setSelectedData(record); setAction('DELETE') }} className="text-destructive" onClick={(e) => e.stopPropagation()}> + Delete Client + + + + ), + }, + ]; + + const tableProps: TableProps = { + bordered: false, + size: 'large', + showHeader: true, + pagination: { + pageSizeOptions: [5, 10, 20, 50], + defaultPageSize: 10, + showSizeChanger: true, + showQuickJumper: true, + size: 'middle' as any + }, + scroll: { x: 'max-content' }, + tableLayout: 'auto', + }; + + return ( + <> +
+
+
+ +
+ +
+ + + + {(action === 'CREATE' || action === 'EDIT') && { router.refresh(); handleClose() }} />} + + {action === 'DELETE' ? { router.refresh(); handleClose() }} + title={selectedData?.name!} description={`This action cannot be undone. This will permanently delete and remove client ${selectedData?.name} from our servers.`} + titleButton={`I understand the consequences, delete this client`} + /> : null} + + ); +} + +export default ComponentPage; \ No newline at end of file diff --git a/app/admin/project-assignment/client/page.tsx b/app/admin/project-assignment/client/page.tsx new file mode 100644 index 0000000..0307abe --- /dev/null +++ b/app/admin/project-assignment/client/page.tsx @@ -0,0 +1,38 @@ +import { type Metadata } from 'next'; +import { Suspense, lazy } from 'react'; +import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'; +import LazyLoading from '@/components/loader/LazyLoading'; +import fetchData from '@/lib/fetchData'; + +const ComponentPage = lazy(() => import('./component')); +const ExportComponent = lazy(() => import('./component/Export')); + +export const metadata: Metadata = { + title: "Client - Project Assignment | Admin", +} +export default async function ClientPage() { + const data = await fetchData('/client') + + return ( + <> +
+ + +
+ Client Management + Here's a list of clients that have been registered for project assignment! +
+ }> + + +
+ + }> + + + +
+
+ + ); +} \ No newline at end of file diff --git a/app/admin/project-assignment/end-user/component/Export.tsx b/app/admin/project-assignment/end-user/component/Export.tsx new file mode 100644 index 0000000..6e67d7e --- /dev/null +++ b/app/admin/project-assignment/end-user/component/Export.tsx @@ -0,0 +1,62 @@ +'use client' + +import { FC, useState } from 'react'; +import { Icons } from '@/components/Icons'; +import { Button } from '@/components/ui/button'; +import { useSession } from 'next-auth/react'; +import { exportTable } from '@/lib/exportExcel'; +import dayjs from 'dayjs'; +import { IExcelJSColumnType } from '@/types/types'; +import { IUser } from '@/app/admin/administration/user/component/type'; + +type Props = { + data: IUser[] +} + +const ExportComponent: FC = ({ data }) => { + const [isLoading, setIsLoading] = useState(false) + + const { data: session } = useSession() + + const handleExport = async () => { + setIsLoading(true) + + const columns: IExcelJSColumnType[] = [ + { header: 'No', key: 'number', width: 5, style: { numFmt: '0;[Red]0' } }, + { header: 'Code', key: 'code', width: 15 }, + { header: 'Name', key: 'name', width: 25 }, + { header: 'Description', key: 'description', width: 25 }, + { header: 'Status', key: 'status', value: 'status.name', width: 15 } + ] + + const resBlob: any = await exportTable(session?.user.detail as IUser, data, columns, 'List of End Users') + if (resBlob) { + const url = URL.createObjectURL(resBlob); + + // Create a link and trigger a click event to start the download + const a = document.createElement("a"); + a.style.display = "none"; + a.href = url; + a.download = `End User List - Export by ${session?.user.detail.nik} - ${dayjs().format('YYYYMMDD HH:mm:ss')}`; // Set the downloaded filename + document.body.appendChild(a); + a.click(); + + // Clean up by removing the temporary link and URL + document.body.removeChild(a); + URL.revokeObjectURL(url); + } + + setIsLoading(false) + } + + return ( + + ); +} + +export default ExportComponent; \ No newline at end of file diff --git a/app/admin/project-assignment/end-user/component/index.tsx b/app/admin/project-assignment/end-user/component/index.tsx new file mode 100644 index 0000000..de0673f --- /dev/null +++ b/app/admin/project-assignment/end-user/component/index.tsx @@ -0,0 +1,183 @@ +'use client' + +import { ChangeEvent, FC, useEffect, useState } from 'react'; +import { MoreHorizontalIcon } from 'lucide-react'; +import { Table } from 'antd'; +import { TableProps, type ColumnsType } from 'antd/es/table'; +import { PlusCircledIcon } from '@radix-ui/react-icons'; +import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from '@/components/ui/dropdown-menu'; +import { Button } from '@/components/ui/button'; +import { Input } from '@/components/ui/input'; +import { useRouter } from 'next/navigation'; +import Image from 'next/image'; +import { IEndUser } from '@/app/(dashboard)/task/types'; +import { LazyImage } from '@/components/ui/lazy-image'; +import BadgeStatus from '@/components/ui/badge-status'; +import { ConfirmDeleteWithInput } from '@/components/modal/ConfirmDeleteWithInput'; +import FormEndUser from '@/app/(dashboard)/task/component/FormEndUser'; + +type Props = { + data: IEndUser[] +}; + +const ComponentPage: FC = ({ data }) => { + const [filterData, setFilterData] = useState([]) + const [action, setAction] = useState<'CREATE' | 'EDIT' | 'DELETE' | undefined>(undefined) + const [selectedData, setSelectedData] = useState() + + const router = useRouter() + + useEffect(() => { + if (data) { + setFilterData(data) + } + }, [data]) + + + + const handleSearch = (e: ChangeEvent) => { + const text = e.target.value + if (text) { + const newData = [...data!].filter(item => ( + item.name?.toLowerCase().includes(text.toLowerCase()) || + item.code?.toLowerCase()?.includes(text.toLowerCase()) || + item.description?.toLowerCase().includes(text.toLowerCase()) || + item?.status.name.toLowerCase()?.includes(text.toLowerCase()) + )) + setFilterData(newData) + } else { + setFilterData(data) + } + } + + const handleClose = () => { + setAction(undefined) + setSelectedData(undefined) + } + + const Columns: ColumnsType = [ + { + title: 'No', + dataIndex: 'key', + render: (text, record, index) => index + 1 + }, + { + title: 'Code', + dataIndex: 'code', + sorter: (a, b) => a.code!.localeCompare(b.code!) + }, + { + title: 'End User Name', + dataIndex: 'name', + sorter: (a, b) => a.name.localeCompare(b.name), + render: (text, record) => ( +
+ {record.photo ? + + : + + } +

{text}

+
+ ) + }, + { + title: 'Description', + dataIndex: 'description', + sorter: (a, b) => a.description.localeCompare(b.description) + }, + { + title: 'Status', + dataIndex: 'status_name', + filters: [ + { + text: 'ACTIVE', + value: 'A', + }, + { + text: 'INACTIVE', + value: 'N', + }, + { + text: 'DELETED', + value: 'X', + }, + ], + onFilter: (value, record) => record.status.code?.indexOf(value as string) === 0, + align: 'center', + render: (text, record) => ( +
+ +
+ ) + }, + { + title: 'Action', + key: 'action', + fixed: 'right', + render: (_, record) => ( + + + + + e?.stopPropagation()}> + { setAction('EDIT'); setSelectedData(record) }}>Edit End User + { setSelectedData(record); setAction('DELETE') }} className="text-destructive" onClick={(e) => e.stopPropagation()}> + Delete End User + + + + ), + }, + ]; + + const tableProps: TableProps = { + bordered: false, + size: 'large', + showHeader: true, + pagination: { + pageSizeOptions: [5, 10, 20, 50], + defaultPageSize: 10, + showSizeChanger: true, + showQuickJumper: true, + size: 'middle' as any + }, + scroll: { x: 'max-content' }, + tableLayout: 'auto', + }; + + return ( + <> +
+
+
+ +
+ +
+
+ + + {(action === 'CREATE' || action === 'EDIT') && { router.refresh(); handleClose() }} />} + + {action === 'DELETE' ? { router.refresh(); handleClose() }} + title={selectedData?.name!} description={`This action cannot be undone. This will permanently delete and remove End User ${selectedData?.name} from our servers.`} + titleButton={`I understand the consequences, delete this End User`} + /> : null} + + ); +} + +export default ComponentPage; \ No newline at end of file diff --git a/app/admin/project-assignment/end-user/page.tsx b/app/admin/project-assignment/end-user/page.tsx new file mode 100644 index 0000000..e0570f4 --- /dev/null +++ b/app/admin/project-assignment/end-user/page.tsx @@ -0,0 +1,38 @@ +import { type Metadata } from 'next'; +import { Suspense, lazy } from 'react'; +import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'; +import LazyLoading from '@/components/loader/LazyLoading'; +import fetchData from '@/lib/fetchData'; + +const ComponentPage = lazy(() => import('./component')); +const ExportComponent = lazy(() => import('./component/Export')); + +export const metadata: Metadata = { + title: "End User - Project Assignment | Admin", +} +export default async function EndUserPage() { + const data = await fetchData('/end-user') + + return ( + <> +
+ + +
+ End User Management + Here's a list of end users that have been registered for project assignment! +
+ }> + + +
+ + }> + + + +
+
+ + ); +} \ No newline at end of file diff --git a/app/admin/project-assignment/project-management/component/Export.tsx b/app/admin/project-assignment/project-management/component/Export.tsx new file mode 100644 index 0000000..768abf0 --- /dev/null +++ b/app/admin/project-assignment/project-management/component/Export.tsx @@ -0,0 +1,67 @@ +'use client' + +import { FC, useState } from 'react'; +import { Icons } from '@/components/Icons'; +import { Button } from '@/components/ui/button'; +import { useSession } from 'next-auth/react'; +import { exportTable } from '@/lib/exportExcel'; +import dayjs from 'dayjs'; +import { IExcelJSColumnType } from '@/types/types'; +import { IUser } from '@/app/admin/administration/user/component/type'; + +type Props = { + data: IUser[] +} + +const ExportComponent: FC = ({ data }) => { + const [isLoading, setIsLoading] = useState(false) + + const { data: session } = useSession() + + const handleExport = async () => { + setIsLoading(true) + + const columns: IExcelJSColumnType[] = [ + { header: 'No', key: 'number', width: 5, style: { numFmt: '0;[Red]0' } }, + { header: 'Code', key: 'code', value: 'project.code', width: 15 }, + { header: 'Name', key: 'name', value: 'project.name', width: 25 }, + { header: 'Client Name', key: 'client', value: 'client.name', width: 25 }, + { header: 'End User Name', key: 'end_user', value: 'end_user.name', width: 25 }, + { header: 'Year', key: 'year', value: 'project.year', width: 25 }, + { header: 'Start Date', key: 'start_date', value: 'project.start_date', style: { numFmt: 'dd/mm/yyyy' }, width: 25 }, + { header: 'End Date', key: 'end_date', value: 'project.end_date', style: { numFmt: 'dd/mm/yyyy' }, width: 25 }, + { header: 'Description', key: 'description', value: 'project.description', width: 25 }, + { header: 'Status', key: 'status', value: 'status.name', width: 15 } + ] + + const resBlob: any = await exportTable(session?.user.detail as IUser, data, columns, 'List of Projects') + if (resBlob) { + const url = URL.createObjectURL(resBlob); + + // Create a link and trigger a click event to start the download + const a = document.createElement("a"); + a.style.display = "none"; + a.href = url; + a.download = `Project List - Export by ${session?.user.detail.nik} - ${dayjs().format('YYYYMMDD HH:mm:ss')}`; // Set the downloaded filename + document.body.appendChild(a); + a.click(); + + // Clean up by removing the temporary link and URL + document.body.removeChild(a); + URL.revokeObjectURL(url); + } + + setIsLoading(false) + } + + return ( + + ); +} + +export default ExportComponent; \ No newline at end of file diff --git a/app/admin/project-assignment/project-management/component/FormProject.tsx b/app/admin/project-assignment/project-management/component/FormProject.tsx new file mode 100644 index 0000000..7e60915 --- /dev/null +++ b/app/admin/project-assignment/project-management/component/FormProject.tsx @@ -0,0 +1,231 @@ +import { useState, type FC } from 'react'; +import { + AlertDialog, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle +} from "@/components/ui/alert-dialog" +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 { toast } from 'sonner'; +import { Button } from '@/components/ui/button'; +import { CheckCircle, Loader2 } from 'lucide-react'; +import { Input } from '@/components/ui/input'; +import { serverApiCall } from '@/lib/server-api'; +import { Textarea } from '@/components/ui/textarea'; +import { LazyImage } from '@/components/ui/lazy-image'; +import { useFetchWithAxios } from '@/lib/axios/useFetch'; +import { ComboboxCustomUI } from '@/components/ui/combobox-custom-ui'; +import { IClient, IEndUser } from '@/app/(dashboard)/task/types'; +import { DatePicker } from '@/components/ui/datepicker'; +import { IProjectAssignment } from '@/app/(dashboard)/task/type.assignment'; + +const validationSchema = Yup.object().shape({ + client_id: Yup.number().required(), + end_user_id: Yup.number().required(), + name: Yup.string().required(), + code: Yup.string().required('Project code is required'), + year: Yup.string().required('Year is required'), + 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), + description: Yup.string().optional().default(''), +}); + +type FormDataType = Yup.InferType; + +type Props = { + data?: IProjectAssignment + onCancel?: VoidFunction + onSuccess?: VoidFunction; +}; + +const FormProject: FC = ({ data, onSuccess, onCancel }) => { + const [isLoading, setIsLoading] = useState(false); + + const { data: clientList } = useFetchWithAxios('/client') + const { data: endUserList } = useFetchWithAxios('/end-user') + + const form = useForm({ + resolver: yupResolver(validationSchema), + defaultValues: { + "name": data?.project?.name || '', + client_id: data?.client.id || undefined, + end_user_id: data?.end_user.id || undefined, + code: data?.project?.code || '', + year: data?.project?.year || '', + start_date: data?.project?.start_date ? new Date(data.project.start_date) : undefined, + end_date: data?.project?.end_date ? new Date(data.project.end_date) : null, + 'description': data?.project?.description || '', + }, + }); + + const onSubmit = async (payload: FormDataType) => { + setIsLoading(true); + + let res: any + if (data) { + res = await serverApiCall('PUT', `/project/${data.id}`, payload) + } else { + res = await serverApiCall('POST', '/project', payload) + } + + setIsLoading(false) + if (res.success) { + toast.success('Project saved successfully') + onSuccess!() + } else { + toast.error(`Fail to save project`, { description: `(${res.code || '-'}) ${res.message}` }) + } + }; + + return ( + <> + + + + Project Information + + Enter the basic details of the Project. + + +
+ +
+ ( + + Project Name * + + + + + + )} + /> + ( + + Client + + 0 ? clientList.map((item: IClient) => ({ label: item.name, value: item.id, originalData: item })) : []} + value={field.value} onChange={field.onChange} placeholder='Select client' className='shrink' + + // --- CUSTOM DROPDOWN OPTIONS --- + renderOption={(option, isSelected) => { + const item = option.originalData as IClient; + return ( +
+
+ +
+ + {item.name} + + + {item.description} + +
+
+ {isSelected && } +
+ ); + }} + /> +
+ +
+ )} + /> + ( + + End User + + 0 ? endUserList.map((item: IEndUser) => ({ label: item.name, value: item.id, originalData: item })) : []} + value={field.value} onChange={field.onChange} placeholder='Select end user' className='shrink' + + // --- CUSTOM DROPDOWN OPTIONS --- + renderOption={(option, isSelected) => { + const item = option.originalData as IEndUser; + return ( +
+
+ +
+ + {item.name} + + + {item.description} + +
+
+ {isSelected && } +
+ ); + }} + /> +
+ +
+ )} + /> +
+ ( + + Code + + + + )} /> + ( + + Year + + + + )} /> +
+ +
+ ( + + Start Date + + + + )} /> + ( + + End Date + + + + )} /> +
+ + ( + + Description + +