mirror of
https://github.com/ichsankurnia/hats-app.git
synced 2026-12-05 10:56:28 +00:00
fixing ui, logic etc..
This commit is contained in:
@@ -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<IProjectAssignment>()
|
||||
|
||||
const router = useRouter()
|
||||
@@ -60,6 +62,9 @@ export default function ClientDetailComponent({ clientId, initialAssignments }:
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
<FilterComponent />
|
||||
|
||||
{/* --- EMPTY STATE --- */}
|
||||
{initialAssignments.length === 0 ?
|
||||
<Card className="border-dashed bg-accent/20">
|
||||
@@ -83,19 +88,19 @@ export default function ClientDetailComponent({ clientId, initialAssignments }:
|
||||
/* --- GRID VIEW --- */
|
||||
<div className="grid gap-4">
|
||||
{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 (
|
||||
<motion.div key={assignment.id} initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }}>
|
||||
<Link href={`${clientId}/${assignment.id}`}>
|
||||
<Card900 key={assignment.id} className="group hover:border-primary/30 transition-all duration-300">
|
||||
<Card900 key={assignment.id} className="group hover:border-primary/30 transition-all duration-300 hover:scale-101">
|
||||
<CardContent className="py-4">
|
||||
<div className="flex items-start justify-between gap-4">
|
||||
<div className="flex items-start gap-4">
|
||||
@@ -104,11 +109,11 @@ export default function ClientDetailComponent({ clientId, initialAssignments }:
|
||||
</div>
|
||||
<div>
|
||||
{isProject ?
|
||||
<Link href={`${clientId}/project-detail/${assignment.project.id}`} onClick={(e) => e.stopPropagation()}>
|
||||
<div className="flex items-center gap-3 mb-1">
|
||||
<div className='flex items-center gap-0 group-hover:gap-3 duration-300'>
|
||||
<h3 className="font-bold text-xl group-hover:underline duration-300 group-hover:text-his">{assignmentName}</h3>
|
||||
<Button size="icon" variant="secondary" className="h-8 w-8 rounded-full opacity-0 group-hover:opacity-100 transition-opacity cursor-pointer">
|
||||
<Link href={`${clientId}/project-detail/${assignment.project?.id}`} onClick={(e) => e.stopPropagation()}>
|
||||
<div className="flex flex-col sm:flex-row items-start sm:items-center gap-3 mb-1 group/in">
|
||||
<div className='flex items-center gap-0 group-hover/in:gap-3 duration-300'>
|
||||
<h3 className="font-bold text-xl group-hover/in:underline duration-300 group-hover/in:text-his">{assignmentName}</h3>
|
||||
<Button size="icon" variant="secondary" className="h-8 w-8 rounded-full opacity-0 group-hover/in:opacity-100 transition-opacity cursor-pointer">
|
||||
<ExternalLink className="w-4 h-4" />
|
||||
</Button>
|
||||
</div>
|
||||
@@ -117,18 +122,18 @@ export default function ClientDetailComponent({ clientId, initialAssignments }:
|
||||
</div>
|
||||
</Link>
|
||||
:
|
||||
<div className="flex items-center gap-3 mb-1">
|
||||
<div className="flex flex-col sm:flex-row items-start sm:items-center gap-3 mb-1">
|
||||
<h3 className="font-bold text-xl">{assignmentName}</h3>
|
||||
<Badge variant={'info'}>{assignmentType}</Badge>
|
||||
<BadgeStatus status={assignmentStatus} />
|
||||
</div>
|
||||
}
|
||||
|
||||
{assignment.wo_code && (
|
||||
{assignment.wo_name &&
|
||||
<p className="text-sm font-medium text-primary mb-1">
|
||||
WO: {assignment.wo_name}
|
||||
</p>
|
||||
)}
|
||||
}
|
||||
|
||||
<p className="text-muted-foreground line-clamp-2 text-sm mb-4">
|
||||
{assignmentDesc}
|
||||
@@ -184,15 +189,17 @@ export default function ClientDetailComponent({ clientId, initialAssignments }:
|
||||
<DropdownMenuItem asChild>
|
||||
<Link href={`/task/client-detail/${clientId}/${assignment.id}`}>View Assignment Details</Link>
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem asChild>
|
||||
<Link href={`${clientId}/project-detail/${assignment.project.id}`}>View Project Details</Link>
|
||||
</DropdownMenuItem>
|
||||
{isProject ?
|
||||
<DropdownMenuItem asChild>
|
||||
<Link href={`${clientId}/project-detail/${assignment.project?.id}`}>View Project Details</Link>
|
||||
</DropdownMenuItem> : null
|
||||
}
|
||||
<DropdownMenuItem asChild>
|
||||
<Link href={`${clientId}/project-assignments?is_edit=true&assignment_id=${assignment.id}`}>Edit Assignment</Link>
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={() => { setSelectedData(assignment); setAction('MANAGE_EMPLOYEE') }}>Manage Employees</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={() => { setSelectedData(assignment); setAction('UPDATE_STATUS') }}>Update Assignment Status</DropdownMenuItem>
|
||||
<DropdownMenuItem className="text-destructive">Delete</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={(e) => e.stopPropagation()} onSelect={() => { setSelectedData(assignment); setAction('MANAGE_EMPLOYEE') }}>Manage Employees</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={(e) => e.stopPropagation()} onSelect={() => { setSelectedData(assignment); setAction('UPDATE_STATUS') }}>Update Assignment Status</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={(e) => e.stopPropagation()} onSelect={() => { setSelectedData(assignment); setAction('DELETE') }} className="text-destructive">Delete</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
@@ -236,39 +243,43 @@ export default function ClientDetailComponent({ clientId, initialAssignments }:
|
||||
return (
|
||||
<TableRow key={assignment.id}>
|
||||
<TableCell className="font-medium">{assignment.im_name}</TableCell>
|
||||
<TableCell>{assignment.im_code || '-'}</TableCell>
|
||||
<TableCell>{assignment.im_code || ''}</TableCell>
|
||||
<TableCell className="max-w-[300px] truncate" title={assignment.im_description}>
|
||||
{assignment.im_description}
|
||||
</TableCell>
|
||||
<TableCell>{assignment.im_year || '-'}</TableCell>
|
||||
<TableCell>{assignment.im_year || ''}</TableCell>
|
||||
<TableCell className="whitespace-nowrap">
|
||||
{assignment.im_start_date ? new Date(assignment.im_start_date).toLocaleDateString() : '-'}
|
||||
{assignment.im_start_date ? new Date(assignment.im_start_date).toLocaleDateString() : ''}
|
||||
</TableCell>
|
||||
<TableCell className="whitespace-nowrap">
|
||||
{assignment.im_end_date ? new Date(assignment.im_end_date).toLocaleDateString() : '-'}
|
||||
{assignment.im_end_date ? new Date(assignment.im_end_date).toLocaleDateString() : ''}
|
||||
</TableCell>
|
||||
<TableCell className="font-medium">{assignment.project.name}</TableCell>
|
||||
<TableCell>{assignment.project.code || '-'}</TableCell>
|
||||
<TableCell className="max-w-[300px] truncate" title={assignment.project.description}>
|
||||
{assignment.project.description}
|
||||
<TableCell className="font-medium">
|
||||
<Link href={`${clientId}/project-detail/${assignment.project?.id}`} className='text-blue-500 hover:text-his duration-300'>
|
||||
{assignment.project?.name}
|
||||
</Link>
|
||||
</TableCell>
|
||||
<TableCell>{assignment.project.year || '-'}</TableCell>
|
||||
<TableCell>{assignment.project?.code || ''}</TableCell>
|
||||
<TableCell className="max-w-[300px] truncate" title={assignment.project?.description}>
|
||||
{assignment.project?.description}
|
||||
</TableCell>
|
||||
<TableCell>{assignment.project?.year || ''}</TableCell>
|
||||
<TableCell className="whitespace-nowrap">
|
||||
{assignment.project.start_date ? new Date(assignment.project.start_date).toLocaleDateString() : '-'}
|
||||
{assignment.project?.start_date ? new Date(assignment.project?.start_date).toLocaleDateString() : ''}
|
||||
</TableCell>
|
||||
<TableCell className="whitespace-nowrap">
|
||||
{assignment.project.end_date ? new Date(assignment.project.end_date).toLocaleDateString() : '-'}
|
||||
{assignment.project?.end_date ? new Date(assignment.project?.end_date).toLocaleDateString() : ''}
|
||||
</TableCell>
|
||||
<TableCell>{assignment.wo_name || '-'}</TableCell>
|
||||
<TableCell>{assignment.wo_code || '-'}</TableCell>
|
||||
<TableCell>{assignment.wo_name || ''}</TableCell>
|
||||
<TableCell>{assignment.wo_code || ''}</TableCell>
|
||||
<TableCell className="whitespace-nowrap">
|
||||
{assignment.wo_start_date ? new Date(assignment.wo_start_date).toLocaleDateString() : '-'}
|
||||
{assignment.wo_start_date ? new Date(assignment.wo_start_date).toLocaleDateString() : ''}
|
||||
</TableCell>
|
||||
<TableCell className="whitespace-nowrap">
|
||||
{assignment.wo_end_date ? new Date(assignment.wo_end_date).toLocaleDateString() : '-'}
|
||||
{assignment.wo_end_date ? new Date(assignment.wo_end_date).toLocaleDateString() : ''}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<BadgeStatus status={assignment.project.status || assignment.project_status.name} />
|
||||
<BadgeStatus status={assignment.project?.status || assignment.project_status.name} />
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<DropdownMenu>
|
||||
@@ -281,15 +292,19 @@ export default function ClientDetailComponent({ clientId, initialAssignments }:
|
||||
<DropdownMenuItem asChild>
|
||||
<Link href={`${clientId}/${assignment.id}`}>View Assignment Details</Link>
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem asChild>
|
||||
<Link href={`${clientId}/project-detail/${assignment.project.id}`}>View Project Details</Link>
|
||||
</DropdownMenuItem>
|
||||
{assignment.project?.code ?
|
||||
<DropdownMenuItem asChild>
|
||||
<Link href={`${clientId}/project-detail/${assignment.project?.id}`}>View Project Details</Link>
|
||||
</DropdownMenuItem>
|
||||
:
|
||||
null
|
||||
}
|
||||
<DropdownMenuItem asChild>
|
||||
<Link href={`${clientId}/project-assignments?is_edit=true&assignment_id=${assignment.id}`}>Edit Assignment</Link>
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={() => { setSelectedData(assignment); setAction('MANAGE_EMPLOYEE') }}>Add Team</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={() => { setSelectedData(assignment); setAction('UPDATE_STATUS') }}>Update Status</DropdownMenuItem>
|
||||
<DropdownMenuItem className="text-destructive">Delete</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={(e) => e.stopPropagation()} onSelect={() => { setSelectedData(assignment); setAction('MANAGE_EMPLOYEE') }}>Add Team</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={(e) => e.stopPropagation()} onSelect={() => { setSelectedData(assignment); setAction('UPDATE_STATUS') }}>Update Status</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={(e) => e.stopPropagation()} onSelect={() => { setSelectedData(assignment); setAction('DELETE') }} className="text-destructive">Delete</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</TableCell>
|
||||
@@ -311,6 +326,11 @@ export default function ClientDetailComponent({ clientId, initialAssignments }:
|
||||
<FormUpdateStatus data={selectedData!} title={selectedData?.wo_name || selectedData?.im_name} onCancel={handleClose} onSuccess={handleSuccess} />
|
||||
: null
|
||||
}
|
||||
|
||||
{action === 'DELETE' ? <ConfirmDeleteWithInput endpoint={`/project-assignment/${selectedData?.id}`} onCancel={handleClose} onSuccess={() => { 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}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -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 (
|
||||
<div className="flex-1 space-y-8 p-6 sm:p-8 pt-6">
|
||||
<div className="flex flex-col md:flex-row md:items-end justify-between gap-6">
|
||||
@@ -46,8 +105,8 @@ export default async function ClientDetailPage({ params }: Props) {
|
||||
<ArrowLeft className="w-4 h-4 mr-1" /> Back to Clients
|
||||
</Button>
|
||||
</Link>
|
||||
<h1 className="text-4xl font-bold tracking-tight">{client.name}</h1>
|
||||
<p className="text-lg text-muted-foreground">End User: {client.end_user_name}</p>
|
||||
<h1 className="text-xl sm:text-4xl font-bold tracking-tight">{client.name}</h1>
|
||||
<p className="text-sm sm:text-lg text-muted-foreground">End User: {client.end_user_name}</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex gap-3">
|
||||
@@ -66,7 +125,7 @@ export default async function ClientDetailPage({ params }: Props) {
|
||||
{/* Pass the server-fetched data as props */}
|
||||
<ClientDetailComponent
|
||||
clientId={client_id}
|
||||
initialAssignments={assignmentList}
|
||||
initialAssignments={filterData()}
|
||||
/>
|
||||
</div>
|
||||
|
||||
|
||||
+4
-2
@@ -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)
|
||||
|
||||
+78
-14
@@ -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 (
|
||||
<>
|
||||
<MotionDiv
|
||||
@@ -140,8 +188,8 @@ export default async function ProjectDetailPage({ params }: Props) {
|
||||
</div>
|
||||
|
||||
{/* Client card */}
|
||||
<div className="inline-flex items-center gap-5 p-5 rounded-xl bg-muted/40 border border-border/60 backdrop-blur-sm">
|
||||
<div className="w-14 h-14 rounded-lg bg-linear-to-br from-primary to-his shadow-lg shrink-0">
|
||||
<div className="inline-flex flex-col sm:flex-row items-center gap-5 p-5 rounded-xl bg-muted/40 border border-border/60 backdrop-blur-sm">
|
||||
<div className="w-full h-20 sm:w-14 sm:h-14 rounded-lg bg-linear-to-br from-primary to-his shadow-lg shrink-0">
|
||||
<LazyImage alt={client.name} src={client.photo} className='w-full h-full object-cover rounded-lg' />
|
||||
</div>
|
||||
<div>
|
||||
@@ -202,9 +250,7 @@ export default async function ProjectDetailPage({ params }: Props) {
|
||||
{/* Work Orders section */}
|
||||
<div className="mb-4 flex items-center justify-between flex-wrap gap-3">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="w-10 h-10 rounded-xl bg-linear-to-br from-primary to-his flex items-center justify-center shadow-lg">
|
||||
<ClipboardList className="w-5 h-5 text-white" />
|
||||
</div>
|
||||
<ClipboardList className="w-6 h-6 text-primary" />
|
||||
<div>
|
||||
<h2 className="text-xl sm:text-2xl font-bold text-foreground">Work Orders</h2>
|
||||
<p className="text-muted-foreground">
|
||||
@@ -214,10 +260,28 @@ export default async function ProjectDetailPage({ params }: Props) {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className='mb-5'>
|
||||
<FilterComponent />
|
||||
</div>
|
||||
<div className="space-y-4">
|
||||
{project.project_assignment.map((wo: any, i: number) =>
|
||||
{filterData() && filterData().length > 0 ? project.project_assignment.map((wo: any, i: number) =>
|
||||
<WorkOrderCard key={wo.id} workOrder={wo} index={i} defaultOpen={i === 0} />
|
||||
)}
|
||||
)
|
||||
:
|
||||
<Card className="border-dashed bg-accent/20">
|
||||
<CardContent className="flex flex-col items-center justify-center py-16 space-y-4">
|
||||
<div className="w-16 h-16 rounded-full bg-accent flex items-center justify-center">
|
||||
<Briefcase className="w-8 h-8 text-muted-foreground" />
|
||||
</div>
|
||||
<div className="text-center">
|
||||
<h3 className="text-xl font-semibold">No Project Assignments Found</h3>
|
||||
<p className="text-muted-foreground max-w-xs mx-auto mt-2">
|
||||
Try to change the filter or create one to get started.
|
||||
</p>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
}
|
||||
</div>
|
||||
|
||||
</MotionDiv>
|
||||
|
||||
@@ -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 <Card900 className="py-12 text-center border-2 border-dashed rounded-xl">
|
||||
return <Card className="py-12 text-center border-2 border-dashed rounded-xl">
|
||||
<BookOpenCheck className="w-12 h-12 mx-auto text-muted-foreground opacity-20" />
|
||||
<h3 className="text-lg font-medium">No project assignment found</h3>
|
||||
</Card900>
|
||||
</Card>
|
||||
}
|
||||
|
||||
return (
|
||||
@@ -22,69 +24,97 @@ export default function AssignmentTable({ data }: { data: any[] }) {
|
||||
<TableRow>
|
||||
<TableHead className="min-w-[150px]">Client</TableHead>
|
||||
<TableHead className="min-w-[120px]">End User</TableHead>
|
||||
<TableHead className="min-w-[200px]">IM Name</TableHead>
|
||||
<TableHead>IM Code</TableHead>
|
||||
<TableHead className="min-w-[200px]">Description</TableHead>
|
||||
<TableHead>IM Year</TableHead>
|
||||
<TableHead>IM Start</TableHead>
|
||||
<TableHead>IM End</TableHead>
|
||||
<TableHead className="min-w-[200px]">Project Name</TableHead>
|
||||
<TableHead>Project Code</TableHead>
|
||||
<TableHead className="min-w-[200px]">Description</TableHead>
|
||||
<TableHead>Year</TableHead>
|
||||
<TableHead>Proj Start</TableHead>
|
||||
<TableHead>Proj End</TableHead>
|
||||
<TableHead className="min-w-[180px]">Work Order</TableHead>
|
||||
<TableHead className="min-w-[150px]">Work Order</TableHead>
|
||||
<TableHead>WO Code</TableHead>
|
||||
<TableHead>WO Start</TableHead>
|
||||
<TableHead>WO End</TableHead>
|
||||
<TableHead>Last Status</TableHead>
|
||||
<TableHead>Date Status Changed</TableHead>
|
||||
<TableHead className="min-w-[200px]">Status Remarks</TableHead>
|
||||
<TableHead className="w-[50px]"></TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{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 (
|
||||
<TableRow key={`${assignment.id}-${wo?.id || idx}`} className="hover:bg-accent/30">
|
||||
<TableCell className="font-bold text-primary">{client.name}</TableCell>
|
||||
<TableCell>{client.endUser}</TableCell>
|
||||
<TableRow key={idx} className="hover:bg-accent/30">
|
||||
<TableCell className="font-medium">
|
||||
<Link href={`/assignments/${assignment.id}`} className="hover:underline text-blue-600 dark:text-blue-400">
|
||||
{assignment.name}
|
||||
<Link href={`client-detail/${assignment.project?.client?.id}`} className="hover:underline text-blue-500 hover:text-his">
|
||||
{assignment.project?.client?.name}
|
||||
</Link>
|
||||
</TableCell>
|
||||
<TableCell className="font-mono text-xs">{assignment.code || '-'}</TableCell>
|
||||
<TableCell className="max-w-[250px] truncate text-xs" title={assignment.description}>
|
||||
{assignment.description}
|
||||
<TableCell className="font-bold text-primary">{assignment.project?.client?.end_user_name}</TableCell>
|
||||
<TableCell className="font-medium">{assignment.im_name}</TableCell>
|
||||
<TableCell>{assignment.im_code || ''}</TableCell>
|
||||
<TableCell className="max-w-[300px] truncate" title={assignment.im_description}>
|
||||
{assignment.im_description}
|
||||
</TableCell>
|
||||
<TableCell>{assignment.year || '-'}</TableCell>
|
||||
<TableCell className="whitespace-nowrap text-xs">
|
||||
{assignment.startDate ? new Date(assignment.startDate).toLocaleDateString() : '-'}
|
||||
<TableCell>{assignment.im_year || ''}</TableCell>
|
||||
<TableCell className="whitespace-nowrap">
|
||||
{assignment.im_start_date ? new Date(assignment.im_start_date).toLocaleDateString() : ''}
|
||||
</TableCell>
|
||||
<TableCell className="whitespace-nowrap text-xs">
|
||||
{assignment.endDate ? new Date(assignment.endDate).toLocaleDateString() : '-'}
|
||||
<TableCell className="whitespace-nowrap">
|
||||
{assignment.im_end_date ? new Date(assignment.im_end_date).toLocaleDateString() : ''}
|
||||
</TableCell>
|
||||
<TableCell className="font-medium">{wo?.name || '-'}</TableCell>
|
||||
<TableCell className="font-mono text-xs">{wo?.code || '-'}</TableCell>
|
||||
<TableCell className="whitespace-nowrap text-xs">
|
||||
{wo?.startDate ? new Date(wo.startDate).toLocaleDateString() : '-'}
|
||||
<TableCell className="font-medium">
|
||||
<Link href={`client-detail/${assignment.project?.client?.id}/project-detail/${assignment.project?.id}`} className='text-blue-500 hover:text-his duration-300'>
|
||||
{assignment.project?.name}
|
||||
</Link>
|
||||
</TableCell>
|
||||
<TableCell className="whitespace-nowrap text-xs">
|
||||
{wo?.endDate ? new Date(wo.endDate).toLocaleDateString() : '-'}
|
||||
<TableCell>{assignment.project?.code || ''}</TableCell>
|
||||
<TableCell className="max-w-[300px] truncate" title={assignment.project?.description}>
|
||||
{assignment.project?.description}
|
||||
</TableCell>
|
||||
<TableCell>{assignment.project?.year || ''}</TableCell>
|
||||
<TableCell className="whitespace-nowrap">
|
||||
{assignment.project?.start_date ? new Date(assignment.project?.start_date).toLocaleDateString() : ''}
|
||||
</TableCell>
|
||||
<TableCell className="whitespace-nowrap">
|
||||
{assignment.project?.end_date ? new Date(assignment.project?.end_date).toLocaleDateString() : ''}
|
||||
</TableCell>
|
||||
<TableCell>{assignment.wo_name || ''}</TableCell>
|
||||
<TableCell>{assignment.wo_code || ''}</TableCell>
|
||||
<TableCell className="whitespace-nowrap">
|
||||
{assignment.wo_start_date ? new Date(assignment.wo_start_date).toLocaleDateString() : ''}
|
||||
</TableCell>
|
||||
<TableCell className="whitespace-nowrap">
|
||||
{assignment.wo_end_date ? new Date(assignment.wo_end_date).toLocaleDateString() : ''}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Badge variant="outline" className={cn(
|
||||
"text-[10px] px-2 py-0 h-5",
|
||||
(wo?.status || assignment.status) === 'Active' ? 'text-green-600 border-green-200 bg-green-50' :
|
||||
(wo?.status || assignment.status) === 'Completed' ? 'text-blue-600 border-blue-200 bg-blue-50' :
|
||||
'text-orange-600 border-orange-200 bg-orange-50'
|
||||
)}>
|
||||
{wo?.status || assignment.status}
|
||||
</Badge>
|
||||
<BadgeStatus status={assignment.project?.status || assignment.project_status.name} />
|
||||
</TableCell>
|
||||
<TableCell className="whitespace-nowrap text-xs">
|
||||
{latestStatus ? new Date(latestStatus.date).toLocaleDateString() : '-'}
|
||||
</TableCell>
|
||||
<TableCell className="text-xs italic text-muted-foreground">
|
||||
{latestStatus?.note || '-'}
|
||||
<TableCell>
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="ghost" size="icon" className="h-8 w-8">
|
||||
<MoreVertical className="w-4 h-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuItem asChild>
|
||||
<Link href={`client-detail/${assignment.project?.client?.id}/${assignment.id}`}>View Assignment Details</Link>
|
||||
</DropdownMenuItem>
|
||||
{assignment.project?.code ?
|
||||
<DropdownMenuItem asChild>
|
||||
<Link href={`client-detail/${assignment.project?.client?.id}/project-detail/${assignment.project?.id}`}>View Project Details</Link>
|
||||
</DropdownMenuItem>
|
||||
:
|
||||
null
|
||||
}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
);
|
||||
|
||||
@@ -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[
|
||||
</div>
|
||||
|
||||
{action === 'EDIT' && <FormClient data={selectedData} onCancel={handleClose} onSuccess={() => { router.refresh(); handleClose() }} />}
|
||||
{action === 'DELETE' ? <ConfirmDelete endpoint={`/client/${selectedData?.id}`} onCancel={handleClose} onSuccess={() => { router.refresh(); handleClose() }} /> : null}
|
||||
{action === 'DELETE' ? <ConfirmDeleteWithInput endpoint={`/client/${selectedData?.id}`} onCancel={handleClose} onSuccess={() => { 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}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -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<Props> = ({ }) => {
|
||||
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 (
|
||||
<div className='flex flex-col sm:flex-row justify-between items-center gap-5'>
|
||||
<div className='flex flex-col sm:flex-row items-center gap-5 w-full sm:w-auto'>
|
||||
<div className="relative w-full sm:w-64">
|
||||
<Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
|
||||
<Input
|
||||
placeholder="Search..."
|
||||
className="pl-10 w-full bg-white dark:bg-zinc-900"
|
||||
value={searchText} // ✅ Controlled by local state for snappy typing
|
||||
onChange={(e) => setSearchText(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<MultiSelect
|
||||
className='w-full sm:w-72 dark:bg-zinc-900'
|
||||
placeholder='Select status'
|
||||
value={currentStatus ? currentStatus.split(',') : []}
|
||||
onChange={handleStatusChange}
|
||||
options={STATUS_LIST.map((item) => ({ label: item, value: item }))}
|
||||
maxCount={1}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Select value={currentSort} onValueChange={handleSortChange}>
|
||||
<SelectTrigger className="w-full md:w-max bg-white dark:bg-zinc-900">
|
||||
<SelectValue placeholder="Sort by" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="default">Default</SelectItem>
|
||||
<SelectItem value="latest">Latest</SelectItem>
|
||||
<SelectItem value="oldest">Oldest</SelectItem>
|
||||
<SelectItem value="participants_desc">Most Participants</SelectItem>
|
||||
<SelectItem value="participants_asc">Fewest Participants</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default FilterComponent;
|
||||
@@ -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<typeof validationSchema>;
|
||||
|
||||
|
||||
const ManageEmployee: FC<Props> = ({ title, onCancel, onSuccess }) => {
|
||||
const [selectedEmployeeIds, setSelectedEmployeeIds] = useState<number[]>([]);
|
||||
const [isLoading, setIsLoading] = useState(false)
|
||||
|
||||
const { data, isLoading: isLoadingFetchUser } = useFetchWithAxios('/user')
|
||||
|
||||
const form = useForm<FormDataType>({
|
||||
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 (
|
||||
<>
|
||||
<AlertDialog open={true}>
|
||||
<AlertDialogContent className="max-w-md">
|
||||
<AlertDialogContent className='max-h-[90vh] overflow-y-auto overflow-x-hidden'>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>Manage Team</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
Assign or remove employees for <strong>{title}</strong>
|
||||
Assign employees for <strong>{title}</strong>
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<div className="grid gap-4 py-4 max-h-[400px] overflow-y-auto pr-2">
|
||||
@@ -57,35 +103,68 @@ const ManageEmployee: FC<Props> = ({ title, onCancel, onSuccess }) => {
|
||||
<Skeleton className='h-10 w-full' />
|
||||
</div>
|
||||
:
|
||||
data?.user?.map((emp: IUser) => (
|
||||
<div
|
||||
key={emp.id}
|
||||
className={cn(
|
||||
"flex items-center gap-4 p-3 rounded-xl border-2 transition-all cursor-pointer",
|
||||
selectedEmployeeIds.includes(emp.id) ? "border-primary bg-primary/5" : "border-transparent hover:bg-accent"
|
||||
)}
|
||||
onClick={() => toggleEmployee(emp.id)}
|
||||
>
|
||||
<div className="relative">
|
||||
<LazyImage src={emp.avatar} alt={emp.fullname} className="w-10 h-10 rounded-full object-cover" />
|
||||
{selectedEmployeeIds.includes(emp.id) &&
|
||||
<div className="absolute -top-1 -right-1 w-4 h-4 bg-primary rounded-full flex items-center justify-center text-white border-2 border-background">
|
||||
<Check className="w-2 h-2" />
|
||||
</div>
|
||||
}
|
||||
<Form {...form}>
|
||||
<form onSubmit={form.handleSubmit(onSubmit)}>
|
||||
<div className="grid grid-cols-1 gap-4 mb-6">
|
||||
<FormField control={form.control} name='user_id'
|
||||
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'
|
||||
// --- 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} />
|
||||
<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>
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="font-bold text-sm truncate">{emp.fullname}</p>
|
||||
<p className="text-xs text-muted-foreground truncate">{emp.position}</p>
|
||||
</div>
|
||||
</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>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel onClick={onCancel} disabled={isLoading}>Cancel</AlertDialogCancel>
|
||||
<Button type='submit' disabled={isLoading}>{isLoading ? <Loader2 /> : null} Save Changes</Button>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</>
|
||||
|
||||
@@ -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 (
|
||||
<div className="flex-1 space-y-8 p-6 sm:p-8 pt-6">
|
||||
|
||||
|
||||
Reference in New Issue
Block a user