From 2d0f2fa1f0538517d4e05605b362e6a40cc7c8e3 Mon Sep 17 00:00:00 2001 From: Ichsan Kurniawan Date: Mon, 20 Apr 2026 17:13:49 +0700 Subject: [PATCH] fixing ui, logic etc.. --- .../(main)/ClientDetailComponent.tsx | 110 +++++++------ .../client-detail/[client_id]/(main)/page.tsx | 67 +++++++- .../ProjectAssignmentForm.tsx | 6 +- .../project-detail/[project_id]/page.tsx | 92 +++++++++-- .../task/component/AssignmentTable.tsx | 120 +++++++++------ app/(dashboard)/task/component/ClientGrid.tsx | 7 +- .../task/component/FilterComponent.tsx | 104 +++++++++++++ .../task/component/ManageEmployee.tsx | 145 ++++++++++++++---- app/(dashboard)/task/page.tsx | 25 ++- 9 files changed, 517 insertions(+), 159 deletions(-) create mode 100644 app/(dashboard)/task/component/FilterComponent.tsx diff --git a/app/(dashboard)/task/client-detail/[client_id]/(main)/ClientDetailComponent.tsx b/app/(dashboard)/task/client-detail/[client_id]/(main)/ClientDetailComponent.tsx index 825163e..a4e6f9f 100644 --- a/app/(dashboard)/task/client-detail/[client_id]/(main)/ClientDetailComponent.tsx +++ b/app/(dashboard)/task/client-detail/[client_id]/(main)/ClientDetailComponent.tsx @@ -3,7 +3,7 @@ import { useState } from 'react'; import { motion } from 'motion/react'; -import { Briefcase, Clock, Users, MoreVertical, Check, Calendar as CalendarIcon, LayoutGrid, Table as TableIcon, ExternalLink } from 'lucide-react'; +import { Briefcase, Clock, Users, MoreVertical, Calendar as CalendarIcon, LayoutGrid, Table as TableIcon, ExternalLink } from 'lucide-react'; import { Button } from '@/components/ui/button'; import { Card, Card900, CardContent } from '@/components/ui/card'; import { Badge } from '@/components/ui/badge'; @@ -19,6 +19,8 @@ import ManageEmployee from '../../../component/ManageEmployee'; import { useRouter } from 'next/navigation'; import FormUpdateStatus from '../../../component/FormUpdateStatus'; import BadgeStatus from '@/components/ui/badge-status'; +import FilterComponent from '../../../component/FilterComponent'; +import { ConfirmDeleteWithInput } from '@/components/modal/ConfirmDeleteWithInput'; interface Props { clientId: string; @@ -27,7 +29,7 @@ interface Props { export default function ClientDetailComponent({ clientId, initialAssignments }: Props) { const [viewMode, setViewMode] = useState<'grid' | 'table'>('grid'); - const [action, setAction] = useState<'MANAGE_EMPLOYEE' | 'UPDATE_STATUS' | undefined>() + const [action, setAction] = useState<'MANAGE_EMPLOYEE' | 'UPDATE_STATUS' | 'DELETE' | undefined>() const [selectedData, setSelectedData] = useState() const router = useRouter() @@ -60,6 +62,9 @@ export default function ClientDetailComponent({ clientId, initialAssignments }: + + + {/* --- EMPTY STATE --- */} {initialAssignments.length === 0 ? @@ -83,19 +88,19 @@ export default function ClientDetailComponent({ clientId, initialAssignments }: /* --- GRID VIEW --- */
{initialAssignments.map((assignment) => { - const isProject = assignment.project.code + const isProject = assignment.project?.code const assignmentType = isProject ? 'Project' : 'IM' - const assignmentName = assignment.project.name || assignment.im_name - const assignmentStartDate = assignment.project.start_date || assignment.im_start_date - const assignmentEndDate = assignment.project.end_date || assignment.im_end_date - const assignmentDesc = assignment.project.description || assignment.im_description - const assignmentStatus = assignment.project.status || assignment.project_status.name + const assignmentName = assignment.project?.name || assignment.im_name + const assignmentStartDate = assignment.project?.start_date || assignment.im_start_date + const assignmentEndDate = assignment.project?.end_date || assignment.im_end_date + const assignmentDesc = assignment.project?.description || assignment.im_description + const assignmentStatus = assignment.project?.status || assignment.project_status.name return ( - +
@@ -104,11 +109,11 @@ export default function ClientDetailComponent({ clientId, initialAssignments }:
{isProject ? - e.stopPropagation()}> -
-
-

{assignmentName}

-
@@ -117,18 +122,18 @@ export default function ClientDetailComponent({ clientId, initialAssignments }:
: -
+

{assignmentName}

{assignmentType}
} - {assignment.wo_code && ( + {assignment.wo_name &&

WO: {assignment.wo_name}

- )} + }

{assignmentDesc} @@ -184,15 +189,17 @@ export default function ClientDetailComponent({ clientId, initialAssignments }: View Assignment Details - - View Project Details - + {isProject ? + + View Project Details + : null + } Edit Assignment - { setSelectedData(assignment); setAction('MANAGE_EMPLOYEE') }}>Manage Employees - { setSelectedData(assignment); setAction('UPDATE_STATUS') }}>Update Assignment Status - Delete + e.stopPropagation()} onSelect={() => { setSelectedData(assignment); setAction('MANAGE_EMPLOYEE') }}>Manage Employees + e.stopPropagation()} onSelect={() => { setSelectedData(assignment); setAction('UPDATE_STATUS') }}>Update Assignment Status + e.stopPropagation()} onSelect={() => { setSelectedData(assignment); setAction('DELETE') }} className="text-destructive">Delete

@@ -236,39 +243,43 @@ export default function ClientDetailComponent({ clientId, initialAssignments }: return ( {assignment.im_name} - {assignment.im_code || '-'} + {assignment.im_code || ''} {assignment.im_description} - {assignment.im_year || '-'} + {assignment.im_year || ''} - {assignment.im_start_date ? new Date(assignment.im_start_date).toLocaleDateString() : '-'} + {assignment.im_start_date ? new Date(assignment.im_start_date).toLocaleDateString() : ''} - {assignment.im_end_date ? new Date(assignment.im_end_date).toLocaleDateString() : '-'} + {assignment.im_end_date ? new Date(assignment.im_end_date).toLocaleDateString() : ''} - {assignment.project.name} - {assignment.project.code || '-'} - - {assignment.project.description} + + + {assignment.project?.name} + - {assignment.project.year || '-'} + {assignment.project?.code || ''} + + {assignment.project?.description} + + {assignment.project?.year || ''} - {assignment.project.start_date ? new Date(assignment.project.start_date).toLocaleDateString() : '-'} + {assignment.project?.start_date ? new Date(assignment.project?.start_date).toLocaleDateString() : ''} - {assignment.project.end_date ? new Date(assignment.project.end_date).toLocaleDateString() : '-'} + {assignment.project?.end_date ? new Date(assignment.project?.end_date).toLocaleDateString() : ''} - {assignment.wo_name || '-'} - {assignment.wo_code || '-'} + {assignment.wo_name || ''} + {assignment.wo_code || ''} - {assignment.wo_start_date ? new Date(assignment.wo_start_date).toLocaleDateString() : '-'} + {assignment.wo_start_date ? new Date(assignment.wo_start_date).toLocaleDateString() : ''} - {assignment.wo_end_date ? new Date(assignment.wo_end_date).toLocaleDateString() : '-'} + {assignment.wo_end_date ? new Date(assignment.wo_end_date).toLocaleDateString() : ''} - + @@ -281,15 +292,19 @@ export default function ClientDetailComponent({ clientId, initialAssignments }: View Assignment Details - - View Project Details - + {assignment.project?.code ? + + View Project Details + + : + null + } Edit Assignment - { setSelectedData(assignment); setAction('MANAGE_EMPLOYEE') }}>Add Team - { setSelectedData(assignment); setAction('UPDATE_STATUS') }}>Update Status - Delete + e.stopPropagation()} onSelect={() => { setSelectedData(assignment); setAction('MANAGE_EMPLOYEE') }}>Add Team + e.stopPropagation()} onSelect={() => { setSelectedData(assignment); setAction('UPDATE_STATUS') }}>Update Status + e.stopPropagation()} onSelect={() => { setSelectedData(assignment); setAction('DELETE') }} className="text-destructive">Delete @@ -311,6 +326,11 @@ export default function ClientDetailComponent({ clientId, initialAssignments }: : null } + + {action === 'DELETE' ? { router.refresh(); handleClose() }} + title={selectedData?.project.name || selectedData?.im_name!} description={`This action cannot be undone. This will permanently delete and remove project assignment ${selectedData?.project.name || selectedData?.im_name!} from our servers.`} + titleButton={`I understand the consequences, delete this assignment`} + /> : null} ); } \ No newline at end of file diff --git a/app/(dashboard)/task/client-detail/[client_id]/(main)/page.tsx b/app/(dashboard)/task/client-detail/[client_id]/(main)/page.tsx index 10885e5..b69f092 100644 --- a/app/(dashboard)/task/client-detail/[client_id]/(main)/page.tsx +++ b/app/(dashboard)/task/client-detail/[client_id]/(main)/page.tsx @@ -8,13 +8,23 @@ import Link from 'next/link'; import ClientDetailComponent from './ClientDetailComponent'; import fetchData from '@/lib/fetchData'; import { LazyImage } from '@/components/ui/lazy-image'; +import { IProjectAssignment } from '../../../type.assignment'; type Props = { params: Promise<{ client_id: string }> + searchParams: Promise<{ [key: string]: string | undefined }> }; -export default async function ClientDetailPage({ params }: Props) { +export default async function ClientDetailPage({ params, searchParams }: Props) { const { client_id } = await params; + const q = (await searchParams)!.q + const status = (await searchParams)!.status + const sort = (await searchParams)!.sort + + const query = (q || '').toLowerCase() + const activeStatuses = status ? status.toLowerCase()?.split(',') : []; + const sortBy = sort || 'default'; + const getClientById = fetchData(`/client/${client_id}`) // const getAssignmentsByClient = fetchData(`/client/project-assignment/${client_id}`) @@ -33,6 +43,55 @@ export default async function ClientDetailPage({ params }: Props) { ); } + console.log(assignmentList) + const filterData = () => { + if (assignmentList && assignmentList.length === 0) return [] + // 1. FILTERING + let processedData = assignmentList.filter((item: IProjectAssignment) => { + const matchesSearch = query === '' || ( + (item.im_name?.toLowerCase().includes(query)) || + (item.im_code?.toLowerCase().includes(query)) || + (item.project?.name?.toLowerCase().includes(query)) || + (item.project?.code?.toLowerCase().includes(query)) || + (item.wo_name?.toLowerCase().includes(query)) || + (item.wo_code?.toLowerCase().includes(query)) + ); + + // --- Status Filter --- + const itemStatus = item.project_status?.name?.toLowerCase(); + const matchesStatus = activeStatuses.length === 0 || (itemStatus && activeStatuses.includes(itemStatus)); + + return matchesSearch && matchesStatus; + }); + + // 2. SORTING + processedData = processedData.sort((a: IProjectAssignment, b: IProjectAssignment) => { + if (sortBy === 'latest') { + return new Date(b.created_at).getTime() - new Date(a.created_at).getTime(); + } + + if (sortBy === 'oldest') { + return new Date(a.created_at).getTime() - new Date(b.created_at).getTime(); + } + + if (sortBy === 'participants_desc') { + const aCount = a.project_assignment_work_order_detail?.length || 0; + const bCount = b.project_assignment_work_order_detail?.length || 0; + return bCount - aCount; // Highest count first + } + + if (sortBy === 'participants_asc') { + const aCount = a.project_assignment_work_order_detail?.length || 0; + const bCount = b.project_assignment_work_order_detail?.length || 0; + return aCount - bCount; // Lowest count first + } + + return 0; // 'default' - keeps original array order + }); + + return processedData; + } + return (
@@ -46,8 +105,8 @@ export default async function ClientDetailPage({ params }: Props) { Back to Clients -

{client.name}

-

End User: {client.end_user_name}

+

{client.name}

+

End User: {client.end_user_name}

@@ -66,7 +125,7 @@ export default async function ClientDetailPage({ params }: Props) { {/* Pass the server-fetched data as props */}
diff --git a/app/(dashboard)/task/client-detail/[client_id]/project-assignments/ProjectAssignmentForm.tsx b/app/(dashboard)/task/client-detail/[client_id]/project-assignments/ProjectAssignmentForm.tsx index 2d8f2b3..ddd865e 100644 --- a/app/(dashboard)/task/client-detail/[client_id]/project-assignments/ProjectAssignmentForm.tsx +++ b/app/(dashboard)/task/client-detail/[client_id]/project-assignments/ProjectAssignmentForm.tsx @@ -170,7 +170,7 @@ export default function CreateAssignmentForm({ client, clientId, projectList, is setIsLoading(true); const newPayload = { - "client_id": clientId, + "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, @@ -189,13 +189,15 @@ export default function CreateAssignmentForm({ client, clientId, projectList, is "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 ? (payload.workOrder as any).endDate ? dayjs((payload.workOrder as any).endDate).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) diff --git a/app/(dashboard)/task/client-detail/[client_id]/project-detail/[project_id]/page.tsx b/app/(dashboard)/task/client-detail/[client_id]/project-detail/[project_id]/page.tsx index bbe48fa..d1cb1e3 100644 --- a/app/(dashboard)/task/client-detail/[client_id]/project-detail/[project_id]/page.tsx +++ b/app/(dashboard)/task/client-detail/[client_id]/project-detail/[project_id]/page.tsx @@ -1,22 +1,29 @@ import { Button } from '@/components/ui/button'; import Link from 'next/link'; import fetchData from '@/lib/fetchData'; -import ProjectDetailComponent from './ProjectDetailComponent'; -import { ArrowLeft, Briefcase, Building2, Calendar, CheckCircle2, ClipboardList, Clock3, Hash, Users } from 'lucide-react'; -import { COMPLETE_STATUS_LIST, ONPROGRESS_STATUS_LIST } from '@/app/(dashboard)/task/type.assignment'; -import { motion } from 'motion/react'; -import { Card900 } from '@/components/ui/card'; +import { ArrowLeft, Briefcase, Calendar, CheckCircle2, ClipboardList, Clock3, Hash, Users } from 'lucide-react'; +import { COMPLETE_STATUS_LIST, IProjectAssignment, ONPROGRESS_STATUS_LIST } from '@/app/(dashboard)/task/type.assignment'; +import { Card, Card900, CardContent } from '@/components/ui/card'; import WorkOrderCard from './WorkOrderCard'; import { MotionDiv } from '@/components/ui/motion-wrapper'; import { LazyImage } from '@/components/ui/lazy-image'; import { Badge } from '@/components/ui/badge'; +import FilterComponent from '@/app/(dashboard)/task/component/FilterComponent'; type Props = { params: Promise<{ client_id: string; project_id: string }> + searchParams: Promise<{ [key: string]: string | undefined }> }; -export default async function ProjectDetailPage({ params }: Props) { +export default async function ProjectDetailPage({ params, searchParams }: Props) { const { client_id, project_id } = await params; + const q = (await searchParams)!.q + const status = (await searchParams)!.status + const sort = (await searchParams)!.sort + + const query = (q || '').toLowerCase() + const activeStatuses = status ? status.toLowerCase()?.split(',') : []; + const sortBy = sort || 'default'; const getClientById = fetchData(`/client/${client_id}`) const getAssignmentByProjectId = fetchData(`/project/${project_id}`) @@ -88,8 +95,49 @@ export default async function ProjectDetailPage({ params }: Props) { }, ]; + const filterData = () => { + if (project.project_assignment && project.project_assignment?.length === 0) return [] + // 1. FILTERING + let processedData = project.project_assignment?.filter((item: IProjectAssignment) => { + const matchesSearch = query === '' || ( + (item.wo_name?.toLowerCase().includes(query)) || + (item.wo_code?.toLowerCase().includes(query)) + ); - // 4. Pass the fetched data to the interactive Client Component + // --- Status Filter --- + const itemStatus = item.project_status?.name?.toLowerCase(); + const matchesStatus = activeStatuses.length === 0 || (itemStatus && activeStatuses.includes(itemStatus)); + + return matchesSearch && matchesStatus; + }); + + // 2. SORTING + processedData = processedData.sort((a: IProjectAssignment, b: IProjectAssignment) => { + if (sortBy === 'latest') { + return new Date(b.created_at).getTime() - new Date(a.created_at).getTime(); + } + + if (sortBy === 'oldest') { + return new Date(a.created_at).getTime() - new Date(b.created_at).getTime(); + } + + if (sortBy === 'participants_desc') { + const aCount = a.project_assignment_work_order_detail?.length || 0; + const bCount = b.project_assignment_work_order_detail?.length || 0; + return bCount - aCount; // Highest count first + } + + if (sortBy === 'participants_asc') { + const aCount = a.project_assignment_work_order_detail?.length || 0; + const bCount = b.project_assignment_work_order_detail?.length || 0; + return aCount - bCount; // Lowest count first + } + + return 0; // 'default' - keeps original array order + }); + + return processedData; + } return ( <> {/* Client card */} -
-
+
+
@@ -202,9 +250,7 @@ export default async function ProjectDetailPage({ params }: Props) { {/* Work Orders section */}
-
- -
+

Work Orders

@@ -214,10 +260,28 @@ export default async function ProjectDetailPage({ params }: Props) {

+
+ +
- {project.project_assignment.map((wo: any, i: number) => + {filterData() && filterData().length > 0 ? project.project_assignment.map((wo: any, i: number) => - )} + ) + : + + +
+ +
+
+

No Project Assignments Found

+

+ Try to change the filter or create one to get started. +

+
+
+
+ }
diff --git a/app/(dashboard)/task/component/AssignmentTable.tsx b/app/(dashboard)/task/component/AssignmentTable.tsx index 83ced88..50e2c13 100644 --- a/app/(dashboard)/task/component/AssignmentTable.tsx +++ b/app/(dashboard)/task/component/AssignmentTable.tsx @@ -1,17 +1,19 @@ // app/clients/components/assignment-table.tsx -import { Card, Card900 } from '@/components/ui/card'; +import { Card } from '@/components/ui/card'; import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table'; -import { Badge } from '@/components/ui/badge'; import Link from 'next/link'; -import { cn } from '@/lib/utils'; -import { BookOpenCheck } from 'lucide-react'; +import { BookOpenCheck, MoreVertical } from 'lucide-react'; +import BadgeStatus from '@/components/ui/badge-status'; +import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from '@/components/ui/dropdown-menu'; +import { Button } from '@/components/ui/button'; +import { IProjectAssignment } from '../type.assignment'; -export default function AssignmentTable({ data }: { data: any[] }) { +export default function AssignmentTable({ data }: { data: IProjectAssignment[] }) { if (data.length === 0) { - return + return

No project assignment found

-
+ } return ( @@ -22,69 +24,97 @@ export default function AssignmentTable({ data }: { data: any[] }) { Client End User + IM Name + IM Code + Description + IM Year + IM Start + IM End Project Name Project Code Description Year Proj Start Proj End - Work Order + Work Order WO Code WO Start WO End Last Status - Date Status Changed - Status Remarks + - {data.map((item, idx) => { - const { client, assignment, wo } = item; - const latestStatus = wo?.statusHistory?.[0] || assignment.statusHistory?.[0]; + {data.map((assignment, idx) => { + const isProject = assignment.project?.code return ( - - {client.name} - {client.endUser} + - - {assignment.name} + + {assignment.project?.client?.name} - {assignment.code || '-'} - - {assignment.description} + {assignment.project?.client?.end_user_name} + {assignment.im_name} + {assignment.im_code || ''} + + {assignment.im_description} - {assignment.year || '-'} - - {assignment.startDate ? new Date(assignment.startDate).toLocaleDateString() : '-'} + {assignment.im_year || ''} + + {assignment.im_start_date ? new Date(assignment.im_start_date).toLocaleDateString() : ''} - - {assignment.endDate ? new Date(assignment.endDate).toLocaleDateString() : '-'} + + {assignment.im_end_date ? new Date(assignment.im_end_date).toLocaleDateString() : ''} - {wo?.name || '-'} - {wo?.code || '-'} - - {wo?.startDate ? new Date(wo.startDate).toLocaleDateString() : '-'} + + + {assignment.project?.name} + - - {wo?.endDate ? new Date(wo.endDate).toLocaleDateString() : '-'} + {assignment.project?.code || ''} + + {assignment.project?.description} + + {assignment.project?.year || ''} + + {assignment.project?.start_date ? new Date(assignment.project?.start_date).toLocaleDateString() : ''} + + + {assignment.project?.end_date ? new Date(assignment.project?.end_date).toLocaleDateString() : ''} + + {assignment.wo_name || ''} + {assignment.wo_code || ''} + + {assignment.wo_start_date ? new Date(assignment.wo_start_date).toLocaleDateString() : ''} + + + {assignment.wo_end_date ? new Date(assignment.wo_end_date).toLocaleDateString() : ''} - - {wo?.status || assignment.status} - + - - {latestStatus ? new Date(latestStatus.date).toLocaleDateString() : '-'} - - - {latestStatus?.note || '-'} + + + + + + + + View Assignment Details + + {assignment.project?.code ? + + View Project Details + + : + null + } + + ); diff --git a/app/(dashboard)/task/component/ClientGrid.tsx b/app/(dashboard)/task/component/ClientGrid.tsx index 2252a95..82ca642 100644 --- a/app/(dashboard)/task/component/ClientGrid.tsx +++ b/app/(dashboard)/task/component/ClientGrid.tsx @@ -16,8 +16,8 @@ import { import { DUMMY_EMPLOYEES, IClient } from '../types'; import { useState } from 'react'; import { useRouter } from 'next/navigation'; -import { ConfirmDelete } from '@/components/modal/ConfirmDelete'; import FormClient from './FormClient'; +import { ConfirmDeleteWithInput } from '@/components/modal/ConfirmDeleteWithInput'; export default function ClientGrid({ clients, assignments }: { clients: IClient[], assignments: any[] }) { const router = useRouter(); @@ -172,7 +172,10 @@ export default function ClientGrid({ clients, assignments }: { clients: IClient[
{action === 'EDIT' && { router.refresh(); handleClose() }} />} - {action === 'DELETE' ? { router.refresh(); handleClose() }} /> : null} + {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} ); } \ No newline at end of file diff --git a/app/(dashboard)/task/component/FilterComponent.tsx b/app/(dashboard)/task/component/FilterComponent.tsx new file mode 100644 index 0000000..29ec3ca --- /dev/null +++ b/app/(dashboard)/task/component/FilterComponent.tsx @@ -0,0 +1,104 @@ +"use client" + +import { Input } from '@/components/ui/input'; +import { MultiSelect } from '@/components/ui/multi-select'; // Assuming this is a custom component +import { Search } from 'lucide-react'; +import { usePathname, useRouter, useSearchParams } from 'next/navigation'; +import { type FC, useEffect, useState } from 'react'; +import { STATUS_LIST } from '../type.assignment'; +import { + Select, SelectContent, SelectItem, SelectTrigger, SelectValue, +} from '@/components/ui/select'; +import useDebounce from '@/hooks/useDebounce'; + +type Props = {}; + +const FilterComponent: FC = ({ }) => { + const router = useRouter(); + const pathname = usePathname(); + const searchParams = useSearchParams(); + + const currentQuery = searchParams?.get('q') || ''; + const currentStatus = searchParams?.get('status'); + const currentSort = searchParams?.get('sort') || ''; + + const [searchText, setSearchText] = useState(currentQuery); + + const [debouncedSearchText] = useDebounce(searchText, 500); + + useEffect(() => { + const params = new URLSearchParams(searchParams!); + + if (debouncedSearchText) { + params.set('q', debouncedSearchText); + } else { + params.delete('q'); + } + + router.replace(`${pathname}?${params.toString()}`, { scroll: false }); + }, [debouncedSearchText, pathname, router]); // Remove searchParams from dependency array to prevent infinite loops + + const handleStatusChange = (val: any[]) => { + const params = new URLSearchParams(searchParams!); + + if (val && val.length > 0) { + params.set('status', val.join(',')); + } else { + params.delete('status'); + } + + router.replace(`${pathname}?${params.toString()}`, { scroll: false }); + }; + + const handleSortChange = (val: string) => { + const params = new URLSearchParams(searchParams!); + + if (val && val !== 'default') { + params.set('sort', val); + } else { + params.delete('sort'); + } + + router.replace(`${pathname}?${params.toString()}`, { scroll: false }); + }; + + return ( +
+
+
+ + setSearchText(e.target.value)} + /> +
+ + ({ label: item, value: item }))} + maxCount={1} + /> +
+ + +
+ ); +} + +export default FilterComponent; \ No newline at end of file diff --git a/app/(dashboard)/task/component/ManageEmployee.tsx b/app/(dashboard)/task/component/ManageEmployee.tsx index bd1cee9..47ab24c 100644 --- a/app/(dashboard)/task/component/ManageEmployee.tsx +++ b/app/(dashboard)/task/component/ManageEmployee.tsx @@ -1,6 +1,6 @@ "use client" -import { useState, type FC } from 'react'; +import { useMemo, useState, type FC } from 'react'; import { AlertDialog, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from "@/components/ui/alert-dialog" @@ -12,6 +12,14 @@ 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'; type Props = { data: IProjectAssignment @@ -20,31 +28,69 @@ type Props = { onSuccess?: VoidFunction; }; +const validationSchema = Yup.object().shape({ + start_date: Yup.date().required('Start date is required'), + end_date: Yup.date().nullable().min(Yup.ref('startDate'), 'End date cannot be before start date').default(null), + user_id: Yup.array().of(Yup.number().required("Each item must be a number")).min(1, 'One user must be add').required() +}); + +type FormDataType = Yup.InferType; + + const ManageEmployee: FC = ({ title, onCancel, onSuccess }) => { const [selectedEmployeeIds, setSelectedEmployeeIds] = useState([]); const [isLoading, setIsLoading] = useState(false) const { data, isLoading: isLoadingFetchUser } = useFetchWithAxios('/user') + const form = useForm({ + resolver: yupResolver(validationSchema), + defaultValues: {}, + }); + const toggleEmployee = (empId: number) => { setSelectedEmployeeIds(prev => prev.includes(empId) ? prev.filter(i => i !== empId) : [...prev, empId] ); }; - const handleAssignEmployee = async () => { - setIsLoading(true) - onSuccess!() - } + const onSubmit = async (payload: FormDataType) => { + setIsLoading(true); + + let newPayload: any = { ...payload } + + let res: any + if (data) { + res = await serverApiCall('PUT', `/project-assignment/assign-user/${data.id}`, newPayload) + } else { + res = await serverApiCall('POST', '/project-assignment/assign-user', newPayload) + } + + 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 data?.user?.map((item: IUser) => ({ + label: item.fullname, + value: item.id, + originalData: item + })) || [] + }, [data]) return ( <> - + Manage Team - Assign or remove employees for {title} + Assign employees for {title}
@@ -57,35 +103,68 @@ const ManageEmployee: FC = ({ title, onCancel, onSuccess }) => {
: - data?.user?.map((emp: IUser) => ( -
toggleEmployee(emp.id)} - > -
- - {selectedEmployeeIds.includes(emp.id) && -
- -
- } +
+ +
+ ( + + Employee to Assign * + + { + const user = option.originalData as IUser; + return ( +
+
+ +
+ + {user.fullname} + + + {user.role.name} + +
+
+ {isSelected &&
} +
+ ); + }} + /> + + + + )} + /> + ( + + Start Date + + + + )} /> + + ( + + End Date + + + + )} />
-
-

{emp.fullname}

-

{emp.position}

-
-
- )) + + Cancel + + +
+ }
- - Cancel - - diff --git a/app/(dashboard)/task/page.tsx b/app/(dashboard)/task/page.tsx index cd6ccb4..0a48cb4 100644 --- a/app/(dashboard)/task/page.tsx +++ b/app/(dashboard)/task/page.tsx @@ -4,6 +4,8 @@ import HomeTask from './component/HomeTask'; import ClientGrid from './component/ClientGrid'; import AssignmentTable from './component/AssignmentTable'; import fetchData from '@/lib/fetchData'; +import { IClient } from './types'; +import { IProjectAssignment } from './type.assignment'; type Props = { searchParams: Promise<{ view?: string; q?: string }> @@ -21,26 +23,21 @@ export default async function ClientsPage({ searchParams }: Props) { const [allClients, allAssignments] = await Promise.all([getClient, getAssignment]); // 3. Process Data for Grid View - const filteredClients = allClients.filter((c: any) => + const filteredClients = allClients.filter((c: IClient) => c.name.toLowerCase().includes(query) || c.endUser.toLowerCase().includes(query) ); - const flattenedAssignments = allAssignments.flatMap((assignment: any) => { - const client = allClients.find((c: any) => c.id === assignment.clientId); - if (!client) return []; - - if (assignment.workOrder && assignment.workOrder.length > 0) { - return assignment.workOrder.map((wo: any) => ({ client, assignment, wo })); - } - - return [{ client, assignment, wo: null }]; - }).filter((item: any) => - item.client.name.toLowerCase().includes(query) || - item.assignment.name.toLowerCase().includes(query) || - (item.wo?.name.toLowerCase().includes(query) ?? false) + const flattenedAssignments = allAssignments.filter((c: IProjectAssignment) => + c.project?.name?.toLowerCase().includes(query) || + c.project?.name?.toLowerCase().includes(query) || + c.im_name?.toLowerCase().includes(query) || + c.im_code?.toLowerCase().includes(query) || + c.wo_name?.toLowerCase().includes(query) || + c.wo_code?.toLowerCase().includes(query) ); + return (