update UI logic

This commit is contained in:
Ichsan Kurniawan
2026-04-21 19:30:45 +07:00
parent b5735a90c4
commit 60d1af3758
13 changed files with 243 additions and 261 deletions
@@ -1,4 +1,3 @@
// app/task/client-detail/[clientId]/project-assignments-client.tsx
"use client"
import { useState } from 'react';
@@ -12,7 +11,6 @@ import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";
import Link from 'next/link';
import { DUMMY_EMPLOYEES } from '../../../types';
import { LazyImage } from '@/components/ui/lazy-image';
import { IProjectAssignment } from '../../../type.assignment';
import ManageEmployee from '../../../component/ManageEmployee';
@@ -24,10 +22,10 @@ import { ConfirmDeleteWithInput } from '@/components/modal/ConfirmDeleteWithInpu
interface Props {
clientId: string;
initialAssignments: IProjectAssignment[];
assignmentLists: IProjectAssignment[];
}
export default function ClientDetailComponent({ clientId, initialAssignments }: Props) {
export default function ClientDetailComponent({ clientId, assignmentLists }: Props) {
const [viewMode, setViewMode] = useState<'grid' | 'table'>('grid');
const [action, setAction] = useState<'MANAGE_EMPLOYEE' | 'UPDATE_STATUS' | 'DELETE' | undefined>()
const [selectedData, setSelectedData] = useState<IProjectAssignment>()
@@ -57,7 +55,7 @@ export default function ClientDetailComponent({ clientId, initialAssignments }:
</TabsList>
</Tabs>
<Badge variant="outline" className="px-3 py-1">
{initialAssignments.length} Total
{assignmentLists.length} Total
</Badge>
</div>
</div>
@@ -66,7 +64,7 @@ export default function ClientDetailComponent({ clientId, initialAssignments }:
<FilterComponent />
{/* --- EMPTY STATE --- */}
{initialAssignments.length === 0 ?
{assignmentLists.length === 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">
@@ -83,11 +81,11 @@ export default function ClientDetailComponent({ clientId, initialAssignments }:
</Link>
</CardContent>
</Card>
: viewMode === 'grid' ?
: viewMode === 'grid' ?
/* --- GRID VIEW --- */
<div className="grid gap-4">
{initialAssignments.map((assignment) => {
{assignmentLists.map((assignment) => {
const isProject = assignment.project?.code
const assignmentType = isProject ? 'Project' : 'IM'
@@ -130,14 +128,10 @@ export default function ClientDetailComponent({ clientId, initialAssignments }:
}
{assignment.wo_name &&
<p className="text-sm font-medium text-primary mb-1">
WO: {assignment.wo_name}
</p>
<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}
</p>
<p className="text-muted-foreground line-clamp-2 text-sm mb-4">{assignmentDesc}</p>
<div className="flex flex-wrap items-center gap-6 text-sm text-muted-foreground">
<div className="flex items-center gap-2">
@@ -150,18 +144,17 @@ export default function ClientDetailComponent({ clientId, initialAssignments }:
<div className="flex items-center gap-2">
<Users className="w-4 h-4" />
<div className="flex -space-x-2">
{assignment?.project_assignment_work_order_detail?.slice(0, 3).map(empId => {
const emp = DUMMY_EMPLOYEES.find(e => e.id === empId);
{assignment?.project_assignment_work_order_detail?.map((user, key) => {
return (
<div key={empId}>
<div key={key}>
<Tooltip>
<TooltipTrigger asChild>
<LazyImage src={emp?.avatar!} alt={emp?.name!} className="w-6 h-6 rounded-full border-2 border-background cursor-help" />
<TooltipTrigger>
<LazyImage src={user?.user.avatar ? `${process.env.BASE_URL_IMG}/${user?.user.avatar}` : '/assets/no-avatar.jpg'} alt={user?.user.fullname!} className="w-6 h-6 rounded-full border-2 border-background cursor-help hover:scale-110 hover:z-10 transition-transform" />
</TooltipTrigger>
<TooltipContent>
<div className="text-xs">
<p className="font-bold">{emp?.name}</p>
<p className="opacity-80">{emp?.role}</p>
<p className="font-bold">{user?.user.fullname}</p>
<p className="opacity-80">{user?.user.role?.name}</p>
</div>
</TooltipContent>
</Tooltip>
@@ -197,7 +190,7 @@ export default function ClientDetailComponent({ clientId, initialAssignments }:
<DropdownMenuItem asChild>
<Link href={`${clientId}/project-assignments?is_edit=true&assignment_id=${assignment.id}`}>Edit Assignment</Link>
</DropdownMenuItem>
<DropdownMenuItem onClick={(e) => e.stopPropagation()} onSelect={() => { setSelectedData(assignment); setAction('MANAGE_EMPLOYEE') }}>Manage Employees</DropdownMenuItem>
<DropdownMenuItem onClick={(e) => e.stopPropagation()} onSelect={() => { setSelectedData(assignment); setAction('MANAGE_EMPLOYEE') }}>Manage Team</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>
@@ -210,8 +203,8 @@ export default function ClientDetailComponent({ clientId, initialAssignments }:
)
})}
</div>
:
:
/* --- TABLE VIEW --- */
<Card className="overflow-hidden">
<div className="overflow-x-auto">
@@ -234,12 +227,13 @@ export default function ClientDetailComponent({ clientId, initialAssignments }:
<TableHead>WO Code</TableHead>
<TableHead>WO Start</TableHead>
<TableHead>WO End</TableHead>
<TableHead>Team</TableHead>
<TableHead>Status</TableHead>
<TableHead className="w-[50px]"></TableHead>
</TableRow>
</TableHeader>
<TableBody>
{initialAssignments.map((assignment) => {
{assignmentLists.map((assignment) => {
return (
<TableRow key={assignment.id}>
<TableCell className="font-medium">{assignment.im_name}</TableCell>
@@ -278,6 +272,33 @@ export default function ClientDetailComponent({ clientId, initialAssignments }:
<TableCell className="whitespace-nowrap">
{assignment.wo_end_date ? new Date(assignment.wo_end_date).toLocaleDateString() : ''}
</TableCell>
<TableCell>
<div className="flex -space-x-2">
{assignment?.project_assignment_work_order_detail?.map((user, key) => {
return (
<div key={key}>
<Tooltip>
<TooltipTrigger>
<LazyImage src={user?.user.avatar ? `${process.env.BASE_URL_IMG}/${user?.user.avatar}` : '/assets/no-avatar.jpg'} alt={user?.user.fullname!} className="w-6 h-6 rounded-full border-2 border-background cursor-help hover:scale-110 hover:z-10 transition-transform" />
</TooltipTrigger>
<TooltipContent>
<div className="text-xs">
<p className="font-bold">{user?.user.fullname}</p>
<p className="opacity-80">{user?.user.role?.name}</p>
</div>
</TooltipContent>
</Tooltip>
</div>
);
})}
{assignment.project_assignment_work_order_detail?.length > 3 && (
<div className="w-6 h-6 rounded-full bg-accent border-2 border-background flex items-center justify-center text-[10px] font-bold">
+{assignment.project_assignment_work_order_detail?.length - 3}
</div>
)}
{assignment.project_assignment_work_order_detail && assignment.project_assignment_work_order_detail.length === 0 && <span>No employees assigned</span>}
</div>
</TableCell>
<TableCell>
<BadgeStatus status={assignment.project?.status || assignment.project_status.name} />
</TableCell>
@@ -302,7 +323,7 @@ export default function ClientDetailComponent({ clientId, initialAssignments }:
<DropdownMenuItem asChild>
<Link href={`${clientId}/project-assignments?is_edit=true&assignment_id=${assignment.id}`}>Edit Assignment</Link>
</DropdownMenuItem>
<DropdownMenuItem onClick={(e) => e.stopPropagation()} onSelect={() => { setSelectedData(assignment); setAction('MANAGE_EMPLOYEE') }}>Add Team</DropdownMenuItem>
<DropdownMenuItem onClick={(e) => e.stopPropagation()} onSelect={() => { setSelectedData(assignment); setAction('MANAGE_EMPLOYEE') }}>Manage 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>
@@ -277,7 +277,7 @@ export default function ClientDetailPage({ params }: Props) {
</DropdownMenuItem>
<DropdownMenuItem>Edit Assignment</DropdownMenuItem>
<DropdownMenuItem onClick={() => handleOpenEmployeeDialog(assignment)}>
Manage Employees
Manage Team
</DropdownMenuItem>
<DropdownMenuItem className="text-destructive">Archive</DropdownMenuItem>
</DropdownMenuContent>
@@ -354,7 +354,7 @@ export default function ClientDetailPage({ params }: Props) {
</DropdownMenuItem>
<DropdownMenuItem>Edit Assignment</DropdownMenuItem>
<DropdownMenuItem onClick={() => handleOpenEmployeeDialog(assignment)}>
Manage Employees
Manage Team
</DropdownMenuItem>
<DropdownMenuItem className="text-destructive">Archive</DropdownMenuItem>
</DropdownMenuContent>
@@ -124,7 +124,7 @@ export default async function ClientDetailPage({ params, searchParams }: Props)
{/* Pass the server-fetched data as props */}
<ClientDetailComponent
clientId={client_id}
initialAssignments={filterData()}
assignmentLists={filterData()}
/>
</div>
@@ -2,7 +2,7 @@
"use client"
import { motion } from 'motion/react';
import { ArrowLeft, Briefcase, Calendar, CheckCircle2, History, AlertCircle, UserPlus, ExternalLink } from 'lucide-react';
import { ArrowLeft, Briefcase, Calendar, CheckCircle2, History, AlertCircle, UserPlus, ExternalLink, Mail, Phone } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle, CardDescription, Card900 } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
@@ -17,6 +17,9 @@ import FormUpdateStatus from '../../../component/FormUpdateStatus';
import BadgeStatus from '@/components/ui/badge-status';
import Link from 'next/link';
import ManageEmployee from '../../../component/ManageEmployee';
import dayjs from 'dayjs';
import { LazyImage } from '@/components/ui/lazy-image';
import AssignedPeople from '../project-detail/[project_id]/AssignedPeople';
interface Props {
client: IClient | undefined;
@@ -147,13 +150,13 @@ export default function AssignmentDetail({ client, initialAssignment: assignment
</h2>
</div>
{!assignment.wo_name ? (
{!assignment.wo_name ?
<Card className="border-dashed bg-accent/10">
<CardContent className="py-10 text-center text-muted-foreground">
No work orders defined for this assignment.
</CardContent>
</Card>
) : (
:
<div className="grid gap-4">
<Card900 className="overflow-hidden border-l-4 border-l-primary">
<CardContent className="p-6">
@@ -175,37 +178,22 @@ export default function AssignmentDetail({ client, initialAssignment: assignment
</div>
</div>
{/* WO Status History Mini-Timeline */}
{assignment.project_assignment_status_detail && assignment.project_assignment_status_detail.length > 0 && (
<div className="mt-6 pt-6 border-t">
<div className='flex items-center justify-between'>
<p className="text-xs font-bold uppercase text-muted-foreground mb-4">Team</p>
<Button variant="outline" onClick={() => setAction('MANAGE_EMPLOYEE')} className="gap-2">
<UserPlus className="w-4 h-4" />
Add Team
</Button>
</div>
<div className="space-y-4">
{assignment.project_assignment_work_order_detail && assignment.project_assignment_work_order_detail.length === 0 && <span className='text-muted-foreground'>No employees assigned</span>}
{assignment.project_assignment_work_order_detail.map((history) => (
<div key={history.id} className="flex gap-3 text-sm">
<div className="w-2 h-2 rounded-full bg-primary mt-1.5 shrink-0" />
<div>
<div className="flex items-center gap-2">
<span className="font-bold">{history.status}</span>
<span className="text-muted-foreground text-xs">{new Date(history.date_status_changed).toLocaleDateString()}</span>
</div>
<p className="text-muted-foreground text-xs mt-0.5">{history.status_remarks}</p>
</div>
</div>
))}
</div>
<div className="mt-6 pt-6 border-t">
<div className='flex items-center justify-between'>
<p className="text-xs font-bold uppercase text-muted-foreground mb-4">Team</p>
<Button variant="outline" onClick={() => setAction('MANAGE_EMPLOYEE')} className="gap-2">
<UserPlus className="w-4 h-4" />
Manage Team
</Button>
</div>
)}
</div>
<AssignedPeople people={assignment.project_assignment_work_order_detail} />
</CardContent>
</Card900>
</div>
)}
}
</div>
</div>
@@ -231,12 +219,12 @@ export default function AssignmentDetail({ client, initialAssignment: assignment
<Badge variant={idx === 0 ? "default" : "outline"} className="text-[10px] h-5">
{history.status}
</Badge>
<span className="text-[10px] text-muted-foreground font-mono">
<span className="text-xs text-muted-foreground font-mono">
{new Date(history.date_status_changed).toLocaleDateString()}
</span>
</div>
<p className="text-sm font-medium">{history.status_remarks}</p>
<p className="text-[10px] text-muted-foreground">
<p className="text-xs text-muted-foreground">
Recorded: {new Date(history.created_at!).toLocaleString()}
</p>
</div>
@@ -114,13 +114,13 @@ export default function CreateAssignmentForm({ client, clientId, projectList, is
setIsFullLoading(false)
if (res.success) {
const data: IProjectAssignment = res.data.data
form.setValue('type', data.project.code ? 'Project' : 'IM')
form.setValue('name', data.project.name || data.im_name)
form.setValue('code', data.project.code || data.im_code)
form.setValue('year', data.project.year || data.im_year)
form.setValue('startDate', data.project.start_date || data.im_start_date)
form.setValue('endDate', data.project.end_date || data.im_end_date)
form.setValue('description', data.project.description || data.im_description)
form.setValue('type', data.project?.code ? 'Project' : 'IM')
form.setValue('name', data.project?.name || data.im_name)
form.setValue('code', data.project?.code || data.im_code)
form.setValue('year', data.project?.year || data.im_year)
form.setValue('startDate', data.project?.start_date || data.im_start_date)
form.setValue('endDate', data.project?.end_date || data.im_end_date)
form.setValue('description', data.project?.description || data.im_description)
form.setValue('workOrder.name' as any, data.wo_name)
form.setValue('workOrder.code' as any, data.wo_code)
@@ -347,12 +347,12 @@ export default function CreateAssignmentForm({ client, clientId, projectList, is
<CommandItem
key={p.id}
onSelect={() => {
form.setValue('name', p.project?.name, { shouldValidate: true });
form.setValue('code', p.project?.code, { shouldValidate: true });
form.setValue('year', p.project?.year, { shouldValidate: true });
form.setValue('startDate', new Date(p.project?.start_date), { shouldValidate: true });
form.setValue('endDate', new Date(p.project?.end_date), { shouldValidate: true });
form.setValue('description', p.project?.description, { shouldValidate: true });
form.setValue('name', p.project?.name!, { shouldValidate: true });
form.setValue('code', p.project?.code!, { shouldValidate: true });
form.setValue('year', p.project?.year!, { shouldValidate: true });
form.setValue('startDate', new Date(p.project?.start_date!), { shouldValidate: true });
form.setValue('endDate', new Date(p.project?.end_date!), { shouldValidate: true });
form.setValue('description', p.project?.description!, { shouldValidate: true });
setOpenProjectSearch(false);
setIsExistProject(true)
@@ -360,7 +360,7 @@ export default function CreateAssignmentForm({ client, clientId, projectList, is
}}
>
<Check className={cn("mr-2 h-4 w-4", field.value === p.project?.name ? "opacity-100" : "opacity-0")} />
{p?.project.name}
{p?.project?.name!}
</CommandItem>
))}
</CommandGroup>
@@ -1,5 +1,6 @@
import fetchData from "@/lib/fetchData";
import ProjectAssignmentForm from "./ProjectAssignmentForm";
import { IProjectAssignment } from "../../../type.assignment";
type Props = {
params: Promise<{ client_id: string }>
@@ -19,7 +20,7 @@ export default async function CreateAssignmentPage({ params, searchParams }: Pro
return (
<div className="max-w-4xl mx-auto p-6 sm:p-8 pt-6 pb-20">
<ProjectAssignmentForm client={client} clientId={client_id} projectList={projectList || []}
<ProjectAssignmentForm client={client} clientId={client_id} projectList={projectList && projectList.length > 0 ? projectList.filter((item: IProjectAssignment) => item.project?.name) : []}
isEdit={isEdit ? true : false} assignmentId={assignmentId as any}
/>
</div>
@@ -1,52 +1,35 @@
import { ProjectAssignmentWorkOrderDetail } from '@/app/(dashboard)/task/type.assignment';
import { Badge } from '@/components/ui/badge';
import { LazyImage } from '@/components/ui/lazy-image';
import dayjs from 'dayjs';
import { Mail, Phone, Calendar } from 'lucide-react';
interface AssignedPeopleProps {
people: any[];
interface Props {
people: ProjectAssignmentWorkOrderDetail[];
}
const avatarGradients = [
'from-rose-500 to-pink-600',
'from-sky-500 to-blue-600',
'from-amber-500 to-orange-600',
'from-emerald-500 to-green-600',
'from-violet-500 to-purple-600',
'from-cyan-500 to-teal-600',
];
const getInitials = (name: string) =>
name.split(' ').map((n) => n[0]).slice(0, 2).join('').toUpperCase();
const AssignedPeople = ({ people }: AssignedPeopleProps) => {
const AssignedPeople = ({ people }: Props) => {
if (people.length === 0) {
return (
<div className="text-center py-8 text-sm text-muted-foreground bg-muted/40 rounded-lg border border-dashed border-border">
No people assigned yet
<div className="text-center py-8 text-sm text-muted-foreground bg-muted/40 rounded-lg border border-dashed border-border mt-5">
No team assigned yet
</div>
);
}
const formatDate = (date: string) =>
new Date(date).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' });
return (
<div className="space-y-4">
{/* Stacked avatars */}
<div className="flex items-center gap-3">
<div className="flex -space-x-3">
{people.slice(0, 5).map((person, i) => (
<div
key={person.id}
className={`w-10 h-10 rounded-full bg-linear-to-br ${avatarGradients[i % avatarGradients.length]} ring-2 ring-background flex items-center justify-center text-xs font-bold text-white shadow-md hover:scale-110 hover:z-10 transition-transform`}
title={person.name}
>
{getInitials(person.name)}
</div>
))}
{people.length > 5 && (
{people.slice(0, 5).map((user, i) =>
<LazyImage key={i} src={user?.user.avatar ? `${process.env.BASE_URL_IMG}/${user?.user.avatar}` : '/assets/no-avatar.jpg'} alt={user?.user.fullname!} className="w-10 h-10 rounded-full ring-2 ring-background hover:scale-110 hover:z-10 transition-transform" />
)}
{people.length > 5 &&
<div className="w-10 h-10 rounded-full bg-muted ring-2 ring-background flex items-center justify-center text-xs font-bold text-muted-foreground shadow-md">
+{people.length - 5}
</div>
)}
}
</div>
<div className="text-sm">
<p className="font-semibold text-foreground">{people.length} People</p>
@@ -56,32 +39,22 @@ const AssignedPeople = ({ people }: AssignedPeopleProps) => {
{/* Detailed list */}
<div className="space-y-2">
{people.map((person, i) => (
<div
key={person.id}
className="group flex items-center gap-3 p-3 rounded-xl bg-card/40 border border-border/60 hover:border-primary/40 hover:bg-card/80 transition-all"
>
<div
className={`w-11 h-11 shrink-0 rounded-full bg-linear-to-br ${avatarGradients[i % avatarGradients.length]} flex items-center justify-center text-sm font-bold text-white shadow-md`}
>
{getInitials(person.name)}
</div>
{people.map((user, i) => (
<div key={user.id} className="group flex items-center gap-3 p-3 rounded-xl bg-card/40 border border-border/60 hover:border-primary/40 hover:bg-card/80 transition-all">
<LazyImage src={user?.user.avatar ? `${process.env.BASE_URL_IMG}/${user?.user.avatar}` : '/assets/no-avatar.jpg'} alt={user?.user.fullname!} className="w-11 h-11 rounded-full border border-border" />
<div className="flex-1 min-w-0">
<div className="flex items-start gap-2 flex-wrap">
<p className="text-sm font-semibold text-foreground truncate min-w-0">{person.name}</p>
<span className="text-[10px] font-medium uppercase tracking-wider px-2 py-0.5 rounded bg-primary/10 text-primary ring-1 ring-primary/20 whitespace-nowrap">
{person.role}
</span>
<p className="text-sm font-semibold text-foreground truncate min-w-0">{user.user.fullname}</p>
<Badge variant='violet'>{user.user.role?.name}</Badge>
</div>
<div className="flex flex-col sm:flex-row sm:items-center gap-1 sm:gap-3 mt-1 text-xs text-muted-foreground sm:flex-wrap min-w-0">
<span className="inline-flex items-center gap-1 min-w-0">
<Mail className="w-3 h-3 shrink-0" />
<span className="truncate">{person.email}</span>
<span className="truncate">{user.user.email}</span>
</span>
<span className="inline-flex items-center gap-1">
<Phone className="w-3 h-3 shrink-0" />
<span className="font-mono">{person.phone}</span>
<span className="font-mono">{user.user.phone_number}</span>
</span>
</div>
</div>
@@ -92,7 +65,7 @@ const AssignedPeople = ({ people }: AssignedPeopleProps) => {
</span>
<span className="text-xs font-medium text-foreground inline-flex items-center gap-1">
<Calendar className="w-3 h-3" />
{formatDate(person.assigned_date)}
{user.assigned_date ? dayjs(user.assigned_date).format('MMMM DD, YYYY') : 'N/A'}
</span>
</div>
</div>
+11 -11
View File
@@ -13,7 +13,7 @@ import {
import {
Tooltip, TooltipContent, TooltipTrigger,
} from '@/components/ui/tooltip';
import { DUMMY_EMPLOYEES, IClient } from '../types';
import { IClient } from '../types';
import { useState } from 'react';
import { useRouter } from 'next/navigation';
import FormClient from './FormClient';
@@ -48,6 +48,7 @@ export default function ClientGrid({ clients, assignments }: { clients: IClient[
// const woCount = clientAssignments.reduce((acc, a) => acc + a.workOrders.length, 0);
const woCount = client.total_work_order
const assignedEmployeeIds = Array.from(new Set(clientAssignments.flatMap(a => a.assignedEmployees)));
console.log(client)
return (
<motion.div
@@ -106,7 +107,7 @@ export default function ClientGrid({ clients, assignments }: { clients: IClient[
<>
A dedicated team of{" "}
<span className="font-bold text-foreground">{assignedEmployeeIds.length} experts</span> is handling{" "}
<span className="font-bold text-foreground">{woCount} work order{woCount! > 1 ? 's' : ''}</span>{" "}to ensure successful delivery for <span className="italic">{client.endUser}</span>.
<span className="font-bold text-foreground">{woCount} work order{woCount! > 1 ? 's' : ''}</span>{" "}to ensure successful delivery for <span className="italic">{client.end_user_name}</span>.
</>
)}
</>
@@ -118,30 +119,29 @@ export default function ClientGrid({ clients, assignments }: { clients: IClient[
<div className="flex flex-col gap-1">
<span className="text-[10px] uppercase tracking-wider font-semibold text-muted-foreground">Assigned Team</span>
<div className="flex -space-x-2 overflow-hidden">
{assignedEmployeeIds.slice(0, 5).map((empId) => {
const emp = DUMMY_EMPLOYEES.find(e => e.id === empId);
{client.users?.slice(0, 5).map((user, key) => {
return (
<div key={empId}>
<div key={key}>
<Tooltip>
<TooltipTrigger asChild>
<LazyImage src={emp?.avatar!} alt={emp?.name!}
<LazyImage src={user?.avatar!} alt={user?.fullname!}
className="inline-block h-8 w-8 rounded-full ring-2 ring-background object-cover"
/>
</TooltipTrigger>
<TooltipContent>
<p className="text-xs font-bold">{emp?.name}</p>
<p className="text-[10px] opacity-80">{emp?.role}</p>
<p className="text-xs font-bold">{user?.fullname}</p>
<p className="text-[10px] opacity-80">{user?.role?.name}</p>
</TooltipContent>
</Tooltip>
</div>
);
})}
{assignedEmployeeIds.length > 5 && (
{client.users?.length! > 5 && (
<div className="flex h-8 w-8 items-center justify-center rounded-full bg-accent ring-2 ring-background text-[10px] font-bold">
+{assignedEmployeeIds.length - 5}
+{client.users?.length! - 5}
</div>
)}
{assignedEmployeeIds.length === 0 && (
{client.users?.length === 0 && (
<span className="text-[10px] text-muted-foreground italic">No team assigned</span>
)}
</div>
@@ -12,10 +12,15 @@ import { useForm } from 'react-hook-form';
import { IProjectAssignment } from '../type.assignment';
import { DatePicker } from '@/components/ui/datepicker';
import { Loader2 } from 'lucide-react';
import { STATUS_LIST } from '../data';
import { useFetchWithAxios } from '@/lib/axios/useFetch';
import { IStatus } from '../types';
import { Skeleton } from '@/components/ui/skeleton';
import { serverApiCall } from '@/lib/server-api';
import { toast } from 'sonner';
import dayjs from 'dayjs';
const validationSchema = Yup.object().shape({
status: Yup.string().required(),
project_status_id: Yup.string().required(),
date: Yup.date().required('Date is required'),
note: Yup.string().optional().default(''),
});
@@ -32,12 +37,29 @@ type Props = {
const FormUpdateStatus: FC<Props> = ({ title, data, onCancel, onSuccess }) => {
const [isLoading, setIsLoading] = useState(false)
const { data: statusList, isLoading: isLoadingStatus } = useFetchWithAxios('/project-status')
const form = useForm<FormDataType>({
resolver: yupResolver(validationSchema),
});
const onSubmit = async (payload: FormDataType) => {
setIsLoading(true);
const newPayload = {
"project_status_id": Number(payload.project_status_id),
"date": dayjs(payload.date).format('YYYY-MM-DD'),
"note": payload.note,
"remarks": payload.note
}
const res = await serverApiCall('PUT', `/project-assignment/status/${data?.id}`, newPayload)
setIsLoading(false)
if (res.success) {
toast.success('Client saved successfully')
onSuccess!()
} else {
toast.error(`Fail to save client`, { description: `(${res.code || '-'}) ${res.message}` })
}
}
return (
@@ -50,56 +72,66 @@ const FormUpdateStatus: FC<Props> = ({ title, data, onCancel, onSuccess }) => {
Update the current status for <strong>{title}</strong>
</AlertDialogDescription>
</AlertDialogHeader>
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)}>
<div className="grid gap-6 py-4">
<FormField control={form.control} name='status'
render={({ field }) => (
<FormItem>
<FormLabel>Status</FormLabel>
<Select onValueChange={field.onChange} defaultValue={String(field.value)}>
<FormControl>
<SelectTrigger className='w-full'>
<SelectValue placeholder="Select Status" />
</SelectTrigger>
</FormControl>
<SelectContent>
<SelectGroup>
<SelectLabel>Status</SelectLabel>
{STATUS_LIST.map((item, key: number) =>
<SelectItem value={item} key={key}>{item}</SelectItem>
)}
</SelectGroup>
</SelectContent>
</Select>
{isLoadingStatus ?
<div className='space-y-2'>
<Skeleton className='h-10 w-full' />
<Skeleton className='h-10 w-full' />
<Skeleton className='h-10 w-full' />
<Skeleton className='h-10 w-full' />
<Skeleton className='h-10 w-full' />
</div>
:
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)}>
<div className="grid gap-6 py-4">
<FormField control={form.control} name='project_status_id'
render={({ field }) => (
<FormItem>
<FormLabel>Status</FormLabel>
<Select onValueChange={field.onChange} defaultValue={String(field.value)}>
<FormControl>
<SelectTrigger className='w-full'>
<SelectValue placeholder="Select Status" />
</SelectTrigger>
</FormControl>
<SelectContent>
<SelectGroup>
<SelectLabel>Status</SelectLabel>
{statusList.map((item: IStatus, key: number) =>
<SelectItem value={String(item.id)} key={key} className='capitalize'>{item.name}</SelectItem>
)}
</SelectGroup>
</SelectContent>
</Select>
<FormMessage />
</FormItem>
)}
/>
<FormField control={form.control} name='date' render={({ field }) => (
<FormItem className="flex flex-col">
<FormLabel>Start Date</FormLabel>
<DatePicker date={field.value as Date} setDate={field.onChange} />
<FormMessage />
</FormItem>
)}
/>
<FormField control={form.control} name='date' render={({ field }) => (
<FormItem className="flex flex-col">
<FormLabel>Start Date</FormLabel>
<DatePicker date={field.value as Date} setDate={field.onChange} />
<FormMessage />
</FormItem>
)} />
)} />
<FormField control={form.control} name='note' render={({ field }) => (
<FormItem>
<FormLabel>Note / Remarks</FormLabel>
<FormControl>
<Textarea placeholder="Add a note about this status change..." className="min-h-[100px]" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)} />
</div>
<AlertDialogFooter>
<AlertDialogCancel onClick={onCancel} disabled={isLoading}>Cancel</AlertDialogCancel>
<Button type='submit' disabled={isLoading}>{isLoading ? <Loader2 /> : null} Save Changes</Button>
</AlertDialogFooter>
</form>
</Form>
<FormField control={form.control} name='note' render={({ field }) => (
<FormItem>
<FormLabel>Note / Remarks</FormLabel>
<FormControl>
<Textarea placeholder="Add a note about this status change..." className="min-h-[100px]" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)} />
</div>
<AlertDialogFooter>
<AlertDialogCancel onClick={onCancel} disabled={isLoading}>Cancel</AlertDialogCancel>
<Button type='submit' disabled={isLoading}>{isLoading ? <Loader2 /> : null} Save Changes</Button>
</AlertDialogFooter>
</form>
</Form>
}
</AlertDialogContent>
</AlertDialog>
</>
@@ -19,6 +19,7 @@ import { serverApiCall } from '@/lib/server-api';
import { toast } from 'sonner';
import { DatePicker } from '@/components/ui/datepicker';
import { MultiSelectCustomSelection } from '@/components/ui/multi-select-custom-ui';
import dayjs from 'dayjs';
type Props = {
data: IProjectAssignment
@@ -29,42 +30,42 @@ type Props = {
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()
end_date: Yup.date().nullable().min(Yup.ref('start_date'), 'End date cannot be before start date').default(null),
users: Yup.array().of(Yup.number().required("Each item must be a number")).min(1, 'One user must be add').required()
});
type FormDataType = Yup.InferType<typeof validationSchema>;
const ManageEmployee: FC<Props> = ({ title, onCancel, onSuccess }) => {
const [selectedEmployeeIds, setSelectedEmployeeIds] = useState<number[]>([]);
const ManageEmployee: FC<Props> = ({ data, title, onCancel, onSuccess }) => {
const [isLoading, setIsLoading] = useState(false)
const { data, isLoading: isLoadingFetchUser } = useFetchWithAxios('/user')
const { data: userList, 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 onSubmit = async (payload: FormDataType) => {
setIsLoading(true);
let newPayload: any = { ...payload }
const arrData = payload.users.map(item => (
{
"project_assignment_id": data.id,
"user_id": item,
"start_date": dayjs(payload.start_date).format('YYYY-MM-DD'),
"end_date": dayjs(payload.end_date).format('YYYY-MM-DD')
}
))
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)
const submitPayload = {
data: arrData
}
console.log(submitPayload)
const res = await serverApiCall('POST', '/project-assignment/assign-user', submitPayload)
setIsLoading(false)
if (res.success) {
toast.success('Client saved successfully')
@@ -75,13 +76,14 @@ const ManageEmployee: FC<Props> = ({ title, onCancel, onSuccess }) => {
};
const mappedUsers = useMemo(() => {
return data?.user?.map((item: IUser) => ({
return userList?.user?.map((item: IUser) => ({
label: item.fullname,
value: item.id,
originalData: item
})) || []
}, [data])
return (
<>
<AlertDialog open={true}>
@@ -105,7 +107,7 @@ const ManageEmployee: FC<Props> = ({ title, onCancel, onSuccess }) => {
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)}>
<div className="grid grid-cols-1 gap-4 mb-6">
<FormField control={form.control} name='user_id'
<FormField control={form.control} name='users'
render={({ field }) => (
<FormItem>
<FormLabel>Employee to Assign <span className='text-red-600 font-bold'>*</span></FormLabel>
-1
View File
@@ -24,7 +24,6 @@ export default async function ClientsPage({ searchParams }: Props) {
const [allClients, allAssignments] = await Promise.all([getClient, getAssignment]);
console.log(allAssignments)
const filteredClients = getFilteredClients(allClients, query, sortBy)
const filterAssignments = getFilteredAssignments(allAssignments, query, status, sortBy)
+10 -1
View File
@@ -1,3 +1,5 @@
import { IUser } from "@/app/admin/administration/user/component/type"
export interface IProjectAssignment {
id: number
im_code?: any
@@ -17,7 +19,7 @@ export interface IProjectAssignment {
wo_end_date?: string
wo_warranty: any
project_assignment_status_detail: ProjectAssignmentStatusDetail[]
project_assignment_work_order_detail: any[]
project_assignment_work_order_detail: ProjectAssignmentWorkOrderDetail[]
status: Status
created_at: string
}
@@ -65,3 +67,10 @@ export interface Status {
name: string
id: number
}
export interface ProjectAssignmentWorkOrderDetail {
id: number
assigned_date: string
user: IUser
}
+13 -56
View File
@@ -1,3 +1,5 @@
import { IUser } from "@/app/admin/administration/user/component/type";
export type IEndUser = {
id?: string;
name: string;
@@ -20,7 +22,7 @@ export type IClient = {
total_project?: number
total_work_order?: number
total_user_assigned?: number
users?: IEmployee[]
users?: IUser[]
created_at?: string
created_by?: number
updated_at?: string
@@ -29,58 +31,13 @@ export type IClient = {
deleted_by?: number
};
export type IProjectType = 'Project' | 'IM';
export type IStatusUpdate = {
id: string;
status: string;
date: string;
note: string;
createdAt: string;
};
export type IWorkOrder = {
id: string;
projectId: string;
name: string;
description: string;
createdAt: string;
code?: string;
startDate?: string;
endDate?: string;
status: 'Active' | 'Completed' | 'On Hold';
statusHistory: IStatusUpdate[];
};
export type IProjectAssignment = {
id: string;
clientId: string;
type: IProjectType;
name: string;
description: string;
status: 'Active' | 'Completed' | 'On Hold';
statusHistory: IStatusUpdate[];
createdAt: string;
workOrder: IWorkOrder;
assignedEmployees: string[]; // Employee IDs
code?: string;
year?: string;
startDate?: string;
endDate?: string;
};
export type IEmployee = {
id: string;
name: string;
role: string;
avatar: string;
email: string;
};
export const DUMMY_EMPLOYEES: IEmployee[] = [
{ id: 'e1', name: 'John Doe', role: 'Project Manager', avatar: 'https://i.pravatar.cc/150?u=e1', email: 'john@example.com' },
{ id: 'e2', name: 'Jane Smith', role: 'Senior Developer', avatar: 'https://i.pravatar.cc/150?u=e2', email: 'jane@example.com' },
{ id: 'e3', name: 'Mike Johnson', role: 'UI/UX Designer', avatar: 'https://i.pravatar.cc/150?u=e3', email: 'mike@example.com' },
{ id: 'e4', name: 'Sarah Wilson', role: 'QA Engineer', avatar: 'https://i.pravatar.cc/150?u=e4', email: 'sarah@example.com' },
{ id: 'e5', name: 'Alex Brown', role: 'Backend Developer', avatar: 'https://i.pravatar.cc/150?u=e5', email: 'alex@example.com' },
];
export interface IStatus {
id: number
name: string
created_at: string
created_by: any
updated_at: any
updated_by: any
deleted_at: any
deleted_by: any
}