mirror of
https://github.com/ichsankurnia/hats-app.git
synced 2026-12-05 10:56:28 +00:00
Add client & assignment detail UI; update dev env
Introduce client and assignment detail pages and client-side components for the Task dashboard. Adds interactive ClientDetailComponent, AssignmentDetailComponent, page entries (server + dummy variants), project-assignment form, various UI components (AssignmentTable, ClientGrid, ManageEmployee, FormUpdateStatus, ConfirmDelete, LazyImage helper), types and a dummy data hook. Update app/(dashboard)/task/page.tsx to use the new components. Update .env.development to point to dev API endpoints, bump NEXT_PUBLIC_APP_VERSION to v1.2.0 and add NEXT_PUBLIC_S3_IMAGE_URL.
This commit is contained in:
+8
-8
@@ -1,13 +1,11 @@
|
||||
BASE_PATH = ""
|
||||
NEXT_PUBLIC_APP_URL="http://localhost:1209"
|
||||
|
||||
# BASE_URL_API = https://hats-his.nutech-integrasi.com/presence-api/api/v1
|
||||
# BASE_URL_IMG = https://hats-his.nutech-integrasi.com/presence-api/
|
||||
# BASE_URL_API = https://api-hats.hisnutech.my.id/api/v1
|
||||
# BASE_URL_IMG = https://api-hats.hisnutech.my.id/
|
||||
|
||||
# BASE_URL_API = https://his.nutech-integrasi.com/presence-api/api/v1
|
||||
# BASE_URL_IMG = https://his.nutech-integrasi.com/presence-api/
|
||||
BASE_URL_API = https://api-hats.hisnutech.my.id/api/v1
|
||||
BASE_URL_IMG = https://api-hats.hisnutech.my.id/
|
||||
BASE_URL_API = https://api-hats-dev.hisnutech.my.id/api/v1
|
||||
BASE_URL_IMG = https://api-hats-dev.hisnutech.my.id/
|
||||
|
||||
NEXTAUTH_URL = http://localhost:1209
|
||||
# NEXTAUTH_URL = http://localhost:7090/super-apps/api/auth
|
||||
@@ -19,5 +17,7 @@ FIREBASE_APP_ID = "1:422528660020:web:db16e1cba4d357e32f1061"
|
||||
DEVICE_CODE = "40001"
|
||||
NEXT_PUBLIC_HATS_SUPPORT_NAME = "Amalia"
|
||||
NEXT_PUBLIC_HATS_SUPPORT_PHONE = "6285214074002"
|
||||
NEXT_PUBLIC_APP_VERSION = "v1.1.2"
|
||||
NEXT_PUBLIC_MANAGER_USER_ID = '2'
|
||||
NEXT_PUBLIC_APP_VERSION = "v1.2.0"
|
||||
NEXT_PUBLIC_MANAGER_USER_ID = '2'
|
||||
|
||||
NEXT_PUBLIC_S3_IMAGE_URL = https://cdn.hisnutech.my.id/public
|
||||
@@ -0,0 +1,305 @@
|
||||
// app/task/client-detail/[clientId]/project-assignments-client.tsx
|
||||
"use client"
|
||||
|
||||
import { useState } from 'react';
|
||||
import { motion } from 'motion/react';
|
||||
import { Briefcase, Clock, Users, MoreVertical, Check, Calendar as CalendarIcon, LayoutGrid, Table as TableIcon } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Card, Card900, CardContent } from '@/components/ui/card';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from '@/components/ui/dropdown-menu';
|
||||
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';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import FormUpdateStatus from '../../../component/FormUpdateStatus';
|
||||
|
||||
interface Props {
|
||||
clientId: string;
|
||||
initialAssignments: IProjectAssignment[];
|
||||
}
|
||||
|
||||
export default function ClientDetailComponent({ clientId, initialAssignments }: Props) {
|
||||
const [viewMode, setViewMode] = useState<'grid' | 'table'>('grid');
|
||||
const [action, setAction] = useState<'MANAGE_EMPLOYEE' | 'UPDATE_STATUS' | undefined>()
|
||||
const [selectedData, setSelectedData] = useState<IProjectAssignment>()
|
||||
|
||||
const router = useRouter()
|
||||
|
||||
// Call Server Action (this will automatically refresh the server data if you use revalidatePath in the action)
|
||||
const handleClose = () => {
|
||||
setSelectedData(undefined)
|
||||
setAction(undefined)
|
||||
}
|
||||
|
||||
const handleSuccess = () => {
|
||||
router.refresh()
|
||||
handleClose()
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-2">
|
||||
<h2 className="text-2xl font-bold">Project Assignments</h2>
|
||||
<div className="flex items-center gap-4">
|
||||
<Tabs value={viewMode} onValueChange={(v) => setViewMode(v as 'grid' | 'table')}>
|
||||
<TabsList className="grid w-24 grid-cols-2">
|
||||
<TabsTrigger value="grid" className="p-1"><LayoutGrid className="w-4 h-4" /></TabsTrigger>
|
||||
<TabsTrigger value="table" className="p-1"><TableIcon className="w-4 h-4" /></TabsTrigger>
|
||||
</TabsList>
|
||||
</Tabs>
|
||||
<Badge variant="outline" className="px-3 py-1">
|
||||
{initialAssignments.length} Total
|
||||
</Badge>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* --- EMPTY STATE --- */}
|
||||
{initialAssignments.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">
|
||||
<Briefcase className="w-8 h-8 text-muted-foreground" />
|
||||
</div>
|
||||
<div className="text-center">
|
||||
<h3 className="text-xl font-semibold">No Project Assignments</h3>
|
||||
<p className="text-muted-foreground max-w-xs mx-auto mt-2">
|
||||
This client doesn't have any projects or internal memos yet. Create one to get started.
|
||||
</p>
|
||||
</div>
|
||||
<Link href={`/task/client-detail/${clientId}/project-assignments`}>
|
||||
<Button variant="outline" className="mt-4">Create Assignment</Button>
|
||||
</Link>
|
||||
</CardContent>
|
||||
</Card>
|
||||
: viewMode === 'grid' ?
|
||||
|
||||
/* --- GRID VIEW --- */
|
||||
<div className="grid gap-4">
|
||||
{initialAssignments.map((assignment) => {
|
||||
const isProject = assignment.project.code
|
||||
|
||||
const assignmentType = isProject ? 'Project' : 'IM'
|
||||
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 }}>
|
||||
<Card900 key={assignment.id} className="group hover:border-primary/30 transition-all duration-300">
|
||||
<CardContent className="p-6">
|
||||
<div className="flex items-start justify-between gap-4">
|
||||
<div className="flex items-start gap-4">
|
||||
<div className={`w-12 h-12 rounded-xl flex items-center justify-center shrink-0 ${isProject ? 'bg-orange-500/10 text-orange-500' : 'bg-purple-500/10 text-purple-500'}`}>
|
||||
{isProject ? <Briefcase className="w-6 h-6" /> : <Clock className="w-6 h-6" />}
|
||||
</div>
|
||||
<div>
|
||||
<div className="flex items-center gap-3 mb-1">
|
||||
<h3 className="font-bold text-xl">{assignment.project.name || assignment.im_name}</h3>
|
||||
<Badge variant={isProject ? 'default' : 'info'}>
|
||||
{assignmentType}
|
||||
</Badge>
|
||||
<Badge variant="outline" className={
|
||||
assignmentStatus === 'Active' ? 'text-green-600 border-green-200 bg-green-50' :
|
||||
assignmentStatus === 'Completed' ? 'text-blue-600 border-blue-200 bg-blue-50' :
|
||||
'text-orange-600 border-orange-200 bg-orange-50'
|
||||
}>
|
||||
{assignmentStatus}
|
||||
</Badge>
|
||||
</div>
|
||||
|
||||
{assignment.wo_code && (
|
||||
<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>
|
||||
|
||||
<div className="flex flex-wrap items-center gap-6 text-sm text-muted-foreground">
|
||||
<div className="flex items-center gap-2">
|
||||
<CalendarIcon className="w-4 h-4" />
|
||||
<span>
|
||||
{assignmentStartDate ? new Date(assignmentStartDate).toLocaleDateString() : 'N/A'} -
|
||||
{assignmentEndDate ? new Date(assignmentEndDate).toLocaleDateString() : 'N/A'}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Users className="w-4 h-4" />
|
||||
<div className="flex -space-x-2">
|
||||
{assignment?.users?.slice(0, 3).map(empId => {
|
||||
const emp = DUMMY_EMPLOYEES.find(e => e.id === empId);
|
||||
return (
|
||||
<div key={empId}>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<LazyImage src={emp?.avatar!} alt={emp?.name!} className="w-6 h-6 rounded-full border-2 border-background cursor-help" />
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>
|
||||
<div className="text-xs">
|
||||
<p className="font-bold">{emp?.name}</p>
|
||||
<p className="opacity-80">{emp?.role}</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 && <span>No employees assigned</span>}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="ghost" size="icon">
|
||||
<MoreVertical className="w-5 h-5" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuItem asChild>
|
||||
<Link href={`/task/client-detail/${clientId}/${assignment.id}`}>View Details Assignment</Link>
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem asChild>
|
||||
<Link href={`/task/client-detail/${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>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card900>
|
||||
</motion.div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
:
|
||||
|
||||
/* --- TABLE VIEW --- */
|
||||
<Card className="overflow-hidden">
|
||||
<div className="overflow-x-auto">
|
||||
<Table>
|
||||
<TableHeader className="bg-accent/50">
|
||||
<TableRow>
|
||||
<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-[150px]">Work Order</TableHead>
|
||||
<TableHead>WO Code</TableHead>
|
||||
<TableHead>WO Start</TableHead>
|
||||
<TableHead>WO End</TableHead>
|
||||
<TableHead>Status</TableHead>
|
||||
<TableHead className="w-[50px]"></TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{initialAssignments.map((assignment) => {
|
||||
return (
|
||||
<TableRow key={assignment.id}>
|
||||
<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.im_year || '-'}</TableCell>
|
||||
<TableCell className="whitespace-nowrap">
|
||||
{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() : '-'}
|
||||
</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>
|
||||
<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={
|
||||
assignment.status.name === 'Active' ? 'text-green-600 border-green-200 bg-green-50' :
|
||||
assignment.status.name === 'Completed' ? 'text-blue-600 border-blue-200 bg-blue-50' :
|
||||
'text-orange-600 border-orange-200 bg-orange-50'
|
||||
}>
|
||||
{assignment.status.name}
|
||||
</Badge>
|
||||
</TableCell>
|
||||
<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={`/task/client-detail/${clientId}/${assignment.id}`}>View Details</Link>
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem asChild>
|
||||
<Link href={`/task/client-detail/${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>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
);
|
||||
})}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
</Card>
|
||||
}
|
||||
|
||||
{action === 'MANAGE_EMPLOYEE' ?
|
||||
<ManageEmployee data={selectedData!} title={selectedData?.wo_name || selectedData?.im_name} onCancel={handleClose} onSuccess={handleSuccess} />
|
||||
: null
|
||||
}
|
||||
|
||||
{action === 'UPDATE_STATUS' ?
|
||||
<FormUpdateStatus data={selectedData!} title={selectedData?.wo_name || selectedData?.im_name} onCancel={handleClose} onSuccess={handleSuccess} />
|
||||
: null
|
||||
}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,514 @@
|
||||
"use client"
|
||||
|
||||
import { motion } from 'motion/react';
|
||||
import { ArrowLeft, Plus, Briefcase, Clock, Users, MoreVertical, Check, Calendar as CalendarIcon, LayoutGrid, Table as TableIcon } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Separator } from '@/components/ui/separator';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
import {
|
||||
DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger,
|
||||
} from '@/components/ui/dropdown-menu';
|
||||
import {
|
||||
Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogFooter,
|
||||
} from '@/components/ui/dialog';
|
||||
import {
|
||||
Select, SelectContent, SelectItem, SelectTrigger, SelectValue,
|
||||
} from '@/components/ui/select';
|
||||
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 { use, useState } from 'react';
|
||||
import { toast } from 'sonner';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { DUMMY_EMPLOYEES, IProjectAssignment } from '../../../types';
|
||||
import { useAppState } from '@/hooks/useDummyTaskData';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import Link from 'next/link';
|
||||
|
||||
type Props = {
|
||||
params: Promise<{ client_id: string | undefined }>
|
||||
};
|
||||
|
||||
export default function ClientDetailPage({ params }: Props) {
|
||||
|
||||
const [viewMode, setViewMode] = useState<'grid' | 'table'>('grid');
|
||||
const [statusForm, setStatusForm] = useState({
|
||||
status: 'Active' as IProjectAssignment['status'],
|
||||
note: '',
|
||||
date: new Date().toISOString().split('T')[0]
|
||||
});
|
||||
|
||||
// const { id } = await params;
|
||||
const { client_id } = use(params);
|
||||
const router = useRouter()
|
||||
const { clients, assignments, updateAssignment } = useAppState();
|
||||
|
||||
|
||||
const [editingEmployeesAssignment, setEditingEmployeesAssignment] = useState<IProjectAssignment | null>(null);
|
||||
const [selectedEmployeeIds, setSelectedEmployeeIds] = useState<string[]>([]);
|
||||
|
||||
const [updatingStatusAssignment, setUpdatingStatusAssignment] = useState<IProjectAssignment | null>(null);
|
||||
|
||||
const client = clients.find((c) => c.id === client_id);
|
||||
const clientAssignments = assignments.filter((a) => a.clientId === client_id);
|
||||
|
||||
const handleOpenEmployeeDialog = (assignment: IProjectAssignment) => {
|
||||
setEditingEmployeesAssignment(assignment);
|
||||
setSelectedEmployeeIds(assignment.assignedEmployees);
|
||||
};
|
||||
|
||||
const handleOpenStatusDialog = (assignment: IProjectAssignment) => {
|
||||
setUpdatingStatusAssignment(assignment);
|
||||
setStatusForm({
|
||||
status: assignment.status,
|
||||
note: '',
|
||||
date: new Date().toISOString().split('T')[0]
|
||||
});
|
||||
};
|
||||
|
||||
const toggleEmployee = (empId: string) => {
|
||||
setSelectedEmployeeIds(prev =>
|
||||
prev.includes(empId) ? prev.filter(i => i !== empId) : [...prev, empId]
|
||||
);
|
||||
};
|
||||
|
||||
const handleSaveEmployees = () => {
|
||||
if (editingEmployeesAssignment) {
|
||||
updateAssignment(editingEmployeesAssignment.id, {
|
||||
assignedEmployees: selectedEmployeeIds
|
||||
});
|
||||
toast.success('Team updated successfully');
|
||||
setEditingEmployeesAssignment(null);
|
||||
}
|
||||
};
|
||||
|
||||
const handleSaveStatus = () => {
|
||||
if (updatingStatusAssignment) {
|
||||
updateAssignment(updatingStatusAssignment.id, {
|
||||
status: statusForm.status
|
||||
});
|
||||
// In a real app we would save the note and date to a history log
|
||||
toast.success(`Status updated to ${statusForm.status}`);
|
||||
setUpdatingStatusAssignment(null);
|
||||
}
|
||||
};
|
||||
|
||||
if (!client) {
|
||||
return (
|
||||
<div className="flex flex-col items-center justify-center h-[60vh] space-y-4">
|
||||
<h2 className="text-2xl font-bold">Client not found</h2>
|
||||
<Button onClick={() => router.replace('/task')} variant='outline'>Back to Clients</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<motion.div
|
||||
initial={{ opacity: 0 }}
|
||||
animate={{ opacity: 1 }}
|
||||
exit={{ opacity: 0 }}
|
||||
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">
|
||||
<div className="flex items-start gap-6">
|
||||
<motion.div
|
||||
initial={{ scale: 0.8, opacity: 0 }}
|
||||
animate={{ scale: 1, opacity: 1 }}
|
||||
className="w-24 h-24 rounded-2xl overflow-hidden shadow-xl border-4 border-background"
|
||||
>
|
||||
<img src={client.imageUrl} alt={client.name} className="w-full h-full object-cover" />
|
||||
</motion.div>
|
||||
<div className="space-y-1">
|
||||
<Button variant="ghost" size="sm" className="p-0 h-auto hover:bg-transparent text-muted-foreground mb-2" onClick={() => router.replace('/task')}>
|
||||
<ArrowLeft className="w-4 h-4 mr-1" />
|
||||
Back to Clients
|
||||
</Button>
|
||||
<h1 className="text-4xl font-bold tracking-tight">{client.name}</h1>
|
||||
<p className="text-lg text-muted-foreground">End User: {client.endUser}</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex gap-3">
|
||||
<Link href={`/task/client-detail/${client_id}/project-assignments`} className='w-full sm:w-max'>
|
||||
<Button className="gap-2 w-full">
|
||||
<Plus className="w-4 h-4" />
|
||||
Create Project Assignment
|
||||
</Button>
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-8 lg:grid-cols-3">
|
||||
<div className="lg:col-span-2 space-y-6">
|
||||
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-2">
|
||||
<h2 className="text-2xl font-bold">Project Assignments</h2>
|
||||
<div className="flex items-center gap-4">
|
||||
<Tabs value={viewMode} onValueChange={(v) => setViewMode(v as 'grid' | 'table')}>
|
||||
<TabsList className="grid w-24 grid-cols-2">
|
||||
<TabsTrigger value="grid" className="p-1">
|
||||
<LayoutGrid className="w-4 h-4" />
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="table" className="p-1">
|
||||
<TableIcon className="w-4 h-4" />
|
||||
</TabsTrigger>
|
||||
</TabsList>
|
||||
</Tabs>
|
||||
<Badge variant="outline" className="px-3 py-1">
|
||||
{clientAssignments.length} Total
|
||||
</Badge>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{clientAssignments.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">
|
||||
<Briefcase className="w-8 h-8 text-muted-foreground" />
|
||||
</div>
|
||||
<div className="text-center">
|
||||
<h3 className="text-xl font-semibold">No Project Assignments</h3>
|
||||
<p className="text-muted-foreground max-w-xs mx-auto mt-2">
|
||||
This client doesn't have any projects or internal memos yet. Create one to get started.
|
||||
</p>
|
||||
</div>
|
||||
<Link href={`/task/client-detail/${client_id}/project-assignments`}>
|
||||
<Button variant="outline" className="mt-4">Create Assignment</Button>
|
||||
</Link>
|
||||
</CardContent>
|
||||
</Card>
|
||||
) : viewMode === 'grid' ? (
|
||||
<div className="grid gap-4">
|
||||
{clientAssignments?.map((assignment) => (
|
||||
<Card key={assignment.id} className="group hover:border-primary/30 transition-all duration-300">
|
||||
<CardContent className="p-6">
|
||||
<div className="flex items-start justify-between gap-4">
|
||||
<div className="flex items-start gap-4">
|
||||
<div className={`w-12 h-12 rounded-xl flex items-center justify-center shrink-0 ${assignment.type === 'Project' ? 'bg-orange-500/10 text-orange-500' : 'bg-purple-500/10 text-purple-500'
|
||||
}`}>
|
||||
{assignment.type === 'Project' ? <Briefcase className="w-6 h-6" /> : <Clock className="w-6 h-6" />}
|
||||
</div>
|
||||
<div>
|
||||
<div className="flex items-center gap-3 mb-1">
|
||||
<h3 className="font-bold text-xl">{assignment.name}</h3>
|
||||
<Badge variant={assignment.type === 'Project' ? 'default' : 'secondary'}>
|
||||
{assignment.type}
|
||||
</Badge>
|
||||
<Badge variant="outline" className={
|
||||
assignment.status === 'Active' ? 'text-green-600 border-green-200 bg-green-50' :
|
||||
assignment.status === 'Completed' ? 'text-blue-600 border-blue-200 bg-blue-50' :
|
||||
'text-orange-600 border-orange-200 bg-orange-50'
|
||||
}>
|
||||
{assignment.status}
|
||||
</Badge>
|
||||
</div>
|
||||
|
||||
{assignment.workOrder && (
|
||||
<p className="text-sm font-medium text-primary mb-1">
|
||||
WO: {assignment.workOrder.name}
|
||||
</p>
|
||||
)}
|
||||
|
||||
<p className="text-muted-foreground line-clamp-2 text-sm mb-4">
|
||||
{assignment.description}
|
||||
</p>
|
||||
|
||||
<div className="flex flex-wrap items-center gap-6 text-sm text-muted-foreground">
|
||||
<div className="flex items-center gap-2">
|
||||
<CalendarIcon className="w-4 h-4" />
|
||||
<span>
|
||||
{assignment.startDate ? new Date(assignment.startDate).toLocaleDateString() : 'N/A'} -
|
||||
{assignment.endDate ? new Date(assignment.endDate).toLocaleDateString() : 'N/A'}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Users className="w-4 h-4" />
|
||||
<div className="flex -space-x-2">
|
||||
{assignment.assignedEmployees.slice(0, 3).map(empId => {
|
||||
const emp = DUMMY_EMPLOYEES.find(e => e.id === empId);
|
||||
return (
|
||||
<div key={empId}>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<img
|
||||
src={emp?.avatar}
|
||||
alt={emp?.name}
|
||||
className="w-6 h-6 rounded-full border-2 border-background cursor-help"
|
||||
/>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>
|
||||
<div className="text-xs">
|
||||
<p className="font-bold">{emp?.name}</p>
|
||||
<p className="opacity-80">{emp?.role}</p>
|
||||
</div>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
{assignment.assignedEmployees.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.assignedEmployees.length - 3}
|
||||
</div>
|
||||
)}
|
||||
{assignment.assignedEmployees.length === 0 && <span>No employees assigned</span>}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="ghost" size="icon">
|
||||
<MoreVertical className="w-5 h-5" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuItem asChild>
|
||||
<Link href={`/task/client-detail/${client_id}/${assignment.id}`}>View Details</Link>
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem>Edit Assignment</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={() => handleOpenEmployeeDialog(assignment)}>
|
||||
Manage Employees
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem className="text-destructive">Archive</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<Card className="overflow-hidden">
|
||||
<div className="overflow-x-auto">
|
||||
<Table>
|
||||
<TableHeader className="bg-accent/50">
|
||||
<TableRow>
|
||||
<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-[150px]">Work Order</TableHead>
|
||||
<TableHead>WO Code</TableHead>
|
||||
<TableHead>WO Start</TableHead>
|
||||
<TableHead>WO End</TableHead>
|
||||
<TableHead>Status</TableHead>
|
||||
<TableHead className="w-[50px]"></TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{clientAssignments.map((assignment) => {
|
||||
const wo = assignment.workOrder;
|
||||
return (
|
||||
<TableRow key={assignment.id}>
|
||||
<TableCell className="font-medium">{assignment.name}</TableCell>
|
||||
<TableCell>{assignment.code || '-'}</TableCell>
|
||||
<TableCell className="max-w-[300px] truncate" title={assignment.description}>
|
||||
{assignment.description}
|
||||
</TableCell>
|
||||
<TableCell>{assignment.year || '-'}</TableCell>
|
||||
<TableCell className="whitespace-nowrap">
|
||||
{assignment.startDate ? new Date(assignment.startDate).toLocaleDateString() : '-'}
|
||||
</TableCell>
|
||||
<TableCell className="whitespace-nowrap">
|
||||
{assignment.endDate ? new Date(assignment.endDate).toLocaleDateString() : '-'}
|
||||
</TableCell>
|
||||
<TableCell>{wo?.name || '-'}</TableCell>
|
||||
<TableCell>{wo?.code || '-'}</TableCell>
|
||||
<TableCell className="whitespace-nowrap">
|
||||
{wo?.startDate ? new Date(wo.startDate).toLocaleDateString() : '-'}
|
||||
</TableCell>
|
||||
<TableCell className="whitespace-nowrap">
|
||||
{wo?.endDate ? new Date(wo.endDate).toLocaleDateString() : '-'}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Badge variant="outline" className={
|
||||
assignment.status === 'Active' ? 'text-green-600 border-green-200 bg-green-50' :
|
||||
assignment.status === 'Completed' ? 'text-blue-600 border-blue-200 bg-blue-50' :
|
||||
'text-orange-600 border-orange-200 bg-orange-50'
|
||||
}>
|
||||
{assignment.status}
|
||||
</Badge>
|
||||
</TableCell>
|
||||
<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={`/task/client-detail/${client_id}/${assignment.id}`}>View Details</Link>
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem>Edit Assignment</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={() => handleOpenEmployeeDialog(assignment)}>
|
||||
Manage Employees
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem className="text-destructive">Archive</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
);
|
||||
})}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
</Card>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="space-y-6">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Client Info</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div>
|
||||
<Label className="text-xs text-muted-foreground uppercase tracking-wider">Client Name</Label>
|
||||
<p className="font-medium">{client.name}</p>
|
||||
</div>
|
||||
<div>
|
||||
<Label className="text-xs text-muted-foreground uppercase tracking-wider">End User</Label>
|
||||
<p className="font-medium">{client.endUser}</p>
|
||||
</div>
|
||||
<Separator />
|
||||
<div>
|
||||
<Label className="text-xs text-muted-foreground uppercase tracking-wider">Created At</Label>
|
||||
<p className="font-medium">{new Date(client?.createdAt)?.toLocaleDateString()}</p>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Quick Stats</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-sm text-muted-foreground">Total Projects</span>
|
||||
<span className="font-bold">{clientAssignments.filter(a => a.type === 'Project').length}</span>
|
||||
</div>
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-sm text-muted-foreground">Total IMs</span>
|
||||
<span className="font-bold">{clientAssignments.filter(a => a.type === 'IM').length}</span>
|
||||
</div>
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-sm text-muted-foreground">Total WOs</span>
|
||||
<span className="font-bold">
|
||||
{clientAssignments.reduce((acc, curr) => acc + curr.workOrders?.length, 0)}
|
||||
</span>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Employee Management Dialog */}
|
||||
<Dialog open={!!editingEmployeesAssignment} onOpenChange={(open) => !open && setEditingEmployeesAssignment(null)}>
|
||||
<DialogContent className="max-w-md">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Manage Team</DialogTitle>
|
||||
<DialogDescription>
|
||||
Assign or remove employees for <strong>{editingEmployeesAssignment?.name}</strong>
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div className="grid gap-4 py-4 max-h-[400px] overflow-y-auto pr-2">
|
||||
{DUMMY_EMPLOYEES.map((emp) => (
|
||||
<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">
|
||||
<img src={emp.avatar} alt={emp.name} 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>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="font-bold text-sm truncate">{emp.name}</p>
|
||||
<p className="text-xs text-muted-foreground truncate">{emp.role}</p>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button variant="ghost" onClick={() => setEditingEmployeesAssignment(null)}>Cancel</Button>
|
||||
<Button onClick={handleSaveEmployees}>Save Changes</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
{/* Status Update Dialog */}
|
||||
<Dialog open={!!updatingStatusAssignment} onOpenChange={(open) => !open && setUpdatingStatusAssignment(null)}>
|
||||
<DialogContent className="max-w-md">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Update Status</DialogTitle>
|
||||
<DialogDescription>
|
||||
Update the current status for <strong>{updatingStatusAssignment?.name}</strong>
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div className="grid gap-6 py-4">
|
||||
<div className="space-y-2">
|
||||
<Label>New Status</Label>
|
||||
<Select
|
||||
value={statusForm.status}
|
||||
onValueChange={(v) => setStatusForm({ ...statusForm, status: v as IProjectAssignment['status'] })}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Select status" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="Active">Active</SelectItem>
|
||||
<SelectItem value="Completed">Completed</SelectItem>
|
||||
<SelectItem value="On Hold">On Hold</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label>Date</Label>
|
||||
<div className="relative">
|
||||
<Input
|
||||
type="date"
|
||||
value={statusForm.date}
|
||||
onChange={(e) => setStatusForm({ ...statusForm, date: e.target.value })}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label>Note / Remarks</Label>
|
||||
<Textarea
|
||||
placeholder="Add a note about this status change..."
|
||||
value={statusForm.note}
|
||||
onChange={(e) => setStatusForm({ ...statusForm, note: e.target.value })}
|
||||
className="min-h-[100px]"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button variant="ghost" onClick={() => setUpdatingStatusAssignment(null)}>Cancel</Button>
|
||||
<Button onClick={handleSaveStatus}>Update Status</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</motion.div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
import { ArrowLeft, Plus } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Card900, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Separator } from '@/components/ui/separator';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import Link from 'next/link';
|
||||
|
||||
import ClientDetailComponent from './ClientDetailComponent';
|
||||
import fetchData from '@/lib/fetchData';
|
||||
import { LazyImage } from '@/components/ui/lazy-image';
|
||||
|
||||
type Props = {
|
||||
params: Promise<{ client_id: string }>
|
||||
};
|
||||
|
||||
export default async function ClientDetailPage({ params }: Props) {
|
||||
const { client_id } = await params;
|
||||
|
||||
const getClientById = fetchData(`/client/${client_id}`)
|
||||
const getAssignmentsByClient = fetchData('/project-assignment')
|
||||
|
||||
const [client, assignmentList] = await Promise.all([getClientById, getAssignmentsByClient]);
|
||||
|
||||
if (!client) {
|
||||
return (
|
||||
<div className="flex flex-col items-center justify-center h-[60vh] space-y-4">
|
||||
<h2 className="text-2xl font-bold">Client not found</h2>
|
||||
<Link href="/task">
|
||||
<Button variant='outline'>Back to Clients</Button>
|
||||
</Link>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
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">
|
||||
<div className="flex items-start gap-6">
|
||||
<div className="w-24 h-24 rounded-2xl overflow-hidden shadow-xl border-4 border-background">
|
||||
<LazyImage src={client.photo!} alt={client.name} className="w-full h-full object-cover" />
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<Link href="/task">
|
||||
<Button variant="ghost" size="sm" className="p-0 h-auto hover:bg-transparent text-muted-foreground mb-2">
|
||||
<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>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex gap-3">
|
||||
<Link href={`/task/client-detail/${client_id}/project-assignments`} className='w-full sm:w-max'>
|
||||
<Button className="gap-2 w-full">
|
||||
<Plus className="w-4 h-4" /> Create Project Assignment
|
||||
</Button>
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-8 lg:grid-cols-3">
|
||||
|
||||
{/* --- INTERACTIVE CLIENT COMPONENT (Grid/Table & Modals) --- */}
|
||||
<div className="lg:col-span-2 space-y-6">
|
||||
{/* Pass the server-fetched data as props */}
|
||||
<ClientDetailComponent
|
||||
clientId={client_id}
|
||||
initialAssignments={assignmentList}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* --- STATIC SERVER SIDEBAR --- */}
|
||||
<div className="space-y-6">
|
||||
<Card900>
|
||||
<CardHeader>
|
||||
<CardTitle>Client Info</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div>
|
||||
<Label className="text-xs text-muted-foreground uppercase tracking-wider">Client Name</Label>
|
||||
<p className="font-medium">{client.name}</p>
|
||||
</div>
|
||||
<div>
|
||||
<Label className="text-xs text-muted-foreground uppercase tracking-wider">End User</Label>
|
||||
<p className="font-medium">{client.end_user_name}</p>
|
||||
</div>
|
||||
<Separator />
|
||||
<div>
|
||||
<Label className="text-xs text-muted-foreground uppercase tracking-wider">Created At</Label>
|
||||
<p className="font-medium">{new Date(client.created_at).toLocaleDateString()}</p>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card900>
|
||||
|
||||
<Card900>
|
||||
<CardHeader>
|
||||
<CardTitle>Quick Stats</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-sm text-muted-foreground">Total Projects</span>
|
||||
<span className="font-bold">{client?.total_project || 0}</span>
|
||||
</div>
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-sm text-muted-foreground">Total IMs</span>
|
||||
<span className="font-bold">{client?.total_im || 0}</span>
|
||||
</div>
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-sm text-muted-foreground">Total WOs</span>
|
||||
<span className="font-bold">{client?.total_work_order || 0}</span>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card900>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
+270
@@ -0,0 +1,270 @@
|
||||
// app/task/client-detail/[client_id]/[assignment_id]/project-detail-client.tsx
|
||||
"use client"
|
||||
|
||||
import { motion } from 'motion/react';
|
||||
import { ArrowLeft, Briefcase, Calendar, CheckCircle2, History, AlertCircle } 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';
|
||||
import { Separator } from '@/components/ui/separator';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { IClient } from '../../../types';
|
||||
import { IProjectAssignment } from '../../../type.assignment';
|
||||
import { useState } from 'react';
|
||||
import FormUpdateStatus from '../../../component/FormUpdateStatus';
|
||||
|
||||
interface Props {
|
||||
client: IClient | undefined;
|
||||
initialAssignment: IProjectAssignment;
|
||||
}
|
||||
|
||||
export default function AssignmentDetail({ client, initialAssignment: assignment }: Props) {
|
||||
const [action, setAction] = useState<'ASSIGNMENT' | 'WO' | undefined>()
|
||||
const [selectedData, setSelectedData] = useState<IProjectAssignment>()
|
||||
|
||||
const router = useRouter();
|
||||
|
||||
const isProject = assignment.project.code
|
||||
const title = isProject ? 'Project Detail' : 'Internal Memo Detail';
|
||||
|
||||
const assignmentType = isProject ? 'Project' : 'IM'
|
||||
const assignmentName = assignment.project.name || assignment.im_name
|
||||
const assignmentCode = assignment.project.code || assignment.im_code
|
||||
const assignmentYear = assignment.project.year || assignment.im_year
|
||||
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 handleClose = () => {
|
||||
setSelectedData(undefined)
|
||||
setAction(undefined)
|
||||
}
|
||||
|
||||
const handleSuccess = () => {
|
||||
router.refresh()
|
||||
handleClose()
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<motion.div
|
||||
initial={{ opacity: 0 }}
|
||||
animate={{ opacity: 1 }}
|
||||
className="flex-1 space-y-8 p-6 sm:p-8 pt-6"
|
||||
>
|
||||
{/* Header */}
|
||||
<div className="flex flex-col md:flex-row md:items-center justify-between gap-6">
|
||||
<div className="space-y-1">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="p-0 h-auto hover:bg-transparent text-muted-foreground mb-2"
|
||||
onClick={() => router.back()}
|
||||
>
|
||||
<ArrowLeft className="w-4 h-4 mr-1" />
|
||||
Back to {client?.name}
|
||||
</Button>
|
||||
<div className="flex items-center gap-3">
|
||||
<h1 className="text-4xl font-bold tracking-tight">{title}</h1>
|
||||
<Badge variant={isProject ? 'default' : 'info'} className="text-lg px-3 py-0">
|
||||
{assignmentType}
|
||||
</Badge>
|
||||
</div>
|
||||
<div className="flex items-center gap-3 mt-2">
|
||||
<h2 className="text-xl font-medium text-muted-foreground">{assignmentName}</h2>
|
||||
</div>
|
||||
<div className="flex items-center gap-4 text-muted-foreground">
|
||||
<p className="flex items-center gap-1">
|
||||
<Briefcase className="w-4 h-4" /> Code: {assignmentCode || 'N/A'}
|
||||
</p>
|
||||
<Separator orientation="vertical" className="h-4" />
|
||||
<p className="flex items-center gap-1">
|
||||
<Calendar className="w-4 h-4" /> Year: {assignmentYear || 'N/A'}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex gap-3">
|
||||
<Button variant="outline" onClick={() => setAction('ASSIGNMENT')} className="gap-2">
|
||||
<History className="w-4 h-4" />
|
||||
Update {assignmentType} Status
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-8 lg:grid-cols-3">
|
||||
{/* Left Column: Details & Work Orders */}
|
||||
<div className="lg:col-span-2 space-y-8">
|
||||
{/* Overview Card */}
|
||||
<Card900>
|
||||
<CardHeader>
|
||||
<CardTitle>Overview</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-6">
|
||||
<div className="grid grid-cols-2 md:grid-cols-4 gap-6">
|
||||
<div>
|
||||
<Label className="text-xs text-muted-foreground uppercase tracking-wider">Current Status</Label>
|
||||
<div className="mt-1">
|
||||
<Badge variant="outline" className={cn(
|
||||
"px-3 py-1",
|
||||
assignmentStatus === 'Active' ? 'text-green-600 border-green-200 bg-green-50' :
|
||||
assignmentStatus === 'Completed' ? 'text-blue-600 border-blue-200 bg-blue-50' :
|
||||
'text-orange-600 border-orange-200 bg-orange-50'
|
||||
)}>
|
||||
{assignmentStatus}
|
||||
</Badge>
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<Label className="text-xs text-muted-foreground uppercase tracking-wider">Start Date</Label>
|
||||
<p className="font-medium mt-1">{assignmentStartDate ? new Date(assignmentStartDate).toLocaleDateString() : 'N/A'}</p>
|
||||
</div>
|
||||
<div>
|
||||
<Label className="text-xs text-muted-foreground uppercase tracking-wider">End Date</Label>
|
||||
<p className="font-medium mt-1">{assignmentEndDate ? new Date(assignmentEndDate).toLocaleDateString() : 'N/A'}</p>
|
||||
</div>
|
||||
<div>
|
||||
<Label className="text-xs text-muted-foreground uppercase tracking-wider">Client</Label>
|
||||
<p className="font-medium mt-1">{client?.name}</p>
|
||||
</div>
|
||||
</div>
|
||||
<Separator />
|
||||
<div>
|
||||
<Label className="text-xs text-muted-foreground uppercase tracking-wider">Description</Label>
|
||||
<p className="mt-2 text-muted-foreground leading-relaxed">{assignmentDesc}</p>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card900>
|
||||
|
||||
{/* Work Orders Section */}
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<h2 className="text-2xl font-bold flex items-center gap-2">
|
||||
<CheckCircle2 className="w-6 h-6 text-primary" /> Work Orders
|
||||
</h2>
|
||||
</div>
|
||||
|
||||
{!assignment.wo_code ? (
|
||||
<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">
|
||||
<div className="flex flex-col md:flex-row justify-between gap-6">
|
||||
<div className="space-y-3 flex-1">
|
||||
<div className="flex items-center gap-3">
|
||||
<h3 className="text-xl font-bold">{assignment.wo_name}</h3>
|
||||
<Badge variant="outline" className={cn(
|
||||
assignment.status.name === 'Active' ? 'text-green-600 border-green-200 bg-green-50' :
|
||||
assignment.status.name === 'Completed' ? 'text-blue-600 border-blue-200 bg-blue-50' :
|
||||
'text-orange-600 border-orange-200 bg-orange-50'
|
||||
)}>
|
||||
{assignment.status.name || 'Active'}
|
||||
</Badge>
|
||||
</div>
|
||||
<p className="text-muted-foreground text-sm">{assignment.wo_description}</p>
|
||||
<div className="flex flex-wrap gap-4 text-xs text-muted-foreground">
|
||||
<span className="flex items-center gap-1">
|
||||
<AlertCircle className="w-3 h-3" /> Code: {assignment.wo_code || 'N/A'}
|
||||
</span>
|
||||
<span className="flex items-center gap-1">
|
||||
<Calendar className="w-3 h-3" />
|
||||
{assignment.wo_start_date ? new Date(assignment.wo_start_date).toLocaleDateString() : 'N/A'} - {assignment.wo_end_date ? new Date(assignment.wo_end_date).toLocaleDateString() : 'N/A'}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-start">
|
||||
<Button variant="outline" size="sm" onClick={() => setAction('WO')}>
|
||||
Update WO Status
|
||||
</Button>
|
||||
</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">
|
||||
<p className="text-xs font-bold uppercase text-muted-foreground mb-4">WO Status History</p>
|
||||
<div className="space-y-4">
|
||||
{assignment.project_assignment_status_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>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card900>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Right Column: Status History */}
|
||||
<div className="space-y-8">
|
||||
<Card900>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<History className="w-5 h-5 text-primary" /> {assignmentType} History
|
||||
</CardTitle>
|
||||
<CardDescription>Timeline of status changes</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="relative space-y-8 before:absolute before:inset-0 before:ml-2.5 before:h-full before:w-0.5 before:-translate-x-px before:bg-accent">
|
||||
{assignment.project_assignment_status_detail?.map((history, idx) => (
|
||||
<div key={history.id} className="relative flex items-start gap-4 pl-8">
|
||||
<div className={cn(
|
||||
"absolute left-0 mt-1 w-5 h-5 rounded-full border-4 border-background z-10",
|
||||
idx === 0 ? "bg-primary" : "bg-muted-foreground/30"
|
||||
)} />
|
||||
<div className="flex-1 space-y-1">
|
||||
<div className="flex items-center justify-between">
|
||||
<Badge variant={idx === 0 ? "default" : "outline"} className="text-[10px] h-5">
|
||||
{history.status}
|
||||
</Badge>
|
||||
<span className="text-[10px] 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">
|
||||
Recorded: {new Date(history.created_at!).toLocaleString()}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
{(!assignment.project_assignment_status_detail || assignment.project_assignment_status_detail.length === 0) && (
|
||||
<p className="text-sm text-muted-foreground italic pl-8">No history recorded yet.</p>
|
||||
)}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card900>
|
||||
</div>
|
||||
</div>
|
||||
</motion.div>
|
||||
|
||||
{action === 'ASSIGNMENT' ?
|
||||
<FormUpdateStatus data={assignment} title={assignmentType} onCancel={handleClose} onSuccess={handleSuccess} />
|
||||
: null
|
||||
}
|
||||
|
||||
{action === 'WO' ?
|
||||
<FormUpdateStatus data={assignment} title={assignment.wo_name} onCancel={handleClose} onSuccess={handleSuccess} />
|
||||
: null
|
||||
}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,420 @@
|
||||
"use client"
|
||||
|
||||
import { motion } from 'motion/react';
|
||||
import {
|
||||
ArrowLeft,
|
||||
Briefcase,
|
||||
Users,
|
||||
Calendar,
|
||||
CheckCircle2,
|
||||
History,
|
||||
AlertCircle
|
||||
} from 'lucide-react';
|
||||
import { use, useState } from 'react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Separator } from '@/components/ui/separator';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogFooter,
|
||||
} from '@/components/ui/dialog';
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/components/ui/select';
|
||||
import { toast } from 'sonner';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { useAppState } from '@/hooks/useDummyTaskData';
|
||||
import { DUMMY_EMPLOYEES, IProjectAssignment, IStatusUpdate } from '../../../types';
|
||||
import Link from 'next/link';
|
||||
|
||||
type Props = {
|
||||
params: Promise<{ client_id: string; assignment_id: string }>
|
||||
};
|
||||
export default function ProjectOrIMDetailPage({ params }: Props) {
|
||||
// const { id } = await params;
|
||||
const { client_id, assignment_id: id } = use(params);
|
||||
|
||||
const router = useRouter();
|
||||
const { assignments, clients, updateAssignment } = useAppState();
|
||||
|
||||
const [updatingStatusType, setUpdatingStatusType] = useState<'assignment' | 'wo' | null>(null);
|
||||
const [targetWoId, setTargetWoId] = useState<string | null>(null);
|
||||
const [statusForm, setStatusForm] = useState({
|
||||
status: 'Active' as IProjectAssignment['status'],
|
||||
note: '',
|
||||
date: new Date().toISOString().split('T')[0]
|
||||
});
|
||||
|
||||
const assignment = assignments.find((a) => a.id === id);
|
||||
const client = clients.find((c) => c.id === assignment?.clientId);
|
||||
|
||||
if (!assignment) {
|
||||
return (
|
||||
<div className="flex flex-col items-center justify-center h-[60vh] space-y-4">
|
||||
<h2 className="text-2xl font-bold">Assignment not found</h2>
|
||||
<Button onClick={() => router.replace('/task')} variant='outline'>Back to Clients</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const title = assignment.type === 'Project' ? 'Project Detail' : 'Internal Memo Detail';
|
||||
|
||||
const handleOpenStatusDialog = (type: 'assignment' | 'wo', woId?: string) => {
|
||||
setUpdatingStatusType(type);
|
||||
setTargetWoId(woId || null);
|
||||
|
||||
const currentStatus = type === 'assignment' ? assignment.status : assignment.workOrder.status || 'Active';
|
||||
|
||||
setStatusForm({
|
||||
status: currentStatus,
|
||||
note: '',
|
||||
date: new Date().toISOString().split('T')[0]
|
||||
});
|
||||
};
|
||||
|
||||
const handleSaveStatus = () => {
|
||||
const newUpdate: IStatusUpdate = {
|
||||
id: Math.random().toString(36).substr(2, 9),
|
||||
status: statusForm.status,
|
||||
date: statusForm.date,
|
||||
note: statusForm.note,
|
||||
createdAt: new Date().toISOString()
|
||||
};
|
||||
|
||||
if (updatingStatusType === 'assignment') {
|
||||
updateAssignment(assignment.id, {
|
||||
status: statusForm.status,
|
||||
statusHistory: [newUpdate, ...(assignment.statusHistory || [])]
|
||||
});
|
||||
toast.success(`Assignment status updated to ${statusForm.status}`);
|
||||
} else if (updatingStatusType === 'wo' && targetWoId) {
|
||||
const updatedWOs = assignment.workOrders.map(wo => {
|
||||
if (wo.id === targetWoId) {
|
||||
return {
|
||||
...wo,
|
||||
status: statusForm.status,
|
||||
statusHistory: [newUpdate, ...(wo.statusHistory || [])]
|
||||
};
|
||||
}
|
||||
return wo;
|
||||
});
|
||||
updateAssignment(assignment.id, { workOrders: updatedWOs });
|
||||
toast.success(`Work Order status updated to ${statusForm.status}`);
|
||||
}
|
||||
|
||||
setUpdatingStatusType(null);
|
||||
setTargetWoId(null);
|
||||
};
|
||||
|
||||
return (
|
||||
<motion.div
|
||||
initial={{ opacity: 0 }}
|
||||
animate={{ opacity: 1 }}
|
||||
className="flex-1 space-y-8 p-6 sm:p-8 pt-6"
|
||||
>
|
||||
{/* Header */}
|
||||
<div className="flex flex-col md:flex-row md:items-center justify-between gap-6">
|
||||
<div className="space-y-1">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="p-0 h-auto hover:bg-transparent text-muted-foreground mb-2"
|
||||
onClick={() => router.back()}
|
||||
>
|
||||
<ArrowLeft className="w-4 h-4 mr-1" />
|
||||
Back to {client?.name}
|
||||
</Button>
|
||||
<div className="flex items-center gap-3">
|
||||
<h1 className="text-4xl font-bold tracking-tight">{title}</h1>
|
||||
<Badge variant={assignment.type === 'Project' ? 'default' : 'secondary'} className="text-lg px-3 py-1">
|
||||
{assignment.type}
|
||||
</Badge>
|
||||
</div>
|
||||
<div className="flex items-center gap-3 mt-2">
|
||||
<h2 className="text-xl font-medium text-muted-foreground">{assignment.name}</h2>
|
||||
</div>
|
||||
<div className="flex items-center gap-4 text-muted-foreground">
|
||||
<p className="flex items-center gap-1">
|
||||
<Briefcase className="w-4 h-4" />
|
||||
Code: {assignment.code || 'N/A'}
|
||||
</p>
|
||||
<Separator orientation="vertical" className="h-4" />
|
||||
<p className="flex items-center gap-1">
|
||||
<Calendar className="w-4 h-4" />
|
||||
Year: {assignment.year || 'N/A'}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex gap-3">
|
||||
<Button variant="outline" onClick={() => handleOpenStatusDialog('assignment')} className="gap-2">
|
||||
<History className="w-4 h-4" />
|
||||
Update {assignment.type} Status
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-8 lg:grid-cols-3">
|
||||
{/* Left Column: Details & Work Orders */}
|
||||
<div className="lg:col-span-2 space-y-8">
|
||||
{/* Overview Card */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Overview</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-6">
|
||||
<div className="grid grid-cols-2 md:grid-cols-4 gap-6">
|
||||
<div>
|
||||
<Label className="text-xs text-muted-foreground uppercase tracking-wider">Current Status</Label>
|
||||
<div className="mt-1">
|
||||
<Badge variant="outline" className={cn(
|
||||
"px-3 py-1",
|
||||
assignment.status === 'Active' ? 'text-green-600 border-green-200 bg-green-50' :
|
||||
assignment.status === 'Completed' ? 'text-blue-600 border-blue-200 bg-blue-50' :
|
||||
'text-orange-600 border-orange-200 bg-orange-50'
|
||||
)}>
|
||||
{assignment.status}
|
||||
</Badge>
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<Label className="text-xs text-muted-foreground uppercase tracking-wider">Start Date</Label>
|
||||
<p className="font-medium mt-1">{assignment.startDate ? new Date(assignment.startDate).toLocaleDateString() : 'N/A'}</p>
|
||||
</div>
|
||||
<div>
|
||||
<Label className="text-xs text-muted-foreground uppercase tracking-wider">End Date</Label>
|
||||
<p className="font-medium mt-1">{assignment.endDate ? new Date(assignment.endDate).toLocaleDateString() : 'N/A'}</p>
|
||||
</div>
|
||||
<div>
|
||||
<Label className="text-xs text-muted-foreground uppercase tracking-wider">Client</Label>
|
||||
<p className="font-medium mt-1">{client?.name}</p>
|
||||
</div>
|
||||
</div>
|
||||
<Separator />
|
||||
<div>
|
||||
<Label className="text-xs text-muted-foreground uppercase tracking-wider">Description</Label>
|
||||
<p className="mt-2 text-muted-foreground leading-relaxed">{assignment.description}</p>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Work Orders Section */}
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<h2 className="text-2xl font-bold flex items-center gap-2">
|
||||
<CheckCircle2 className="w-6 h-6 text-primary" />
|
||||
Work Orders
|
||||
</h2>
|
||||
</div>
|
||||
|
||||
{!assignment.workOrder ? (
|
||||
<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">
|
||||
<Card key={assignment.workOrder?.id} className="overflow-hidden border-l-4 border-l-primary">
|
||||
<CardContent className="p-6">
|
||||
<div className="flex flex-col md:flex-row justify-between gap-6">
|
||||
<div className="space-y-3 flex-1">
|
||||
<div className="flex items-center gap-3">
|
||||
<h3 className="text-xl font-bold">{assignment.workOrder?.name}</h3>
|
||||
<Badge variant="outline" className={cn(
|
||||
assignment.workOrder?.status === 'Active' ? 'text-green-600 border-green-200 bg-green-50' :
|
||||
assignment.workOrder?.status === 'Completed' ? 'text-blue-600 border-blue-200 bg-blue-50' :
|
||||
'text-orange-600 border-orange-200 bg-orange-50'
|
||||
)}>
|
||||
{assignment.workOrder?.status || 'Active'}
|
||||
</Badge>
|
||||
</div>
|
||||
<p className="text-muted-foreground text-sm">{assignment.workOrder?.description}</p>
|
||||
<div className="flex flex-wrap gap-4 text-xs text-muted-foreground">
|
||||
<span className="flex items-center gap-1">
|
||||
<AlertCircle className="w-3 h-3" />
|
||||
Code: {assignment.workOrder?.code || 'N/A'}
|
||||
</span>
|
||||
<span className="flex items-center gap-1">
|
||||
<Calendar className="w-3 h-3" />
|
||||
{assignment.workOrder?.startDate ? new Date(assignment.workOrder?.startDate).toLocaleDateString() : 'N/A'} - {assignment.workOrder?.endDate ? new Date(assignment.workOrder?.endDate).toLocaleDateString() : 'N/A'}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-start">
|
||||
<Button variant="outline" size="sm" onClick={() => handleOpenStatusDialog('wo', assignment.workOrder?.id)}>
|
||||
Update WO Status
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* WO Status History Mini-Timeline */}
|
||||
{assignment.workOrder?.statusHistory && assignment.workOrder?.statusHistory.length > 0 && (
|
||||
<div className="mt-6 pt-6 border-t">
|
||||
<p className="text-xs font-bold uppercase text-muted-foreground mb-4">WO Status History</p>
|
||||
<div className="space-y-4">
|
||||
{assignment.workOrder?.statusHistory.slice(0, 2).map((history, idx) => (
|
||||
<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).toLocaleDateString()}</span>
|
||||
</div>
|
||||
<p className="text-muted-foreground text-xs mt-0.5">{history.note}</p>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Right Column: Status History & Team */}
|
||||
<div className="space-y-8">
|
||||
{/* Project Status History Timeline */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<History className="w-5 h-5 text-primary" />
|
||||
{assignment.type} History
|
||||
</CardTitle>
|
||||
<CardDescription>Timeline of status changes</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="relative space-y-8 before:absolute before:inset-0 before:ml-2.5 before:h-full before:w-0.5 before:-translate-x-px before:bg-accent">
|
||||
{assignment.statusHistory?.map((history, idx) => (
|
||||
<div key={history.id} className="relative flex items-start gap-4 pl-8">
|
||||
<div className={cn(
|
||||
"absolute left-0 mt-1 w-5 h-5 rounded-full border-4 border-background z-10",
|
||||
idx === 0 ? "bg-primary" : "bg-muted-foreground/30"
|
||||
)} />
|
||||
<div className="flex-1 space-y-1">
|
||||
<div className="flex items-center justify-between">
|
||||
<Badge variant={idx === 0 ? "default" : "outline"} className="text-[10px] h-5">
|
||||
{history.status}
|
||||
</Badge>
|
||||
<span className="text-[10px] text-muted-foreground font-mono">
|
||||
{new Date(history.date).toLocaleDateString()}
|
||||
</span>
|
||||
</div>
|
||||
<p className="text-sm font-medium">{history.note}</p>
|
||||
<p className="text-[10px] text-muted-foreground">
|
||||
Recorded: {new Date(history.createdAt).toLocaleString()}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
{(!assignment.statusHistory || assignment.statusHistory.length === 0) && (
|
||||
<p className="text-sm text-muted-foreground italic pl-8">No history recorded yet.</p>
|
||||
)}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Team Card */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<Users className="w-5 h-5 text-primary" />
|
||||
Assigned Team
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="space-y-4">
|
||||
{assignment.assignedEmployees.length === 0 ? (
|
||||
<p className="text-sm text-muted-foreground italic">No employees assigned yet.</p>
|
||||
) : (
|
||||
assignment.assignedEmployees.map(empId => {
|
||||
const emp = DUMMY_EMPLOYEES.find(e => e.id === empId);
|
||||
return (
|
||||
<div key={empId} className="flex items-center gap-3 p-2 rounded-lg hover:bg-accent/50 transition-colors">
|
||||
<img src={emp?.avatar} alt={emp?.name} className="w-10 h-10 rounded-full object-cover" />
|
||||
<div className="min-w-0">
|
||||
<p className="text-sm font-bold truncate">{emp?.name}</p>
|
||||
<p className="text-xs text-muted-foreground truncate">{emp?.role}</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})
|
||||
)}
|
||||
<Separator />
|
||||
<Button variant="ghost" size="sm" className="w-full text-primary hover:text-primary hover:bg-primary/5" asChild>
|
||||
<Link href={`/clients/${client?.id}`}>Manage Team in Client Page</Link>
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Status Update Dialog */}
|
||||
<Dialog open={!!updatingStatusType} onOpenChange={(open) => !open && setUpdatingStatusType(null)}>
|
||||
<DialogContent className="max-w-md">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Update {updatingStatusType === 'assignment' ? assignment.type : 'Work Order'} Status</DialogTitle>
|
||||
<DialogDescription>
|
||||
Record a new status update for this {updatingStatusType === 'assignment' ? (assignment.type === 'Project' ? 'project' : 'memo') : 'work order'}.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div className="grid gap-6 py-4">
|
||||
<div className="space-y-2">
|
||||
<Label>New Status</Label>
|
||||
<Select
|
||||
value={statusForm.status}
|
||||
onValueChange={(v) => setStatusForm({ ...statusForm, status: v as IProjectAssignment['status'] })}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Select status" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="Active">Active</SelectItem>
|
||||
<SelectItem value="Completed">Completed</SelectItem>
|
||||
<SelectItem value="On Hold">On Hold</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label>Date of Change</Label>
|
||||
<Input
|
||||
type="date"
|
||||
value={statusForm.date}
|
||||
onChange={(e) => setStatusForm({ ...statusForm, date: e.target.value })}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label>Note / Remarks</Label>
|
||||
<Textarea
|
||||
placeholder="Explain the reason for this status change..."
|
||||
value={statusForm.note}
|
||||
onChange={(e) => setStatusForm({ ...statusForm, note: e.target.value })}
|
||||
className="min-h-[100px]"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button variant="ghost" onClick={() => setUpdatingStatusType(null)}>Cancel</Button>
|
||||
<Button onClick={handleSaveStatus}>Save Update</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</motion.div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import { Button } from '@/components/ui/button';
|
||||
import Link from 'next/link';
|
||||
import AssignmentDetailComponent from './AssignmentDetailComponent';
|
||||
import fetchData from '@/lib/fetchData';
|
||||
|
||||
type Props = {
|
||||
params: Promise<{ client_id: string; assignment_id: string }>
|
||||
};
|
||||
|
||||
export default async function ProjectOrIMDetailPage({ params }: Props) {
|
||||
const { client_id, assignment_id } = await params;
|
||||
|
||||
const getClientById = fetchData(`/client/${client_id}`)
|
||||
const getAssignmentById = fetchData(`/project-assignment/${assignment_id}`)
|
||||
|
||||
const [client, assignment] = await Promise.all([getClientById, getAssignmentById]);
|
||||
|
||||
// 3. Handle 404 Securely on the server
|
||||
if (!assignment) {
|
||||
return (
|
||||
<div className="flex flex-col items-center justify-center h-[60vh] space-y-4">
|
||||
<h2 className="text-2xl font-bold">Assignment not found</h2>
|
||||
<Link href={`/task/client-detail/${client_id}`}>
|
||||
<Button variant="outline">Back to Client</Button>
|
||||
</Link>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// 4. Pass the fetched data to the interactive Client Component
|
||||
return (
|
||||
<AssignmentDetailComponent client={client} initialAssignment={assignment} />
|
||||
);
|
||||
}
|
||||
+564
@@ -0,0 +1,564 @@
|
||||
"use client"
|
||||
|
||||
import { useState, useEffect } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { yupResolver } from '@hookform/resolvers/yup';
|
||||
import { motion, AnimatePresence } from 'motion/react';
|
||||
import { ArrowLeft, ArrowRight, Save, Briefcase, Clock, Search, Check } from 'lucide-react';
|
||||
|
||||
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from '@/components/ui/form';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
import { Card, CardContent, CardHeader, CardTitle, CardDescription, Card900 } from '@/components/ui/card';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Separator } from '@/components/ui/separator';
|
||||
import {
|
||||
Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList,
|
||||
} from '@/components/ui/command';
|
||||
import {
|
||||
Popover, PopoverContent, PopoverTrigger,
|
||||
} from '@/components/ui/popover';
|
||||
import { DatePicker } from '@/components/ui/datepicker';
|
||||
import { toast } from 'sonner';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import * as yup from 'yup';
|
||||
import { IClient } from '../../../types';
|
||||
import { serverApiCall } from '@/lib/server-api';
|
||||
import dayjs from 'dayjs';
|
||||
import PageLoading from '@/components/loader/PageLoading';
|
||||
import { IProjectAssignment } from '../../../type.assignment';
|
||||
|
||||
type IStep = 'type' | 'details' | 'work-orders' | 'review';
|
||||
|
||||
export const assignmentSchema = yup.object({
|
||||
type: yup.string().oneOf(['Project', 'IM']).required('Project type is required'),
|
||||
|
||||
// Details Step
|
||||
name: yup.string().required('Assignment name is required'),
|
||||
code: yup.string().required('Project code is required'),
|
||||
year: yup.string().required('Year is required'),
|
||||
startDate: yup.date().required('Start date is required'),
|
||||
endDate: yup.date().min(yup.ref('startDate'), 'End date cannot be before start date').required('End date is required'),
|
||||
description: yup.string().optional().nullable().default(''),
|
||||
|
||||
// Work Orders Step (Conditional based on 'type')
|
||||
workOrder: yup.object().when('type', {
|
||||
is: 'Project',
|
||||
then: (schema) => schema.shape({
|
||||
name: yup.string().required('Work order name is required'),
|
||||
code: yup.string().required('Work order code is required'),
|
||||
startDate: yup.date().required('Start date is required'),
|
||||
endDate: yup.date().required('End date is required'),
|
||||
description: yup.string().optional().nullable().default(''),
|
||||
}),
|
||||
otherwise: (schema) => schema.nullable().notRequired()
|
||||
})
|
||||
});
|
||||
|
||||
// Infer the TypeScript type from the Yup schema
|
||||
export type AssignmentFormValues = yup.InferType<typeof assignmentSchema>;
|
||||
|
||||
export default function CreateAssignmentForm({ client, clientId, projectList, isEdit, assignmentId }: { client: IClient, projectList: any[], clientId: string, isEdit?: boolean, assignmentId?: string }) {
|
||||
const [existAssignment, setIsExistAssignment] = useState<IProjectAssignment | null>(null)
|
||||
|
||||
const router = useRouter();
|
||||
|
||||
const [step, setStep] = useState<IStep>('type');
|
||||
const [loading, setIsLoading] = useState(false);
|
||||
const [isFullLoading, setIsFullLoading] = useState(false)
|
||||
const [isExistProject, setIsExistProject] = useState(false)
|
||||
const [openProjectSearch, setOpenProjectSearch] = useState(false);
|
||||
|
||||
// 1. Initialize React Hook Form
|
||||
const form = useForm<AssignmentFormValues>({
|
||||
resolver: yupResolver(assignmentSchema),
|
||||
defaultValues: {
|
||||
type: 'Project',
|
||||
name: '',
|
||||
code: '',
|
||||
year: new Date().getFullYear().toString(),
|
||||
description: '',
|
||||
workOrder: {
|
||||
name: '',
|
||||
code: '',
|
||||
description: '',
|
||||
}
|
||||
},
|
||||
mode: "onChange"
|
||||
});
|
||||
|
||||
// Watch values for dynamic UI rendering
|
||||
const assignmentType = form.watch('type');
|
||||
const formValues = form.watch();
|
||||
|
||||
// 3. Navigation & Validation Logic
|
||||
const steps: { id: IStep; label: string }[] = [
|
||||
{ id: 'type', label: 'Type' },
|
||||
{ id: 'details', label: 'Details' },
|
||||
...(assignmentType === 'Project' ? [{ id: 'work-orders' as IStep, label: 'Work Orders' }] : []),
|
||||
{ id: 'review', label: 'Review' },
|
||||
];
|
||||
|
||||
const currentStepIndex = steps.findIndex(s => s.id === step);
|
||||
|
||||
|
||||
useEffect(() => {
|
||||
if (!isEdit) return
|
||||
|
||||
async function getAssignmentDetail() {
|
||||
setIsFullLoading(true)
|
||||
const res: any = await serverApiCall('GET', `/project-assignment/${assignmentId}`)
|
||||
|
||||
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('workOrder.name' as any, data.wo_name)
|
||||
form.setValue('workOrder.code' as any, data.wo_code)
|
||||
form.setValue('workOrder.startDate' as any, data.wo_start_date)
|
||||
form.setValue('workOrder.endDate' as any, data.wo_end_date)
|
||||
form.setValue('workOrder.description' as any, data.wo_description)
|
||||
|
||||
setStep('details')
|
||||
|
||||
setIsExistAssignment(res.data.data)
|
||||
} else {
|
||||
toast.error('Fail to get detail assignment', {
|
||||
description: `(${res.code || '-'}) ${res.message}`
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
getAssignmentDetail()
|
||||
}, [isEdit, assignmentId])
|
||||
|
||||
const handleNext = async () => {
|
||||
let isStepValid = false;
|
||||
|
||||
if (step === 'type') {
|
||||
isStepValid = await form.trigger(['type']);
|
||||
if (isStepValid) setStep('details');
|
||||
}
|
||||
else if (step === 'details') {
|
||||
isStepValid = await form.trigger(['name', 'code', 'year', 'startDate', 'endDate', 'description']);
|
||||
if (isStepValid) setStep(assignmentType === 'Project' ? 'work-orders' : 'review');
|
||||
}
|
||||
else if (step === 'work-orders') {
|
||||
// Trigger the parent key to validate all nested workOrder fields
|
||||
isStepValid = await form.trigger('workOrder');
|
||||
if (isStepValid) setStep('review');
|
||||
}
|
||||
};
|
||||
|
||||
const handleBack = () => {
|
||||
if (step === 'details') setStep('type');
|
||||
else if (step === 'work-orders') setStep('details');
|
||||
else if (step === 'review') setStep(assignmentType === 'Project' ? 'work-orders' : 'details');
|
||||
};
|
||||
|
||||
// 4. Submission
|
||||
const onSubmit = async (payload: AssignmentFormValues) => {
|
||||
setIsLoading(true);
|
||||
|
||||
const newPayload = {
|
||||
"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,
|
||||
"im_start_date": assignmentType === 'IM' ? dayjs(payload.startDate).format('YYYY-MM-DD') : isEdit ? existAssignment?.im_start_date : "",
|
||||
"im_end_date": assignmentType === 'IM' ? dayjs(payload.endDate).format('YYYY-MM-DD') : isEdit ? existAssignment?.im_end_date : "",
|
||||
"im_description": assignmentType === 'IM' ? payload.description : isEdit ? existAssignment?.im_description : "",
|
||||
|
||||
"project_code": assignmentType === 'Project' ? payload.code : '',
|
||||
"project_name": assignmentType === 'Project' ? payload.name : '',
|
||||
"project_year": assignmentType === 'Project' ? Number(payload.year) : 2026,
|
||||
"project_start_date": assignmentType === 'Project' ? dayjs(payload.startDate).format('YYYY-MM-DD') : '',
|
||||
"project_end_date": assignmentType === 'Project' ? dayjs(payload.endDate).format('YYYY-MM-DD') : '',
|
||||
"project_description": assignmentType === 'Project' ? payload.description : '',
|
||||
"project_status_id": isEdit ? existAssignment?.project_status.id : 1,
|
||||
|
||||
"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 ? dayjs((payload.workOrder as any).endDate).format('YYYY-MM-DD') : '',
|
||||
"wo_description": (payload.workOrder as any).description,
|
||||
"wo_warranty": isEdit ? existAssignment?.wo_warranty : '2026-04-16',
|
||||
|
||||
"note": isEdit ? existAssignment?.note : "",
|
||||
}
|
||||
|
||||
let res: any
|
||||
if (isEdit) {
|
||||
res = await serverApiCall('PUT', `/project-assignment/${assignmentId}`, newPayload)
|
||||
} else {
|
||||
res = await serverApiCall('POST', '/project-assignment', newPayload)
|
||||
}
|
||||
|
||||
setIsLoading(false)
|
||||
if (res.success) {
|
||||
toast.success(`${payload.type} saved successfully`);
|
||||
router.replace(`/task/client-detail/${clientId}`);
|
||||
} else {
|
||||
toast.error(`Fail to save assignment`, { description: `(${res.code || '-'}) ${res.message}` })
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<Form {...form}>
|
||||
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-8">
|
||||
|
||||
{/* --- HEADER --- */}
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-4">
|
||||
<Button type="button" variant="ghost" size="icon" onClick={() => router.back()}>
|
||||
<ArrowLeft className="w-5 h-5" />
|
||||
</Button>
|
||||
<div>
|
||||
<h1 className="text-3xl font-bold">Create Project Assignment</h1>
|
||||
<p className="text-muted-foreground">For {client.name}</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* --- STEPPER --- */}
|
||||
<div className="flex items-center justify-between px-2">
|
||||
{steps.map((s, i) => (
|
||||
<div key={s.id} className="flex items-center flex-1 last:flex-none">
|
||||
<div className="flex flex-col items-center gap-2">
|
||||
<div className={cn(
|
||||
"w-10 h-10 rounded-full flex items-center justify-center border-2 transition-all duration-300",
|
||||
i <= currentStepIndex ? "bg-zinc-900 dark:bg-zinc-100 border-primary text-secondary" : "border-border text-muted-foreground"
|
||||
)}>
|
||||
{i < currentStepIndex ? <Check className="w-5 h-5" /> : <span>{i + 1}</span>}
|
||||
</div>
|
||||
<span className={cn(
|
||||
"text-xs font-medium hidden md:block",
|
||||
i <= currentStepIndex ? "text-primary" : "text-muted-foreground"
|
||||
)}>{s.label}</span>
|
||||
</div>
|
||||
{i < steps.length - 1 && (
|
||||
<div className={cn(
|
||||
"h-0.5 flex-1 mx-4 transition-all duration-500",
|
||||
i < currentStepIndex ? "bg-primary" : "bg-border"
|
||||
)} />
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* --- FORM CONTENT --- */}
|
||||
<AnimatePresence mode="wait">
|
||||
<motion.div
|
||||
key={step}
|
||||
initial={{ opacity: 0, x: 20 }}
|
||||
animate={{ opacity: 1, x: 0 }}
|
||||
exit={{ opacity: 0, x: -20 }}
|
||||
transition={{ duration: 0.3 }}
|
||||
>
|
||||
{/* STEP 1: TYPE */}
|
||||
{step === 'type' && (
|
||||
<FormField control={form.control} name="type" render={({ field }) => (
|
||||
<FormItem>
|
||||
<div className="grid md:grid-cols-2 gap-6">
|
||||
<Card onClick={() => field.onChange('Project')}
|
||||
className={cn("cursor-pointer transition-all hover:border-his dark:hover:border-his duration-400", field.value === 'Project' && "ring-2 ring-his/10 border-his dark:ring-his/10 dark:border-his")}
|
||||
>
|
||||
<CardContent className="p-8 flex flex-col items-center text-center space-y-4">
|
||||
<div className="w-16 h-16 rounded-2xl bg-orange-500/10 text-orange-500 flex items-center justify-center">
|
||||
<Briefcase className="w-8 h-8" />
|
||||
</div>
|
||||
<div>
|
||||
<h3 className="text-xl font-bold">Project</h3>
|
||||
<p className="text-muted-foreground text-sm mt-2">
|
||||
Standard project assignment. Requires Work Orders and detailed planning.
|
||||
</p>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card onClick={() => field.onChange('IM')}
|
||||
className={cn("cursor-pointer transition-all hover:border-his dark:hover:border-his duration-400", field.value === 'IM' && "ring-2 ring-his/10 border-his dark:ring-his/10 dark:border-his")}
|
||||
>
|
||||
<CardContent className="p-8 flex flex-col items-center text-center space-y-4">
|
||||
<div className="w-16 h-16 rounded-2xl bg-purple-500/10 text-purple-500 flex items-center justify-center">
|
||||
<Clock className="w-8 h-8" />
|
||||
</div>
|
||||
<div>
|
||||
<h3 className="text-xl font-bold">Internal Memo (IM)</h3>
|
||||
<p className="text-muted-foreground text-sm mt-2">
|
||||
Used for Proof of Concept (PoC) stages. Can be converted to a Project later.
|
||||
</p>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* STEP 2: DETAILS */}
|
||||
{step === 'details' && (
|
||||
<Card900>
|
||||
<CardHeader>
|
||||
<CardTitle>{assignmentType === 'IM' ? 'Internal Memo' : 'Project'} Details</CardTitle>
|
||||
<CardDescription>Provide the basic information for this assignment.</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-6">
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="name"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Assignment Name</FormLabel>
|
||||
<div className="flex gap-2">
|
||||
<div className="flex-1 relative">
|
||||
<FormControl>
|
||||
<Input placeholder={assignmentType === 'Project' ? "Project Name" : "IM Name"} {...field} />
|
||||
</FormControl>
|
||||
{assignmentType === 'Project' && (
|
||||
<div className="absolute right-2 top-1/2 -translate-y-1/2">
|
||||
<Popover open={openProjectSearch} onOpenChange={setOpenProjectSearch}>
|
||||
<PopoverTrigger asChild>
|
||||
<Button variant="ghost" size="sm" className="h-7 px-2 text-xs">
|
||||
<Search className="w-3 h-3 mr-1" /> Existing
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent className="p-0 w-[300px]" align="end">
|
||||
<Command>
|
||||
<CommandInput placeholder="Search existing projects..." />
|
||||
<CommandList>
|
||||
<CommandEmpty>No projects found.</CommandEmpty>
|
||||
<CommandGroup heading="Recent Projects">
|
||||
{projectList.map(p => (
|
||||
<CommandItem
|
||||
key={p.id}
|
||||
onSelect={() => {
|
||||
form.setValue('name', p.name, { shouldValidate: true });
|
||||
form.setValue('code', p.code, { shouldValidate: true });
|
||||
form.setValue('year', p.year, { shouldValidate: true });
|
||||
form.setValue('startDate', p.startDate, { shouldValidate: true });
|
||||
form.setValue('endDate', p.endDate, { shouldValidate: true });
|
||||
form.setValue('description', p.description, { shouldValidate: true });
|
||||
|
||||
setOpenProjectSearch(false);
|
||||
setIsExistProject(true)
|
||||
toast.info(`Autofilled details from ${p.name}`);
|
||||
}}
|
||||
>
|
||||
<Check className={cn("mr-2 h-4 w-4", field.value === p.name ? "opacity-100" : "opacity-0")} />
|
||||
{p.name}
|
||||
</CommandItem>
|
||||
))}
|
||||
</CommandGroup>
|
||||
</CommandList>
|
||||
</Command>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<div className="grid md:grid-cols-2 gap-4">
|
||||
<FormField control={form.control} name="code" disabled={isExistProject} render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{assignmentType} Code</FormLabel>
|
||||
<FormControl><Input placeholder="e.g. 24016" {...field} /></FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)} />
|
||||
<FormField control={form.control} name="year" disabled={isExistProject} render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{assignmentType} Year</FormLabel>
|
||||
<FormControl><Input placeholder="e.g. 2024" {...field} /></FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)} />
|
||||
</div>
|
||||
|
||||
<div className="grid md:grid-cols-2 gap-4">
|
||||
<FormField control={form.control} name="startDate" disabled={isExistProject} 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="endDate" disabled={isExistProject} render={({ field }) => (
|
||||
<FormItem className="flex flex-col">
|
||||
<FormLabel>End Date</FormLabel>
|
||||
<DatePicker date={field.value} setDate={field.onChange} />
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)} />
|
||||
</div>
|
||||
|
||||
<FormField control={form.control} name="description" disabled={isExistProject} render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Description</FormLabel>
|
||||
<FormControl>
|
||||
<Textarea placeholder="Describe the scope..." className="min-h-[120px]" {...field} value={field.value || ''} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)} />
|
||||
</CardContent>
|
||||
</Card900>
|
||||
)}
|
||||
|
||||
{/* STEP 3: WORK ORDERS */}
|
||||
{step === 'work-orders' && (
|
||||
<div className="space-y-6">
|
||||
<div>
|
||||
<h2 className="text-2xl font-bold">Work Order</h2>
|
||||
<p className="text-muted-foreground">Define the initial task for this project.</p>
|
||||
</div>
|
||||
<Card900>
|
||||
<CardContent className="p-6 space-y-4">
|
||||
<div className="grid gap-4 md:grid-cols-2">
|
||||
<FormField control={form.control} name={"workOrder.name" as any} render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>WO Name</FormLabel>
|
||||
<FormControl><Input placeholder="e.g. Initial Site Survey" {...field} value={field.value || ''} /></FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)} />
|
||||
<FormField control={form.control} name={"workOrder.code" as any} render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>WO Code</FormLabel>
|
||||
<FormControl><Input placeholder="e.g. WO-24016" {...field} value={field.value || ''} /></FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)} />
|
||||
</div>
|
||||
<div className="grid gap-4 md:grid-cols-2">
|
||||
<FormField control={form.control} name={"workOrder.startDate" as any} render={({ field }) => (
|
||||
<FormItem className="flex flex-col">
|
||||
<FormLabel>WO Start Date</FormLabel>
|
||||
<DatePicker date={field.value as Date | undefined} setDate={field.onChange} />
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)} />
|
||||
<FormField control={form.control} name={"workOrder.endDate" as any} render={({ field }) => (
|
||||
<FormItem className="flex flex-col">
|
||||
<FormLabel>WO End Date</FormLabel>
|
||||
<DatePicker date={field.value as Date | undefined} setDate={field.onChange} />
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)} />
|
||||
</div>
|
||||
<FormField control={form.control} name={"workOrder.description" as any} render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>WO Description</FormLabel>
|
||||
<FormControl><Textarea placeholder="Briefly describe the task.." className="min-h-[120px]" {...field} value={field.value || ''} /></FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)} />
|
||||
</CardContent>
|
||||
</Card900>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* STEP 4: REVIEW */}
|
||||
{step === 'review' && (
|
||||
<div className="space-y-6">
|
||||
<div>
|
||||
<h2 className="text-2xl font-bold">Review Assignment</h2>
|
||||
<p className="text-muted-foreground">Double check everything before saving.</p>
|
||||
</div>
|
||||
<div className="grid gap-6">
|
||||
<Card900>
|
||||
<CardHeader>
|
||||
<CardTitle>Overview</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-6">
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div>
|
||||
<Label className="text-xs text-muted-foreground uppercase">Type</Label>
|
||||
<div className="mt-1">
|
||||
<Badge variant={formValues.type === 'Project' ? 'default' : 'secondary'}>{formValues.type}</Badge>
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<Label className="text-xs text-muted-foreground uppercase">Client</Label>
|
||||
<p className="font-medium mt-1">{client?.name}</p>
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<Label className="text-xs text-muted-foreground uppercase">Name</Label>
|
||||
<p className="text-xl font-bold mt-1">{formValues.name || 'Untitled Assignment'}</p>
|
||||
</div>
|
||||
<div>
|
||||
<Label className="text-xs text-muted-foreground uppercase">Description</Label>
|
||||
<p className="text-muted-foreground mt-1">{formValues.description || 'No description provided.'}</p>
|
||||
</div>
|
||||
|
||||
{formValues.type === 'Project' && (formValues.workOrder as any)?.name && (
|
||||
<>
|
||||
<Separator />
|
||||
<div>
|
||||
<Label className="text-xs text-muted-foreground uppercase mb-3 block">Work Order</Label>
|
||||
<div className="flex items-center gap-3 p-2 bg-accent/30 rounded-md">
|
||||
<div className="w-6 h-6 rounded-full bg-primary/10 text-primary flex items-center justify-center text-[10px] font-bold">
|
||||
1
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-sm font-medium">{(formValues.workOrder as any).name}</p>
|
||||
<p className="text-xs text-muted-foreground">{(formValues.workOrder as any).description}</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card900>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</motion.div>
|
||||
</AnimatePresence>
|
||||
|
||||
{/* --- FOOTER NAVIGATION --- */}
|
||||
<div className="fixed bottom-0 left-0 right-0 p-6 bg-background/80 backdrop-blur-md border-t flex justify-between z-50">
|
||||
<Button type="button" variant="ghost" onClick={handleBack} disabled={step === 'type'}>
|
||||
Back
|
||||
</Button>
|
||||
|
||||
{/* <Button type="button" className="gap-2" onClick={handleNext}>
|
||||
Next Step <ArrowRight className="w-4 h-4" />
|
||||
</Button> */}
|
||||
<div className="flex gap-4">
|
||||
{step !== 'review' ?
|
||||
<Button key="next-btn" type="button" className="gap-2" onClick={handleNext}>
|
||||
Next Step <ArrowRight className="w-4 h-4" />
|
||||
</Button>
|
||||
:
|
||||
<Button key="submit-btn" type="submit" className="gap-2" disabled={loading}>
|
||||
{loading ? 'Saving...' : <><Save className="w-4 h-4" /> Save Assignment</>}
|
||||
</Button>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
</Form>
|
||||
|
||||
{isFullLoading ? <PageLoading /> : null}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,503 @@
|
||||
"use client"
|
||||
|
||||
import { motion, AnimatePresence } from 'motion/react';
|
||||
import {
|
||||
ArrowLeft, ArrowRight, Save, Briefcase, Clock, Search, Check
|
||||
} from 'lucide-react';
|
||||
import { useState, useMemo, use } from 'react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Separator } from '@/components/ui/separator';
|
||||
import {
|
||||
Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList,
|
||||
} from '@/components/ui/command';
|
||||
import {
|
||||
Popover, PopoverContent, PopoverTrigger,
|
||||
} from '@/components/ui/popover';
|
||||
import { toast } from 'sonner';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { useAppState } from '@/hooks/useDummyTaskData';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { IProjectType } from '../../../types';
|
||||
import { DatePicker } from '@/components/ui/datepicker';
|
||||
|
||||
type IStep = 'type' | 'details' | 'work-orders' | 'review';
|
||||
|
||||
type Props = {
|
||||
params: Promise<{ client_id: string | undefined }>
|
||||
};
|
||||
|
||||
export default function CreateAssignment({ params }: Props) {
|
||||
const { clients, assignments, addAssignment } = useAppState();
|
||||
const router = useRouter()
|
||||
// const { id } = await params;
|
||||
const { client_id: clientId } = use(params);
|
||||
|
||||
// Form State
|
||||
const [type, setType] = useState<IProjectType>('Project');
|
||||
const [name, setName] = useState('');
|
||||
const [description, setDescription] = useState('');
|
||||
const [code, setCode] = useState('');
|
||||
const [year, setYear] = useState(new Date().getFullYear().toString());
|
||||
const [startDate, setStartDate] = useState<Date | undefined>();
|
||||
const [endDate, setEndDate] = useState<Date | undefined>();
|
||||
const [workOrder, setWorkOrder] = useState({
|
||||
name: '',
|
||||
description: '',
|
||||
code: '',
|
||||
startDate: new Date(),
|
||||
endDate: new Date()
|
||||
});
|
||||
|
||||
// Autocomplete state for existing projects
|
||||
const [openProjectSearch, setOpenProjectSearch] = useState(false);
|
||||
|
||||
|
||||
const [step, setStep] = useState<IStep>('type');
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
|
||||
const existingProjects = useMemo(() => {
|
||||
const projects = assignments.filter(a => a.type === 'Project');
|
||||
// Unique projects by name
|
||||
const unique: Record<string, typeof projects[0]> = {};
|
||||
projects.forEach(p => {
|
||||
if (!unique[p.name]) unique[p.name] = p;
|
||||
});
|
||||
return Object.values(unique);
|
||||
}, [assignments]);
|
||||
|
||||
const currentClient = clients.find(c => c.id === clientId);
|
||||
|
||||
const handleNext = () => {
|
||||
if (step === 'type') setStep('details');
|
||||
else if (step === 'details') {
|
||||
if (type === 'Project') setStep('work-orders');
|
||||
else setStep('review');
|
||||
}
|
||||
else if (step === 'work-orders') setStep('review');
|
||||
};
|
||||
|
||||
const handleBack = () => {
|
||||
if (step === 'details') setStep('type');
|
||||
else if (step === 'work-orders') setStep('details');
|
||||
else if (step === 'review') {
|
||||
if (type === 'Project') setStep('work-orders');
|
||||
else setStep('details');
|
||||
}
|
||||
};
|
||||
|
||||
const handleSave = async () => {
|
||||
setLoading(true);
|
||||
const assignmentId = Math.random().toString(36).substr(2, 9);
|
||||
|
||||
const newAssignment = {
|
||||
id: assignmentId,
|
||||
clientId,
|
||||
type,
|
||||
name,
|
||||
description,
|
||||
code,
|
||||
year,
|
||||
startDate,
|
||||
endDate,
|
||||
status: 'Active' as const,
|
||||
statusHistory: [{
|
||||
id: Math.random().toString(36).substr(2, 9),
|
||||
status: 'Active',
|
||||
date: new Date().toISOString().split('T')[0],
|
||||
note: 'Initial assignment creation',
|
||||
createdAt: new Date().toISOString()
|
||||
}],
|
||||
createdAt: new Date().toISOString(),
|
||||
workOrders: type === 'Project' ? [{
|
||||
id: Math.random().toString(36).substr(2, 9),
|
||||
projectId: assignmentId,
|
||||
name: workOrder.name,
|
||||
description: workOrder.description,
|
||||
code: workOrder.code,
|
||||
startDate: workOrder.startDate,
|
||||
endDate: workOrder.endDate,
|
||||
status: 'Active' as const,
|
||||
statusHistory: [{
|
||||
id: Math.random().toString(36).substr(2, 9),
|
||||
status: 'Active',
|
||||
date: new Date().toISOString().split('T')[0],
|
||||
note: 'Initial work order creation',
|
||||
createdAt: new Date().toISOString()
|
||||
}],
|
||||
createdAt: new Date().toISOString(),
|
||||
}] : [],
|
||||
assignedEmployees: [], // Initialized as empty
|
||||
};
|
||||
|
||||
await new Promise(resolve => setTimeout(resolve, 1000));
|
||||
addAssignment(newAssignment);
|
||||
|
||||
setLoading(false);
|
||||
toast.success(`${type} created successfully`);
|
||||
router.replace(`/task/client-detail/${clientId}`);
|
||||
};
|
||||
|
||||
const steps: { id: IStep; label: string }[] = [
|
||||
{ id: 'type', label: 'Type' },
|
||||
{ id: 'details', label: 'Details' },
|
||||
...(type === 'Project' ? [{ id: 'work-orders' as IStep, label: 'Work Orders' }] : []),
|
||||
{ id: 'review', label: 'Review' },
|
||||
];
|
||||
|
||||
const currentStepIndex = steps.findIndex(s => s.id === step);
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="max-w-4xl mx-auto space-y-8 p-6 sm:p-8 pt-6 pb-20">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-4">
|
||||
<Button variant="ghost" size="icon" onClick={() => router.back()}>
|
||||
<ArrowLeft className="w-5 h-5" />
|
||||
</Button>
|
||||
<div>
|
||||
<h1 className="text-3xl font-bold">Create Project Assignment</h1>
|
||||
<p className="text-muted-foreground">
|
||||
{currentClient ? `For ${currentClient.name}` : 'Assign a new project or IM to a client'}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Stepper */}
|
||||
<div className="flex items-center justify-between px-2">
|
||||
{steps.map((s, i) => (
|
||||
<div key={s.id} className="flex items-center flex-1 last:flex-none">
|
||||
<div className="flex flex-col items-center gap-2">
|
||||
<div className={cn(
|
||||
"w-10 h-10 rounded-full flex items-center justify-center border-2 transition-all duration-300",
|
||||
i <= currentStepIndex ? "bg-zinc-900 dark:bg-zinc-100 border-primary text-secondary" : "border-border text-muted-foreground"
|
||||
)}>
|
||||
{i < currentStepIndex ? <Check className="w-5 h-5" /> : <span>{i + 1}</span>}
|
||||
</div>
|
||||
<span className={cn(
|
||||
"text-xs font-medium hidden md:block",
|
||||
i <= currentStepIndex ? "text-primary" : "text-muted-foreground"
|
||||
)}>{s.label}</span>
|
||||
</div>
|
||||
{i < steps.length - 1 && (
|
||||
<div className={cn(
|
||||
"h-0.5 flex-1 mx-4 transition-all duration-500",
|
||||
i < currentStepIndex ? "bg-primary" : "bg-border"
|
||||
)} />
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<AnimatePresence mode="wait">
|
||||
<motion.div
|
||||
key={step}
|
||||
initial={{ opacity: 0, x: 20 }}
|
||||
animate={{ opacity: 1, x: 0 }}
|
||||
exit={{ opacity: 0, x: -20 }}
|
||||
transition={{ duration: 0.3 }}
|
||||
>
|
||||
{step === 'type' && (
|
||||
<div className="grid md:grid-cols-2 gap-6">
|
||||
<Card
|
||||
className={cn(
|
||||
"cursor-pointer transition-all hover:border-his dark:hover:border-his duration-400",
|
||||
type === 'Project' ? "border-his ring-2 ring-his/10 dark:ring-his" : ""
|
||||
)}
|
||||
onClick={() => setType('Project')}
|
||||
>
|
||||
<CardContent className="p-8 flex flex-col items-center text-center space-y-4">
|
||||
<div className="w-16 h-16 rounded-2xl bg-orange-500/10 text-orange-500 flex items-center justify-center">
|
||||
<Briefcase className="w-8 h-8" />
|
||||
</div>
|
||||
<div>
|
||||
<h3 className="text-xl font-bold">Project</h3>
|
||||
<p className="text-muted-foreground text-sm mt-2">
|
||||
Standard project assignment. Requires Work Orders and detailed planning.
|
||||
</p>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card
|
||||
className={cn(
|
||||
"cursor-pointer transition-all hover:border-his dark:hover:border-his duration-400",
|
||||
type === 'IM' ? "border-his ring-2 ring-his/10 dark:ring-his" : ""
|
||||
)}
|
||||
onClick={() => setType('IM')}
|
||||
>
|
||||
<CardContent className="p-8 flex flex-col items-center text-center space-y-4">
|
||||
<div className="w-16 h-16 rounded-2xl bg-purple-500/10 text-purple-500 flex items-center justify-center">
|
||||
<Clock className="w-8 h-8" />
|
||||
</div>
|
||||
<div>
|
||||
<h3 className="text-xl font-bold">Internal Memo (IM)</h3>
|
||||
<p className="text-muted-foreground text-sm mt-2">
|
||||
Used for Proof of Concept (PoC) stages. Can be converted to a Project later.
|
||||
</p>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{step === 'details' && (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>{type} Details</CardTitle>
|
||||
<CardDescription>Provide the basic information for this assignment.</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-6">
|
||||
<div className="space-y-2">
|
||||
<Label>Assignment Name</Label>
|
||||
<div className="flex gap-2">
|
||||
<div className="flex-1 relative">
|
||||
<Input
|
||||
placeholder={type === 'Project' ? "Project Name" : "IM Name"}
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
/>
|
||||
{type === 'Project' && (
|
||||
<div className="absolute right-2 top-1/2 -translate-y-1/2">
|
||||
<Popover open={openProjectSearch} onOpenChange={setOpenProjectSearch}>
|
||||
<PopoverTrigger asChild>
|
||||
<Button variant="ghost" size="sm" className="h-7 px-2 text-xs">
|
||||
<Search className="w-3 h-3 mr-1" />
|
||||
Existing
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent className="p-0 w-[300px]" align="end">
|
||||
<Command>
|
||||
<CommandInput placeholder="Search existing projects..." />
|
||||
<CommandList>
|
||||
<CommandEmpty>No projects found.</CommandEmpty>
|
||||
<CommandGroup heading="Recent Projects">
|
||||
{existingProjects.map(p => (
|
||||
<CommandItem
|
||||
key={p.id}
|
||||
onSelect={() => {
|
||||
setName(p.name);
|
||||
setDescription(p.description);
|
||||
setOpenProjectSearch(false);
|
||||
toast.info(`Autofilled details from ${p.name}`);
|
||||
}}
|
||||
>
|
||||
<Check className={cn("mr-2 h-4 w-4", name === p.name ? "opacity-100" : "opacity-0")} />
|
||||
{p.name}
|
||||
</CommandItem>
|
||||
))}
|
||||
</CommandGroup>
|
||||
</CommandList>
|
||||
</Command>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid md:grid-cols-2 gap-4">
|
||||
<div className="space-y-2">
|
||||
<Label>Project Code</Label>
|
||||
<Input
|
||||
placeholder="e.g. 24016"
|
||||
value={code}
|
||||
onChange={(e) => setCode(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label>Project Year</Label>
|
||||
<Input
|
||||
placeholder="e.g. 2024"
|
||||
value={year}
|
||||
onChange={(e) => setYear(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid md:grid-cols-2 gap-4">
|
||||
<div className="space-y-2">
|
||||
<Label>Start Date</Label>
|
||||
<DatePicker date={startDate} setDate={setStartDate} />
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label>End Date</Label>
|
||||
<DatePicker date={endDate} setDate={setEndDate} />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label>Description</Label>
|
||||
<Textarea
|
||||
placeholder="Describe the scope of this assignment..."
|
||||
className="min-h-[120px]"
|
||||
value={description}
|
||||
onChange={(e) => setDescription(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{step === 'work-orders' && (
|
||||
<div className="space-y-6">
|
||||
<div>
|
||||
<h2 className="text-2xl font-bold">Work Order</h2>
|
||||
<p className="text-muted-foreground">Define the initial task for this project.</p>
|
||||
</div>
|
||||
|
||||
<Card>
|
||||
<CardContent className="p-6 space-y-4">
|
||||
<div className="grid gap-4 md:grid-cols-2">
|
||||
<div className="space-y-2">
|
||||
<Label>WO Name</Label>
|
||||
<Input
|
||||
placeholder="e.g. Initial Site Survey"
|
||||
value={workOrder.name}
|
||||
onChange={(e) => setWorkOrder({ ...workOrder, name: e.target.value })}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label>WO Code</Label>
|
||||
<Input
|
||||
placeholder="e.g. WO-24016"
|
||||
value={workOrder.code}
|
||||
onChange={(e) => setWorkOrder({ ...workOrder, code: e.target.value })}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="grid gap-4 md:grid-cols-2">
|
||||
<div className="space-y-2">
|
||||
<Label>WO Start Date</Label>
|
||||
<DatePicker date={workOrder.startDate} setDate={(val) => setWorkOrder({ ...workOrder, startDate: val! })} />
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label>WO End Date</Label>
|
||||
<DatePicker date={workOrder.endDate} setDate={(val) => setWorkOrder({ ...workOrder, endDate: val! })} />
|
||||
</div>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label>WO Description</Label>
|
||||
<Input
|
||||
placeholder="Briefly describe the task..."
|
||||
value={workOrder.description}
|
||||
onChange={(e) => setWorkOrder({ ...workOrder, description: e.target.value })}
|
||||
/>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{step === 'review' && (
|
||||
<div className="space-y-6">
|
||||
<div>
|
||||
<h2 className="text-2xl font-bold">Review Assignment</h2>
|
||||
<p className="text-muted-foreground">Double check everything before saving.</p>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-6">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Overview</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-6">
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div>
|
||||
<Label className="text-xs text-muted-foreground uppercase">Type</Label>
|
||||
<div className="mt-1">
|
||||
<Badge variant={type === 'Project' ? 'default' : 'secondary'}>{type}</Badge>
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<Label className="text-xs text-muted-foreground uppercase">Client</Label>
|
||||
<p className="font-medium mt-1">{currentClient?.name}</p>
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<Label className="text-xs text-muted-foreground uppercase">Name</Label>
|
||||
<p className="text-xl font-bold mt-1">{name || 'Untitled Assignment'}</p>
|
||||
</div>
|
||||
<div>
|
||||
<Label className="text-xs text-muted-foreground uppercase">Description</Label>
|
||||
<p className="text-muted-foreground mt-1">{description || 'No description provided.'}</p>
|
||||
</div>
|
||||
|
||||
{type === 'Project' && workOrder.name && (
|
||||
<>
|
||||
<Separator />
|
||||
<div>
|
||||
<Label className="text-xs text-muted-foreground uppercase mb-3 block">Work Order</Label>
|
||||
<div className="flex items-center gap-3 p-2 bg-accent/30 rounded-md">
|
||||
<div className="w-6 h-6 rounded-full bg-primary/10 text-primary flex items-center justify-center text-[10px] font-bold">
|
||||
1
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-sm font-medium">{workOrder.name}</p>
|
||||
<p className="text-xs text-muted-foreground">{workOrder.description}</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground italic text-center">
|
||||
Note: Employees can be assigned after the assignment is created.
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</motion.div>
|
||||
</AnimatePresence>
|
||||
|
||||
{/* Navigation Buttons */}
|
||||
<div className="fixed bottom-0 left-0 right-0 p-6 bg-background/80 backdrop-blur-md border-t border-border flex justify-between items-center z-50">
|
||||
<Button
|
||||
variant="ghost"
|
||||
onClick={handleBack}
|
||||
disabled={step === 'type'}
|
||||
>
|
||||
Back
|
||||
</Button>
|
||||
|
||||
<div className="flex gap-4">
|
||||
{step !== 'review' ?
|
||||
<Button
|
||||
className="gap-2"
|
||||
onClick={handleNext}
|
||||
disabled={
|
||||
(step === 'details' && (!name || !clientId)) ||
|
||||
(step === 'type' && !type)
|
||||
}
|
||||
>
|
||||
Next Step
|
||||
<ArrowRight className="w-4 h-4" />
|
||||
</Button>
|
||||
:
|
||||
<Button
|
||||
className="gap-2"
|
||||
onClick={handleSave}
|
||||
disabled={loading}
|
||||
>
|
||||
{loading ? 'Saving...' : (
|
||||
<>
|
||||
<Save className="w-4 h-4" />
|
||||
Save Assignment
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import fetchData from "@/lib/fetchData";
|
||||
import ProjectAssignmentForm from "./ProjectAssignmentForm";
|
||||
|
||||
type Props = {
|
||||
params: Promise<{ client_id: string }>
|
||||
searchParams: Promise<{ [key: string]: string | string[] | undefined }>
|
||||
};
|
||||
|
||||
export default async function CreateAssignmentPage({ params, searchParams }: Props) {
|
||||
const { client_id } = await params;
|
||||
const isEdit = (await searchParams)!.is_edit
|
||||
const assignmentId = (await searchParams)!.assignment_id
|
||||
|
||||
const getClient = fetchData(`/client/${client_id}`)
|
||||
const getProjectByClient = fetchData('/project-assignment')
|
||||
|
||||
const [clientRes, projectList] = await Promise.all([getClient, getProjectByClient]);
|
||||
const client = clientRes && clientRes.length > 0 ? clientRes[0] : clientRes
|
||||
|
||||
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 || []}
|
||||
isEdit={isEdit ? true : false} assignmentId={assignmentId as any}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
// app/clients/components/assignment-table.tsx
|
||||
import { Card, Card900 } 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';
|
||||
|
||||
export default function AssignmentTable({ data }: { data: any[] }) {
|
||||
if (data.length === 0) {
|
||||
return <Card900 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>
|
||||
}
|
||||
|
||||
return (
|
||||
<Card className="overflow-hidden">
|
||||
<div className="overflow-x-auto">
|
||||
<Table>
|
||||
<TableHeader className="bg-accent/50">
|
||||
<TableRow>
|
||||
<TableHead className="min-w-[150px]">Client</TableHead>
|
||||
<TableHead className="min-w-[120px]">End User</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>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>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{data.map((item, idx) => {
|
||||
const { client, assignment, wo } = item;
|
||||
const latestStatus = wo?.statusHistory?.[0] || assignment.statusHistory?.[0];
|
||||
|
||||
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>
|
||||
<TableCell className="font-medium">
|
||||
<Link href={`/assignments/${assignment.id}`} className="hover:underline text-blue-600 dark:text-blue-400">
|
||||
{assignment.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>
|
||||
<TableCell>{assignment.year || '-'}</TableCell>
|
||||
<TableCell className="whitespace-nowrap text-xs">
|
||||
{assignment.startDate ? new Date(assignment.startDate).toLocaleDateString() : '-'}
|
||||
</TableCell>
|
||||
<TableCell className="whitespace-nowrap text-xs">
|
||||
{assignment.endDate ? new Date(assignment.endDate).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>
|
||||
<TableCell className="whitespace-nowrap text-xs">
|
||||
{wo?.endDate ? new Date(wo.endDate).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>
|
||||
</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>
|
||||
</TableRow>
|
||||
);
|
||||
})}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,178 @@
|
||||
// app/clients/components/client-grid.tsx
|
||||
"use client" // Keep as client component if using motion/react animations
|
||||
|
||||
import { motion } from 'motion/react';
|
||||
import { Card, Card900, CardContent } from '@/components/ui/card';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { ExternalLink, MoreHorizontal, Users } from 'lucide-react';
|
||||
import Link from 'next/link';
|
||||
import { LazyImage } from '@/components/ui/lazy-image';
|
||||
import {
|
||||
DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger,
|
||||
} from '@/components/ui/dropdown-menu';
|
||||
import {
|
||||
Tooltip, TooltipContent, TooltipTrigger,
|
||||
} from '@/components/ui/tooltip';
|
||||
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';
|
||||
|
||||
export default function ClientGrid({ clients, assignments }: { clients: IClient[], assignments: any[] }) {
|
||||
const router = useRouter();
|
||||
const [action, setAction] = useState<'EDIT' | 'DELETE' | undefined>(undefined)
|
||||
const [selectedData, setShowSelectedData] = useState<IClient>()
|
||||
|
||||
const handleClose = () => {
|
||||
setAction(undefined)
|
||||
setShowSelectedData(undefined)
|
||||
}
|
||||
|
||||
if (clients.length === 0) {
|
||||
return (
|
||||
<div className="py-12 text-center border-2 border-dashed rounded-xl">
|
||||
<Users className="w-12 h-12 mx-auto text-muted-foreground mb-4 opacity-20" />
|
||||
<h3 className="text-lg font-medium">No client found</h3>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="grid gap-6 md:grid-cols-2 lg:grid-cols-3">
|
||||
{clients.map((client, i) => {
|
||||
const clientAssignments = assignments.filter(a => a.clientId === client.id);
|
||||
const imCount = 0
|
||||
const projectCount = client.total_project;
|
||||
// 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)));
|
||||
|
||||
return (
|
||||
<motion.div
|
||||
key={client.id}
|
||||
initial={{ opacity: 0, scale: 0.95 }}
|
||||
animate={{ opacity: 1, scale: 1 }}
|
||||
transition={{ delay: i * 0.05 }}
|
||||
className="h-full"
|
||||
>
|
||||
<Card900 className="h-full group overflow-hidden hover:shadow-lg transition-all duration-300 border-primary/5 hover:border-primary/20 flex flex-col py-0">
|
||||
<CardContent className="p-0 flex flex-col h-full">
|
||||
<div className="relative h-32 bg-accent/50 overflow-hidden">
|
||||
<LazyImage
|
||||
src={client.photo!}
|
||||
alt={client.name}
|
||||
className="w-full h-full object-cover group-hover:scale-110 transition-transform duration-500"
|
||||
/>
|
||||
<div className="absolute inset-0 bg-linear-to-t from-black/80 via-black/40 to-transparent" />
|
||||
<div className="absolute bottom-4 left-4 right-4 flex items-end justify-between">
|
||||
<div className="text-white">
|
||||
<h3 className="font-bold text-lg leading-tight">{client.name}</h3>
|
||||
<p className="text-xs opacity-80">{client.end_user_name}</p>
|
||||
</div>
|
||||
<Link href={`/task/client-detail/${client.id}`}>
|
||||
<Button size="icon" variant="secondary" className="h-8 w-8 rounded-full opacity-0 group-hover:opacity-100 transition-opacity">
|
||||
<ExternalLink className="w-4 h-4" />
|
||||
</Button>
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
<div className="p-5 flex flex-col flex-1 justify-between gap-4">
|
||||
<div className="space-y-2">
|
||||
{/* <p className="text-sm leading-relaxed text-muted-foreground line-clamp-3 h-16">
|
||||
Currently managing a portfolio of <span className="font-bold text-foreground">{projectCount} projects</span> and <span className="font-bold text-foreground">{imCount} internal memos</span>.
|
||||
A dedicated team of <span className="font-bold text-foreground">{assignedEmployeeIds.length} experts</span> is handling <span className="font-bold text-foreground">{woCount} work orders</span> to ensure successful delivery for <span className="italic">{client.endUser}</span>.
|
||||
</p> */}
|
||||
<p className="text-sm leading-relaxed text-muted-foreground line-clamp-3 h-16">
|
||||
{projectCount === 0 && imCount === 0 && woCount === 0 ?
|
||||
"No active projects, internal memos, or work orders recorded for this client yet."
|
||||
:
|
||||
<>
|
||||
{(projectCount! > 0 || imCount > 0) && (
|
||||
<>
|
||||
Currently managing a portfolio of{" "}
|
||||
{projectCount! > 0 &&
|
||||
<span className="font-bold text-foreground">{projectCount} project{projectCount! > 1 ? 's' : ''}</span>
|
||||
}
|
||||
{projectCount! > 0 && imCount > 0 && " and "}
|
||||
{imCount > 0 &&
|
||||
<span className="font-bold text-foreground">{imCount} internal memo{imCount > 1 ? 's' : ''}</span>
|
||||
}
|
||||
.{" "}
|
||||
</>
|
||||
)}
|
||||
{woCount! > 0 && (
|
||||
<>
|
||||
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>.
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-between pt-4 pb-2 border-t border-border">
|
||||
<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);
|
||||
return (
|
||||
<div key={empId}>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<LazyImage src={emp?.avatar!} alt={emp?.name!}
|
||||
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>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
{assignedEmployeeIds.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}
|
||||
</div>
|
||||
)}
|
||||
{assignedEmployeeIds.length === 0 && (
|
||||
<span className="text-[10px] text-muted-foreground italic">No team assigned</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-2 self-end">
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="ghost" size="icon" className="h-8 w-8">
|
||||
<MoreHorizontal className="w-4 h-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuItem asChild>
|
||||
<Link href={`/task/client-detail/${client.id}`}>View Client Detail</Link>
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onSelect={() => { setShowSelectedData(client); setAction('EDIT') }}>Edit Client</DropdownMenuItem>
|
||||
<DropdownMenuItem onSelect={() => { setShowSelectedData(client); setAction('DELETE') }} className="text-destructive">Delete Client</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card900>
|
||||
</motion.div>
|
||||
);
|
||||
})}
|
||||
</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}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,270 @@
|
||||
import { useCallback, useEffect, useRef, useState, type FC } from 'react';
|
||||
import {
|
||||
AlertDialog, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle
|
||||
} from "@/components/ui/alert-dialog"
|
||||
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage, } from "@/components/ui/form";
|
||||
import * as Yup from 'yup'
|
||||
import { yupResolver } from '@hookform/resolvers/yup';
|
||||
import { IClient } from '../types';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { toast } from 'sonner';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { ImageIcon, Loader2, Plus, Upload, UploadIcon } from 'lucide-react';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { useFetchWithAxios } from '@/lib/axios/useFetch';
|
||||
import { Combobox } from '@/components/ui/combobox';
|
||||
import Dropzone from 'react-dropzone';
|
||||
import { LazyImage } from '@/components/ui/lazy-image';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { serverApiCall } from '@/lib/server-api';
|
||||
import FormEndUser from './FormEndUser';
|
||||
|
||||
const validationSchema = Yup.object().shape({
|
||||
name: Yup.string().required(),
|
||||
end_user_id: Yup.number().required(),
|
||||
imageUrl: Yup.string().optional().default('')
|
||||
});
|
||||
|
||||
type FormDataType = Yup.InferType<typeof validationSchema>;
|
||||
|
||||
type Props = {
|
||||
data?: IClient
|
||||
onCancel?: VoidFunction
|
||||
onSuccess?: VoidFunction;
|
||||
};
|
||||
|
||||
const FormClient: FC<Props> = ({ data, onSuccess, onCancel }) => {
|
||||
const [showEnduserForm, setShowEndUserForm] = useState(false)
|
||||
const [isLoading, setIsLoading] = useState(false)
|
||||
const [currentFile, setCurrentFile] = useState<any | undefined>(undefined);
|
||||
|
||||
const { data: endUserList, mutate } = useFetchWithAxios('/end-user')
|
||||
|
||||
const existFile = data?.photo || null
|
||||
const dropzoneRef = useRef<any>(null);
|
||||
const maxSizeMB = 5
|
||||
|
||||
const openDialog = () => {
|
||||
if (dropzoneRef.current) {
|
||||
dropzoneRef.current.open();
|
||||
}
|
||||
};
|
||||
|
||||
const onDrop = useCallback((acceptedFiles: any[]) => {
|
||||
acceptedFiles.forEach(async (file: any) => {
|
||||
const reader = new FileReader();
|
||||
|
||||
reader.onabort = () => console.log('file reading was aborted');
|
||||
reader.onerror = () => console.log('file reading has failed');
|
||||
reader.onload = async () => {
|
||||
// Do whatever you want with the file contents
|
||||
const binaryStr = reader.result;
|
||||
|
||||
console.log(file)
|
||||
setCurrentFile({ file: file, base64: binaryStr?.toString() });
|
||||
};
|
||||
reader.readAsDataURL(file);
|
||||
});
|
||||
}, []);
|
||||
|
||||
const router = useRouter()
|
||||
|
||||
const form = useForm<FormDataType>({
|
||||
resolver: yupResolver(validationSchema),
|
||||
defaultValues: {
|
||||
"name": data?.name || '',
|
||||
"end_user_id": data?.end_user_id || undefined,
|
||||
'imageUrl': data?.imageUrl || ''
|
||||
},
|
||||
});
|
||||
|
||||
const handleUploadFile = async () => {
|
||||
setIsLoading(true)
|
||||
const toastId = toast.loading('Uploading image...');
|
||||
let fullPathImage = ''
|
||||
|
||||
try {
|
||||
const resPresignUrl: any = await serverApiCall('POST', '/s3', {
|
||||
"filename": currentFile?.file?.name,
|
||||
"type": currentFile?.file?.type,
|
||||
"bucket": "hats-client"
|
||||
})
|
||||
|
||||
console.log({ resPresignUrl })
|
||||
|
||||
if (resPresignUrl.success) {
|
||||
fullPathImage = `${process.env.NEXT_PUBLIC_S3_IMAGE_URL}/${resPresignUrl?.data?.data?.path_url}`
|
||||
const presignedUrl = resPresignUrl?.data?.data?.upload_url
|
||||
|
||||
const uploadResponse = await fetch(presignedUrl, {
|
||||
method: 'PUT',
|
||||
body: currentFile?.file, // Send the raw file directly
|
||||
headers: {
|
||||
'Content-Type': currentFile?.file?.type,
|
||||
},
|
||||
});
|
||||
|
||||
if (!uploadResponse.ok) {
|
||||
throw new Error("Failed to upload image to storage 😢");
|
||||
}
|
||||
} else {
|
||||
toast.error("Oops sorry, error has occurred 😢", {
|
||||
description: `(${resPresignUrl.code}) ${resPresignUrl.message || "An unexpected error occurred while Getting Presigned URL. Please try again later."}`,
|
||||
})
|
||||
}
|
||||
} catch (error: any) {
|
||||
toast.error(`Failed uploading image.\n(${error?.response?.data?.code || error?.response?.status || '-'}) ${error?.response?.data?.message || error?.response?.statusText || error?.message}`);
|
||||
} finally {
|
||||
setIsLoading(false)
|
||||
toast.dismiss(toastId)
|
||||
}
|
||||
|
||||
return fullPathImage
|
||||
}
|
||||
|
||||
const onSubmit = async (payload: FormDataType) => {
|
||||
setIsLoading(true);
|
||||
|
||||
let newPayload: any = { ...payload }
|
||||
|
||||
if (currentFile?.file) {
|
||||
const photoPath = await handleUploadFile()
|
||||
newPayload['photo'] = photoPath
|
||||
} else {
|
||||
newPayload['photo'] = data?.photo
|
||||
}
|
||||
|
||||
let res: any
|
||||
if (data) {
|
||||
res = await serverApiCall('PUT', `/client/${data.id}`, newPayload)
|
||||
} else {
|
||||
res = await serverApiCall('POST', '/client', newPayload)
|
||||
}
|
||||
|
||||
setIsLoading(false)
|
||||
if (res.success) {
|
||||
toast.success('Client saved successfully')
|
||||
if (data) {
|
||||
onSuccess!()
|
||||
} else {
|
||||
router.push(`/task/client-detail/${res.data?.data?.id}`)
|
||||
}
|
||||
} else {
|
||||
toast.error(`Fail to save client`, { description: `(${res.code || '-'}) ${res.message}` })
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
return (
|
||||
<>
|
||||
<AlertDialog open={true}>
|
||||
<AlertDialogContent className='max-h-[90vh] overflow-y-auto overflow-x-hidden'>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>Client Information</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
Enter the basic details of the client and their end user.
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<Form {...form}>
|
||||
<form onSubmit={form.handleSubmit(onSubmit)}>
|
||||
<div className="grid grid-cols-1 gap-4 mb-6">
|
||||
<FormField control={form.control} name='name'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Client Name <span className='text-red-600 font-bold'>*</span></FormLabel>
|
||||
<FormControl>
|
||||
<Input {...field} placeholder='e.g. PT Telkom Indonesia' />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField control={form.control} name='end_user_id'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>End User <span className='text-red-600 font-bold'>*</span></FormLabel>
|
||||
<FormControl>
|
||||
<div className="flex gap-4">
|
||||
<Combobox title='End User' options={endUserList && endUserList.length > 0 ? endUserList.map((item: any) => ({ label: item.name, value: item.id })) : []} value={field.value} setValue={field.onChange} className='flex-1' />
|
||||
<Button type="button" variant="outline" size="icon" className="shrink-0" onClick={() => setShowEndUserForm(true)}>
|
||||
<Plus className="w-4 h-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<div className="flex flex-col gap-2">
|
||||
<Label>Add Client Image</Label>
|
||||
{/* Drop area */}
|
||||
<Dropzone ref={dropzoneRef} onDrop={onDrop} multiple={false} noClick noKeyboard
|
||||
accept={{ 'image/*': ['.png', '.bmp', '.jpeg', '.jpg', '.webp'] }}
|
||||
>
|
||||
{/* @ts-ignore */}
|
||||
{({ getRootProps, getInputProps, acceptedFiles }) => {
|
||||
return (
|
||||
<div {...getRootProps()}
|
||||
className="border-input data-[dragging=true]:bg-accent/50 has-[input:focus]:border-ring has-[input:focus]:ring-ring/50 relative flex min-h-52 flex-col items-center overflow-hidden rounded-xl border border-dashed p-4 transition-colors not-data-files:justify-center has-[input:focus]:ring-[3px]"
|
||||
>
|
||||
<input {...getInputProps()} className="sr-only" aria-label="Upload image file" />
|
||||
|
||||
{currentFile?.base64 || existFile ? (
|
||||
<div className="flex w-full flex-col gap-3">
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<h3 className="truncate text-sm font-medium">
|
||||
Current Image
|
||||
</h3>
|
||||
<Button type='button' variant="outline" size="sm" onClick={openDialog}>
|
||||
<UploadIcon className="-ms-0.5 size-3.5 opacity-60" aria-hidden="true" />
|
||||
Change Image
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 my-4">
|
||||
<LazyImage src={currentFile?.base64 || existFile} alt='gambar-campaign' className="size-full rounded-[inherit] object-cover" />
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex flex-col items-center justify-center px-4 py-3 text-center">
|
||||
<div className="bg-background mb-2 flex size-11 shrink-0 items-center justify-center rounded-full border" aria-hidden="true">
|
||||
<ImageIcon className="size-4 opacity-60" />
|
||||
</div>
|
||||
<p className="mb-1.5 text-sm font-medium">Drop your files here</p>
|
||||
<p className="text-muted-foreground text-xs">
|
||||
SVG, PNG, JPG or GIF (max. {maxSizeMB}MB)
|
||||
</p>
|
||||
<Button type='button' variant="outline" className="mt-4" onClick={openDialog}>
|
||||
<UploadIcon className="-ms-1 opacity-60" aria-hidden="true" />
|
||||
Browse file
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
</div>
|
||||
);
|
||||
}}
|
||||
</Dropzone>
|
||||
</div>
|
||||
</div>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel onClick={onCancel} disabled={isLoading} type='button'>Cancel</AlertDialogCancel>
|
||||
<Button type="submit" disabled={isLoading}>
|
||||
{isLoading && <Loader2 className='animate-spin' />}
|
||||
Save Client
|
||||
</Button>
|
||||
</AlertDialogFooter>
|
||||
</form>
|
||||
</Form>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
|
||||
{showEnduserForm ?
|
||||
<FormEndUser onCancel={() => setShowEndUserForm(false)} onSuccess={() => { mutate(); setShowEndUserForm(false); }} /> : null
|
||||
}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export default FormClient;
|
||||
@@ -0,0 +1,249 @@
|
||||
import { useCallback, useEffect, useRef, useState, type FC } from 'react';
|
||||
import {
|
||||
AlertDialog, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle
|
||||
} from "@/components/ui/alert-dialog"
|
||||
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage, } from "@/components/ui/form";
|
||||
import * as Yup from 'yup'
|
||||
import { yupResolver } from '@hookform/resolvers/yup';
|
||||
import { IEndUser } from '../types';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { toast } from 'sonner';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { ImageIcon, Loader2, UploadIcon } from 'lucide-react';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { serverApiCall } from '@/lib/server-api';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
import Dropzone from 'react-dropzone';
|
||||
import { LazyImage } from '@/components/ui/lazy-image';
|
||||
import { Label } from '@/components/ui/label';
|
||||
|
||||
const validationSchema = Yup.object().shape({
|
||||
name: Yup.string().required(),
|
||||
description: Yup.string().optional().default(''),
|
||||
});
|
||||
|
||||
type FormDataType = Yup.InferType<typeof validationSchema>;
|
||||
|
||||
type Props = {
|
||||
data?: IEndUser
|
||||
onCancel?: VoidFunction
|
||||
onSuccess?: VoidFunction;
|
||||
};
|
||||
|
||||
const FormEndUser: FC<Props> = ({ data, onSuccess, onCancel }) => {
|
||||
const [currentFile, setCurrentFile] = useState<any | undefined>(undefined);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
|
||||
const existFile = data?.photo || null
|
||||
const dropzoneRef = useRef<any>(null);
|
||||
const maxSizeMB = 5
|
||||
|
||||
const openDialog = () => {
|
||||
// Note that the ref is set async,
|
||||
// so it might be null at some point
|
||||
if (dropzoneRef.current) {
|
||||
dropzoneRef.current.open();
|
||||
}
|
||||
};
|
||||
|
||||
const onDrop = useCallback((acceptedFiles: any[]) => {
|
||||
acceptedFiles.forEach(async (file: any) => {
|
||||
const reader = new FileReader();
|
||||
|
||||
reader.onabort = () => console.log('file reading was aborted');
|
||||
reader.onerror = () => console.log('file reading has failed');
|
||||
reader.onload = async () => {
|
||||
// Do whatever you want with the file contents
|
||||
const binaryStr = reader.result;
|
||||
|
||||
console.log(file)
|
||||
setCurrentFile({ file: file, base64: binaryStr?.toString() });
|
||||
};
|
||||
reader.readAsDataURL(file);
|
||||
});
|
||||
}, []);
|
||||
|
||||
|
||||
const form = useForm<FormDataType>({
|
||||
resolver: yupResolver(validationSchema),
|
||||
defaultValues: {
|
||||
"name": data?.name || '',
|
||||
'description': data?.description || '',
|
||||
},
|
||||
});
|
||||
|
||||
const handleUploadFile = async () => {
|
||||
setIsLoading(true)
|
||||
const toastId = toast.loading('Uploading image...');
|
||||
let fullPathImage = ''
|
||||
|
||||
try {
|
||||
const resPresignUrl: any = await serverApiCall('POST', '/s3', {
|
||||
"filename": currentFile?.file?.name,
|
||||
"type": currentFile?.file?.type,
|
||||
"bucket": "hats-end-user"
|
||||
})
|
||||
|
||||
console.log({ resPresignUrl })
|
||||
|
||||
if (resPresignUrl.success) {
|
||||
fullPathImage = `${process.env.NEXT_PUBLIC_S3_IMAGE_URL}/${resPresignUrl?.data?.data?.path_url}`
|
||||
const presignedUrl = resPresignUrl?.data?.data?.upload_url
|
||||
|
||||
const uploadResponse = await fetch(presignedUrl, {
|
||||
method: 'PUT',
|
||||
body: currentFile?.file, // Send the raw file directly
|
||||
headers: {
|
||||
'Content-Type': currentFile?.file?.type,
|
||||
},
|
||||
});
|
||||
|
||||
if (!uploadResponse.ok) {
|
||||
throw new Error("Failed to upload image to storage 😢");
|
||||
}
|
||||
} else {
|
||||
toast.error("Oops sorry, error has occurred 😢", {
|
||||
description: `(${resPresignUrl.code}) ${resPresignUrl.message || "An unexpected error occurred while Getting Presigned URL. Please try again later."}`,
|
||||
id: toastId
|
||||
})
|
||||
}
|
||||
} catch (error: any) {
|
||||
toast.error(`Failed uploading image.\n(${error?.response?.data?.code || error?.response?.status || '-'}) ${error?.response?.data?.message || error?.response?.statusText || error?.message}`, { id: toastId });
|
||||
} finally {
|
||||
setIsLoading(false)
|
||||
}
|
||||
|
||||
return fullPathImage
|
||||
}
|
||||
|
||||
const onSubmit = async (payload: FormDataType) => {
|
||||
setIsLoading(true);
|
||||
|
||||
let newPayload: any = { ...payload }
|
||||
|
||||
if (currentFile?.file) {
|
||||
const photoPath = await handleUploadFile()
|
||||
newPayload['photo'] = photoPath
|
||||
} else {
|
||||
newPayload['photo'] = data?.photo
|
||||
}
|
||||
|
||||
let res: any
|
||||
if (data) {
|
||||
res = await serverApiCall('PUT', `/end-user/${data.id}`, newPayload)
|
||||
} else {
|
||||
res = await serverApiCall('POST', '/end-user', newPayload)
|
||||
}
|
||||
|
||||
setIsLoading(false)
|
||||
if (res.success) {
|
||||
toast.success('End User saved successfully')
|
||||
onSuccess!()
|
||||
} else {
|
||||
toast.error(`Fail to save end user`, { description: `(${res.code || '-'}) ${res.message}` })
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<AlertDialog open={true}>
|
||||
<AlertDialogContent className='max-h-[90vh] overflow-y-auto'>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>EndUser Information</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
Enter the basic details of the EndUser.
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<Form {...form}>
|
||||
<form onSubmit={form.handleSubmit(onSubmit)}>
|
||||
<div className="grid grid-cols-1 gap-4 mb-6">
|
||||
<FormField control={form.control} name='name'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>EndUser Name <span className='text-red-600 font-bold'>*</span></FormLabel>
|
||||
<FormControl>
|
||||
<Input {...field} placeholder='e.g. PT ASDP Indonesia Ferry' />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField control={form.control} name='description'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Description</FormLabel>
|
||||
<FormControl>
|
||||
<Textarea {...field} placeholder='Describe a little about the end user.' />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<div className="flex flex-col gap-2">
|
||||
<Label>Add End User Image</Label>
|
||||
{/* Drop area */}
|
||||
<Dropzone ref={dropzoneRef} onDrop={onDrop} multiple={false} noClick noKeyboard
|
||||
accept={{ 'image/*': ['.png', '.bmp', '.jpeg', '.jpg', '.webp'] }}
|
||||
>
|
||||
{/* @ts-ignore */}
|
||||
{({ getRootProps, getInputProps, acceptedFiles }) => {
|
||||
return (
|
||||
<div {...getRootProps()}
|
||||
className="border-input data-[dragging=true]:bg-accent/50 has-[input:focus]:border-ring has-[input:focus]:ring-ring/50 relative flex min-h-52 flex-col items-center overflow-hidden rounded-xl border border-dashed p-4 transition-colors not-data-files:justify-center has-[input:focus]:ring-[3px]"
|
||||
>
|
||||
<input {...getInputProps()} className="sr-only" aria-label="Upload image file" />
|
||||
|
||||
{currentFile?.base64 || existFile ? (
|
||||
<div className="flex w-full flex-col gap-3">
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<h3 className="truncate text-sm font-medium">
|
||||
Current Image
|
||||
</h3>
|
||||
<Button type='button' variant="outline" size="sm" onClick={openDialog}>
|
||||
<UploadIcon className="-ms-0.5 size-3.5 opacity-60" aria-hidden="true" />
|
||||
Change Image
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 my-4">
|
||||
<LazyImage src={currentFile?.base64 || existFile} alt='gambar-campaign' className="size-full rounded-[inherit] object-cover" />
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex flex-col items-center justify-center px-4 py-3 text-center">
|
||||
<div className="bg-background mb-2 flex size-11 shrink-0 items-center justify-center rounded-full border" aria-hidden="true">
|
||||
<ImageIcon className="size-4 opacity-60" />
|
||||
</div>
|
||||
<p className="mb-1.5 text-sm font-medium">Drop your files here</p>
|
||||
<p className="text-muted-foreground text-xs">
|
||||
SVG, PNG, JPG or GIF (max. {maxSizeMB}MB)
|
||||
</p>
|
||||
<Button type='button' variant="outline" className="mt-4" onClick={openDialog}>
|
||||
<UploadIcon className="-ms-1 opacity-60" aria-hidden="true" />
|
||||
Browse file
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
</div>
|
||||
);
|
||||
}}
|
||||
</Dropzone>
|
||||
</div>
|
||||
</div>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel onClick={onCancel} disabled={isLoading} type='button'>Cancel</AlertDialogCancel>
|
||||
<Button type="submit" disabled={isLoading}>
|
||||
{isLoading && <Loader2 className='animate-spin' />}
|
||||
Save EndUser
|
||||
</Button>
|
||||
</AlertDialogFooter>
|
||||
</form>
|
||||
</Form>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export default FormEndUser;
|
||||
@@ -0,0 +1,108 @@
|
||||
import { useState, type FC } from 'react';
|
||||
import {
|
||||
AlertDialog, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle
|
||||
} from "@/components/ui/alert-dialog"
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Select, SelectContent, SelectGroup, SelectItem, SelectLabel, SelectTrigger, SelectValue } from '@/components/ui/select';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
import * as Yup from 'yup'
|
||||
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage, } from "@/components/ui/form";
|
||||
import { yupResolver } from '@hookform/resolvers/yup';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { IProjectAssignment, STATUS_LIST } from '../type.assignment';
|
||||
import { DatePicker } from '@/components/ui/datepicker';
|
||||
import { Loader2 } from 'lucide-react';
|
||||
|
||||
const validationSchema = Yup.object().shape({
|
||||
status: Yup.string().required(),
|
||||
date: Yup.date().required('Date is required'),
|
||||
note: Yup.string().optional().default(''),
|
||||
});
|
||||
|
||||
type FormDataType = Yup.InferType<typeof validationSchema>;
|
||||
|
||||
type Props = {
|
||||
title: string
|
||||
data?: IProjectAssignment
|
||||
onCancel?: VoidFunction
|
||||
onSuccess?: VoidFunction;
|
||||
};
|
||||
|
||||
const FormUpdateStatus: FC<Props> = ({ title, data, onCancel, onSuccess }) => {
|
||||
const [isLoading, setIsLoading] = useState(false)
|
||||
|
||||
const form = useForm<FormDataType>({
|
||||
resolver: yupResolver(validationSchema),
|
||||
});
|
||||
|
||||
const onSubmit = async (payload: FormDataType) => {
|
||||
setIsLoading(true);
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<AlertDialog open={true} >
|
||||
<AlertDialogContent className="max-w-md">
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>Update Status</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
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>Kategori</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>
|
||||
<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>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export default FormUpdateStatus;
|
||||
@@ -0,0 +1,78 @@
|
||||
// app/clients/components/dashboard-shell.tsx
|
||||
"use client"
|
||||
|
||||
import { useState } from 'react';
|
||||
import { useRouter, usePathname, useSearchParams } from 'next/navigation';
|
||||
import { Plus, Search, LayoutGrid, List } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs';
|
||||
import FormClient from './FormClient';
|
||||
|
||||
interface ShellProps {
|
||||
currentView: 'grid' | 'table';
|
||||
currentQuery: string;
|
||||
}
|
||||
|
||||
export default function HomeTask({ currentView, currentQuery }: ShellProps) {
|
||||
const router = useRouter();
|
||||
const pathname = usePathname();
|
||||
const searchParams = useSearchParams();
|
||||
|
||||
const [showForm, setShowForm] = useState(false);
|
||||
|
||||
// Update URL when Tabs change
|
||||
const handleTabChange = (view: string) => {
|
||||
const params = new URLSearchParams(searchParams!);
|
||||
params.set('view', view);
|
||||
router.push(`${pathname}?${params.toString()}`);
|
||||
};
|
||||
|
||||
// Update URL when typing (Debouncing recommended for production)
|
||||
const handleSearch = (term: string) => {
|
||||
const params = new URLSearchParams(searchParams!);
|
||||
if (term) {
|
||||
params.set('q', term);
|
||||
} else {
|
||||
params.delete('q');
|
||||
}
|
||||
// Use replace so we don't clutter the browser history with every keystroke
|
||||
router.replace(`${pathname}?${params.toString()}`);
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="flex flex-col md:flex-row md:items-center justify-between gap-4">
|
||||
<div>
|
||||
<h1 className="text-lg sm:text-3xl font-medium tracking-tight capitalize">My Task & Projects</h1>
|
||||
<p className="text-xs md:text-base text-muted-foreground w-full lg:w-1/2 xl:w-3/4 mt-2">
|
||||
Something that can be done at any time is often done at no time.
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex items-center gap-3">
|
||||
<Tabs value={currentView} onValueChange={handleTabChange} className="w-auto">
|
||||
<TabsList>
|
||||
<TabsTrigger value="grid" className="gap-2"><LayoutGrid className="w-4 h-4" /> Clients</TabsTrigger>
|
||||
<TabsTrigger value="table" className="gap-2"><List className="w-4 h-4" /> Assignments</TabsTrigger>
|
||||
</TabsList>
|
||||
</Tabs>
|
||||
<Button className="gap-2" onClick={() => setShowForm(true)}>
|
||||
<Plus className="w-4 h-4" /> Add Client
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="relative">
|
||||
<Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
|
||||
<Input
|
||||
placeholder="Search clients, projects, or work orders..."
|
||||
className="pl-10"
|
||||
defaultValue={currentQuery}
|
||||
onChange={(e) => handleSearch(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{showForm && <FormClient onCancel={() => setShowForm(false)} onSuccess={() => { setShowForm(false); router.refresh() }} />}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
"use client"
|
||||
|
||||
import { useState, type FC } from 'react';
|
||||
import {
|
||||
AlertDialog, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle
|
||||
} from "@/components/ui/alert-dialog"
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { Check, Loader2 } from 'lucide-react';
|
||||
import { useFetchWithAxios } from '@/lib/axios/useFetch';
|
||||
import { IUser } from '@/app/admin/administration/user/component/type';
|
||||
import { LazyImage } from '@/components/ui/lazy-image';
|
||||
import { Skeleton } from '@/components/ui/skeleton';
|
||||
import { IProjectAssignment } from '../type.assignment';
|
||||
|
||||
type Props = {
|
||||
data: IProjectAssignment
|
||||
title: string
|
||||
onCancel?: VoidFunction
|
||||
onSuccess?: VoidFunction;
|
||||
};
|
||||
|
||||
const ManageEmployee: FC<Props> = ({ title, onCancel, onSuccess }) => {
|
||||
const [selectedEmployeeIds, setSelectedEmployeeIds] = useState<number[]>([]);
|
||||
const [isLoading, setIsLoading] = useState(false)
|
||||
|
||||
const { data, isLoading: isLoadingFetchUser } = useFetchWithAxios('/user')
|
||||
|
||||
const toggleEmployee = (empId: number) => {
|
||||
setSelectedEmployeeIds(prev =>
|
||||
prev.includes(empId) ? prev.filter(i => i !== empId) : [...prev, empId]
|
||||
);
|
||||
};
|
||||
|
||||
const handleAssignEmployee = async () => {
|
||||
setIsLoading(true)
|
||||
onSuccess!()
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<AlertDialog open={true}>
|
||||
<AlertDialogContent className="max-w-md">
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>Manage Team</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
Assign or remove employees for <strong>{title}</strong>
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<div className="grid gap-4 py-4 max-h-[400px] overflow-y-auto pr-2">
|
||||
{isLoadingFetchUser ?
|
||||
<div className='space-y-2'>
|
||||
<Skeleton className='h-10 w-full' />
|
||||
<Skeleton className='h-10 w-full' />
|
||||
<Skeleton className='h-10 w-full' />
|
||||
<Skeleton className='h-10 w-full' />
|
||||
<Skeleton className='h-10 w-full' />
|
||||
</div>
|
||||
:
|
||||
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>
|
||||
}
|
||||
</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>
|
||||
))
|
||||
}
|
||||
</div>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel onClick={onCancel} disabled={isLoading}>Cancel</AlertDialogCancel>
|
||||
<Button type='submit' disabled={isLoading}>{isLoading ? <Loader2 /> : null} Save Changes</Button>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export default ManageEmployee;
|
||||
@@ -0,0 +1,339 @@
|
||||
"use client"
|
||||
|
||||
import { motion } from 'motion/react';
|
||||
import { Plus, Search, MoreHorizontal, ExternalLink, Users, LayoutGrid, List } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Card, CardContent } from '@/components/ui/card';
|
||||
import {
|
||||
DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger,
|
||||
} from '@/components/ui/dropdown-menu';
|
||||
import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs';
|
||||
import {
|
||||
Table, TableBody, TableCell, TableHead, TableHeader, TableRow,
|
||||
} from '@/components/ui/table';
|
||||
import {
|
||||
Tooltip, TooltipContent, TooltipTrigger,
|
||||
} from '@/components/ui/tooltip';
|
||||
import { useState } from 'react';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { useAppState } from '@/hooks/useDummyTaskData';
|
||||
import Link from 'next/link';
|
||||
import { LazyImage } from '@/components/ui/lazy-image';
|
||||
import { DUMMY_EMPLOYEES, IClient } from './types';
|
||||
import ClientForm from './component/FormClient';
|
||||
|
||||
export default function Clients() {
|
||||
const [search, setSearch] = useState('');
|
||||
const [view, setView] = useState<'grid' | 'table'>('grid');
|
||||
const [selectedData, setSelectedData] = useState<IClient | undefined>()
|
||||
const [showForm, setShowForm] = useState(false)
|
||||
|
||||
const { clients, assignments } = useAppState();
|
||||
|
||||
const filteredClients = clients.filter((c) =>
|
||||
c.name.toLowerCase().includes(search.toLowerCase()) ||
|
||||
c.endUser.toLowerCase().includes(search.toLowerCase())
|
||||
);
|
||||
|
||||
// Flatten data for table view
|
||||
const masterData = assignments.flatMap((assignment: any) => {
|
||||
const client = clients.find(c => c.id === assignment.clientId);
|
||||
if (!client) return [];
|
||||
|
||||
// If no work orders, still show the assignment?
|
||||
// The user image shows WO details, so usually it's WO based.
|
||||
if (assignment.workOrder) {
|
||||
return [{
|
||||
client,
|
||||
assignment,
|
||||
wo: null
|
||||
}];
|
||||
}
|
||||
|
||||
return assignment.workOrder.map((wo: any) => ({
|
||||
client,
|
||||
assignment,
|
||||
wo
|
||||
}));
|
||||
}).filter((item: any) =>
|
||||
item.client.name.toLowerCase().includes(search.toLowerCase()) ||
|
||||
item.assignment.name.toLowerCase().includes(search.toLowerCase()) ||
|
||||
(item.wo?.name.toLowerCase().includes(search.toLowerCase()) ?? false)
|
||||
);
|
||||
|
||||
const handleClose = () => {
|
||||
setSelectedData(undefined)
|
||||
setShowForm(false)
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<motion.div
|
||||
initial={{ opacity: 0, x: 20 }}
|
||||
animate={{ opacity: 1, x: 0 }}
|
||||
exit={{ opacity: 0, x: -20 }}
|
||||
className="flex-1 space-y-8 p-6 sm:p-8 pt-6"
|
||||
>
|
||||
<div className="flex flex-col md:flex-row md:items-center justify-between gap-4">
|
||||
<div>
|
||||
<h1 className="text-lg sm:text-3xl font-medium tracking-tight capitalize">My Task & Projects</h1>
|
||||
<p className="text-xs md:text-base text-muted-foreground w-full lg:w-1/2 xl:w-3/4 mt-2">Something that can be done at any time is often done at no time. Do it now, or decide when you'll do it.</p>
|
||||
</div>
|
||||
<div className="flex items-center gap-3">
|
||||
<Tabs value={view} onValueChange={(v) => setView(v as 'grid' | 'table')} className="w-auto">
|
||||
<TabsList>
|
||||
<TabsTrigger value="grid" className="gap-2">
|
||||
<LayoutGrid className="w-4 h-4" />
|
||||
Grid
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="table" className="gap-2">
|
||||
<List className="w-4 h-4" />
|
||||
Table
|
||||
</TabsTrigger>
|
||||
</TabsList>
|
||||
</Tabs>
|
||||
<Button className="gap-2" onClick={() => setShowForm(true)}><Plus className="w-4 h-4" />Add Client</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="relative">
|
||||
<Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
|
||||
<Input
|
||||
placeholder="Search clients, projects, or work orders..."
|
||||
className="pl-10"
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{view === 'grid' ? (
|
||||
<div className="grid gap-6 md:grid-cols-2 lg:grid-cols-3">
|
||||
{filteredClients.map((client, i) => {
|
||||
const clientAssignments = assignments.filter(a => a.clientId === client.id);
|
||||
const imCount = clientAssignments.filter(a => a.type === 'IM').length;
|
||||
const projectCount = clientAssignments.filter(a => a.type === 'Project').length;
|
||||
// const woCount = clientAssignments.reduce((acc, a) => acc + a.workOrders.length, 0);
|
||||
const woCount = 1
|
||||
const assignedEmployeeIds = Array.from(new Set(clientAssignments.flatMap(a => a.assignedEmployees)));
|
||||
|
||||
return (
|
||||
<motion.div
|
||||
key={client.id}
|
||||
initial={{ opacity: 0, scale: 0.95 }}
|
||||
animate={{ opacity: 1, scale: 1 }}
|
||||
transition={{ delay: i * 0.05 }}
|
||||
className="h-full"
|
||||
>
|
||||
<Card className="h-full group overflow-hidden hover:shadow-lg transition-all duration-300 border-primary/5 hover:border-primary/20 flex flex-col py-0">
|
||||
<CardContent className="p-0 flex flex-col h-full">
|
||||
<div className="relative h-32 bg-accent/50 overflow-hidden">
|
||||
<LazyImage
|
||||
src={client.imageUrl}
|
||||
alt={client.name}
|
||||
className="w-full h-full object-cover group-hover:scale-110 transition-transform duration-500"
|
||||
/>
|
||||
<div className="absolute inset-0 bg-linear-to-t from-black/80 via-black/40 to-transparent" />
|
||||
<div className="absolute bottom-4 left-4 right-4 flex items-end justify-between">
|
||||
<div className="text-white">
|
||||
<h3 className="font-bold text-lg leading-tight">{client.name}</h3>
|
||||
<p className="text-xs opacity-80">{client.endUser}</p>
|
||||
</div>
|
||||
<Link href={`/task/client-detail/${client.id}`}>
|
||||
<Button size="icon" variant="secondary" className="h-8 w-8 rounded-full opacity-0 group-hover:opacity-100 transition-opacity">
|
||||
<ExternalLink className="w-4 h-4" />
|
||||
</Button>
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
<div className="p-5 flex flex-col flex-1 justify-between gap-4">
|
||||
<div className="space-y-2">
|
||||
{/* <p className="text-sm leading-relaxed text-muted-foreground line-clamp-3 h-16">
|
||||
Currently managing a portfolio of <span className="font-bold text-foreground">{projectCount} projects</span> and <span className="font-bold text-foreground">{imCount} internal memos</span>.
|
||||
A dedicated team of <span className="font-bold text-foreground">{assignedEmployeeIds.length} experts</span> is handling <span className="font-bold text-foreground">{woCount} work orders</span> to ensure successful delivery for <span className="italic">{client.endUser}</span>.
|
||||
</p> */}
|
||||
<p className="text-sm leading-relaxed text-muted-foreground line-clamp-3 h-16">
|
||||
{projectCount === 0 && imCount === 0 && woCount === 0 ?
|
||||
"No active projects, internal memos, or work orders recorded for this client yet."
|
||||
:
|
||||
<>
|
||||
{(projectCount > 0 || imCount > 0) && (
|
||||
<>
|
||||
Currently managing a portfolio of{" "}
|
||||
{projectCount > 0 &&
|
||||
<span className="font-bold text-foreground">{projectCount} project{projectCount > 1 ? 's' : ''}</span>
|
||||
}
|
||||
{projectCount > 0 && imCount > 0 && " and "}
|
||||
{imCount > 0 &&
|
||||
<span className="font-bold text-foreground">{imCount} internal memo{imCount > 1 ? 's' : ''}</span>
|
||||
}
|
||||
.{" "}
|
||||
</>
|
||||
)}
|
||||
{woCount > 0 && (
|
||||
<>
|
||||
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>.
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-between pt-4 pb-2 border-t border-border">
|
||||
<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);
|
||||
return (
|
||||
<div key={empId}>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<LazyImage
|
||||
className="inline-block h-8 w-8 rounded-full ring-2 ring-background object-cover"
|
||||
src={emp?.avatar!}
|
||||
alt={emp?.name!}
|
||||
/>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>
|
||||
<p className="text-xs font-bold">{emp?.name}</p>
|
||||
<p className="text-[10px] opacity-80">{emp?.role}</p>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
{assignedEmployeeIds.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}
|
||||
</div>
|
||||
)}
|
||||
{assignedEmployeeIds.length === 0 && (
|
||||
<span className="text-[10px] text-muted-foreground italic">No team assigned</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-2 self-end">
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="ghost" size="icon" className="h-8 w-8">
|
||||
<MoreHorizontal className="w-4 h-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuItem asChild>
|
||||
<Link href={`/task/client-detail/${client.id}`}>View Client Detail</Link>
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onSelect={() => { setShowForm(true); setSelectedData(client) }}>Edit Client</DropdownMenuItem>
|
||||
<DropdownMenuItem className="text-destructive">Delete Client</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</motion.div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
) : (
|
||||
<Card className="overflow-hidden">
|
||||
<div className="overflow-x-auto">
|
||||
<Table>
|
||||
<TableHeader className="bg-accent/50">
|
||||
<TableRow>
|
||||
<TableHead className="min-w-[150px]">Client</TableHead>
|
||||
<TableHead className="min-w-[120px]">End User</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>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>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{masterData.map((item, idx) => {
|
||||
const { client, assignment, wo } = item;
|
||||
const latestStatus = wo?.statusHistory?.[0] || assignment.statusHistory?.[0];
|
||||
|
||||
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>
|
||||
<TableCell className="font-medium">
|
||||
<Link href={`/assignments/${assignment.id}`} className="hover:underline text-blue-600 dark:text-blue-400">
|
||||
{assignment.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>
|
||||
<TableCell>{assignment.year || '-'}</TableCell>
|
||||
<TableCell className="whitespace-nowrap text-xs">
|
||||
{assignment.startDate ? new Date(assignment.startDate).toLocaleDateString() : '-'}
|
||||
</TableCell>
|
||||
<TableCell className="whitespace-nowrap text-xs">
|
||||
{assignment.endDate ? new Date(assignment.endDate).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>
|
||||
<TableCell className="whitespace-nowrap text-xs">
|
||||
{wo?.endDate ? new Date(wo.endDate).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>
|
||||
</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>
|
||||
</TableRow>
|
||||
);
|
||||
})}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{(view === 'grid' ? filteredClients : masterData).length === 0 && (
|
||||
<div className="py-12 text-center border-2 border-dashed rounded-xl">
|
||||
<Users className="w-12 h-12 mx-auto text-muted-foreground mb-4 opacity-20" />
|
||||
<h3 className="text-lg font-medium">No data found</h3>
|
||||
<p className="text-muted-foreground">Try adjusting your search or add new entries.</p>
|
||||
</div>
|
||||
)}
|
||||
</motion.div>
|
||||
|
||||
{showForm ?
|
||||
<ClientForm data={selectedData} onCancel={handleClose} onSuccess={handleClose} /> : null
|
||||
}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
import LazyLoading from "@/components/loader/LazyLoading"
|
||||
import { Suspense } from "react"
|
||||
import TaskComponent from "./component"
|
||||
|
||||
export default async function TaskPage() {
|
||||
const LIST_PROJECT = [
|
||||
{
|
||||
id: 1,
|
||||
title: 'Angksa Pura II',
|
||||
img: '/assets/projects/ap2.jpg'
|
||||
},
|
||||
{
|
||||
id: 2,
|
||||
title: 'ASDP',
|
||||
img: '/assets/projects/asdp.png'
|
||||
},
|
||||
{
|
||||
id: 4,
|
||||
title: 'Imigrasi',
|
||||
img: '/assets/projects/imigrasi.png'
|
||||
},
|
||||
{
|
||||
id: 3,
|
||||
title: 'JakLingko',
|
||||
img: '/assets/projects/jaklingko.png'
|
||||
},
|
||||
{
|
||||
id: 5,
|
||||
title: 'KAI Bandara',
|
||||
img: '/assets/projects/kaibandara.png'
|
||||
},
|
||||
{
|
||||
id: 6,
|
||||
title: 'KAI Commuter',
|
||||
img: '/assets/projects/kci.png'
|
||||
},
|
||||
{
|
||||
id: 7,
|
||||
title: 'LRT Jabodebek',
|
||||
img: '/assets/projects/lrtjabo.png'
|
||||
},
|
||||
{
|
||||
id: 8,
|
||||
title: 'LRT Jakarta',
|
||||
img: '/assets/projects/lrtjakarta.png'
|
||||
},
|
||||
{
|
||||
id: 9,
|
||||
title: 'LRT Sumsel',
|
||||
img: '/assets/projects/lrtsumsel.png'
|
||||
},
|
||||
{
|
||||
id: 10,
|
||||
title: 'Telkomsel',
|
||||
img: '/assets/projects/tsel.png'
|
||||
},
|
||||
{
|
||||
id: 11,
|
||||
title: 'Transjakarta',
|
||||
img: '/assets/projects/transjakarta.jpg'
|
||||
},
|
||||
{
|
||||
id: 12,
|
||||
title: 'Nutech Integrasi',
|
||||
img: '/assets/projects/nutech.png'
|
||||
},
|
||||
]
|
||||
return (
|
||||
<>
|
||||
<div className="flex-1 space-y-8 p-6 sm:p-8 pt-6 ">
|
||||
<div className="flex items-start justify-between space-y-2">
|
||||
<div>
|
||||
<h1 className="text-lg sm:text-3xl font-medium tracking-tight capitalize">My Task</h1>
|
||||
<p className="text-xs md:text-base text-muted-foreground w-1/2 mt-2 hidden md:block">Something that can be done at any time is often done at no time. Do it now, or decide when you'll do it.</p>
|
||||
</div>
|
||||
</div>
|
||||
<Suspense fallback={<LazyLoading />}>
|
||||
<TaskComponent projectList={LIST_PROJECT} />
|
||||
</Suspense>
|
||||
</div>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -1,83 +1,60 @@
|
||||
import LazyLoading from "@/components/loader/LazyLoading"
|
||||
import { Suspense } from "react"
|
||||
import TaskComponent from "./component"
|
||||
// app/clients/page.tsx
|
||||
import { Suspense } from 'react';
|
||||
import HomeTask from './component/HomeTask';
|
||||
import ClientGrid from './component/ClientGrid';
|
||||
import AssignmentTable from './component/AssignmentTable';
|
||||
import fetchData from '@/lib/fetchData';
|
||||
|
||||
type Props = {
|
||||
searchParams: Promise<{ view?: string; q?: string }>
|
||||
};
|
||||
|
||||
export default async function ClientsPage({ searchParams }: Props) {
|
||||
const params = await searchParams;
|
||||
const view = params.view === 'table' ? 'table' : 'grid';
|
||||
const query = (params.q || '').toLowerCase();
|
||||
|
||||
const getClient = fetchData('/client')
|
||||
const getAssignment = fetchData('/project-assignment')
|
||||
|
||||
// Wait for the promises to resolve
|
||||
const [allClients, allAssignments] = await Promise.all([getClient, getAssignment]);
|
||||
|
||||
// 3. Process Data for Grid View
|
||||
const filteredClients = allClients.filter((c: any) =>
|
||||
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)
|
||||
);
|
||||
|
||||
export default async function TaskPage() {
|
||||
const LIST_PROJECT = [
|
||||
{
|
||||
id: 1,
|
||||
title: 'Angksa Pura II',
|
||||
img: '/assets/projects/ap2.jpg'
|
||||
},
|
||||
{
|
||||
id: 2,
|
||||
title: 'ASDP',
|
||||
img: '/assets/projects/asdp.png'
|
||||
},
|
||||
{
|
||||
id: 4,
|
||||
title: 'Imigrasi',
|
||||
img: '/assets/projects/imigrasi.png'
|
||||
},
|
||||
{
|
||||
id: 3,
|
||||
title: 'JakLingko',
|
||||
img: '/assets/projects/jaklingko.png'
|
||||
},
|
||||
{
|
||||
id: 5,
|
||||
title: 'KAI Bandara',
|
||||
img: '/assets/projects/kaibandara.png'
|
||||
},
|
||||
{
|
||||
id: 6,
|
||||
title: 'KAI Commuter',
|
||||
img: '/assets/projects/kci.png'
|
||||
},
|
||||
{
|
||||
id: 7,
|
||||
title: 'LRT Jabodebek',
|
||||
img: '/assets/projects/lrtjabo.png'
|
||||
},
|
||||
{
|
||||
id: 8,
|
||||
title: 'LRT Jakarta',
|
||||
img: '/assets/projects/lrtjakarta.png'
|
||||
},
|
||||
{
|
||||
id: 9,
|
||||
title: 'LRT Sumsel',
|
||||
img: '/assets/projects/lrtsumsel.png'
|
||||
},
|
||||
{
|
||||
id: 10,
|
||||
title: 'Telkomsel',
|
||||
img: '/assets/projects/tsel.png'
|
||||
},
|
||||
{
|
||||
id: 11,
|
||||
title: 'Transjakarta',
|
||||
img: '/assets/projects/transjakarta.jpg'
|
||||
},
|
||||
{
|
||||
id: 12,
|
||||
title: 'Nutech Integrasi',
|
||||
img: '/assets/projects/nutech.png'
|
||||
},
|
||||
]
|
||||
return (
|
||||
<>
|
||||
<div className="flex-1 space-y-8 p-6 sm:p-8 pt-6 ">
|
||||
<div className="flex items-start justify-between space-y-2">
|
||||
<div>
|
||||
<h1 className="text-lg sm:text-3xl font-medium tracking-tight capitalize">My Task</h1>
|
||||
<p className="text-xs md:text-base text-muted-foreground w-1/2 mt-2 hidden md:block">Something that can be done at any time is often done at no time. Do it now, or decide when you'll do it.</p>
|
||||
</div>
|
||||
</div>
|
||||
<Suspense fallback={<LazyLoading />}>
|
||||
<TaskComponent projectList={LIST_PROJECT} />
|
||||
</Suspense>
|
||||
</div>
|
||||
</>
|
||||
)
|
||||
<div className="flex-1 space-y-8 p-6 sm:p-8 pt-6">
|
||||
|
||||
{/* The Shell manages the Search Input, Tabs, and "Add Client" Modal */}
|
||||
<HomeTask currentView={view} currentQuery={query} />
|
||||
|
||||
{/* Render the correct view based on the URL */}
|
||||
<Suspense fallback={<div className="animate-pulse h-96 bg-accent rounded-xl" />}>
|
||||
{view === 'grid' ?
|
||||
<ClientGrid clients={filteredClients} assignments={allAssignments} />
|
||||
:
|
||||
<AssignmentTable data={flattenedAssignments} />
|
||||
}
|
||||
</Suspense>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
export const STATUS_LIST = ["Not Started", "On Progress", "On Going", "Halted", "Issue", "SIT", "UAT", "PTR", "BAST", "Warranty", "End Of Support", "Canceled"]
|
||||
|
||||
export interface IProjectAssignment {
|
||||
id: number
|
||||
im_code: any
|
||||
im_description: any
|
||||
im_end_date: any
|
||||
im_name: any
|
||||
im_start_date: any
|
||||
im_year: any
|
||||
note: string
|
||||
project: Project
|
||||
project_status: ProjectStatus
|
||||
wo_code: string
|
||||
wo_description: string
|
||||
wo_name: string
|
||||
wo_end_date: string
|
||||
wo_warranty: any
|
||||
project_assignment_status_detail: ProjectAssignmentStatusDetail[]
|
||||
project_assignment_work_order_detail: any[]
|
||||
status: Status
|
||||
wo_start_date: string
|
||||
created_at: string
|
||||
users: any[]
|
||||
}
|
||||
|
||||
export interface Project {
|
||||
code: string
|
||||
id: number
|
||||
name: string
|
||||
year: string
|
||||
description: string
|
||||
start_date: string
|
||||
end_date: string
|
||||
status: any
|
||||
client: any
|
||||
}
|
||||
|
||||
export interface ProjectStatus {
|
||||
id: string
|
||||
name: string
|
||||
created_at: string
|
||||
}
|
||||
|
||||
export interface ProjectAssignmentStatusDetail {
|
||||
id: number
|
||||
date_status_changed: string
|
||||
status: string
|
||||
status_remarks: any
|
||||
created_at?: string
|
||||
}
|
||||
|
||||
export interface Status {
|
||||
name: string
|
||||
id: number
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
export type IEndUser = {
|
||||
id?: string;
|
||||
name: string;
|
||||
description: string;
|
||||
photo?: string
|
||||
};
|
||||
|
||||
export type IClient = {
|
||||
id?: string;
|
||||
name: string;
|
||||
endUser: string;
|
||||
imageUrl: string;
|
||||
createdAt?: string;
|
||||
end_user_id?: number
|
||||
photo?: string
|
||||
code?: string
|
||||
end_user_code?: string
|
||||
end_user_name?: string
|
||||
end_user_photo?: any
|
||||
status_id?: number
|
||||
status_code?: string
|
||||
status_name?: string
|
||||
total_project?: number
|
||||
total_work_order?: number
|
||||
total_user_assigned?: number
|
||||
users?: IEmployee[]
|
||||
created_at?: string
|
||||
created_by?: number
|
||||
updated_at?: string
|
||||
updated_by?: number
|
||||
deleted_at?: string
|
||||
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 const INITIAL_CLIENTS: IClient[] = [
|
||||
{
|
||||
id: 'c1',
|
||||
name: 'TechCorp Solutions',
|
||||
endUser: 'Global Logistics Inc.',
|
||||
imageUrl: 'https://picsum.photos/seed/tech/200/200',
|
||||
createdAt: new Date().toISOString(),
|
||||
},
|
||||
{
|
||||
id: 'c2',
|
||||
name: 'Creative Agency',
|
||||
endUser: 'Fashion Brand X',
|
||||
imageUrl: 'https://picsum.photos/seed/creative/200/200',
|
||||
createdAt: new Date().toISOString(),
|
||||
},
|
||||
];
|
||||
@@ -0,0 +1,63 @@
|
||||
import { useState } from "react";
|
||||
import { toast } from "sonner";
|
||||
import {
|
||||
AlertDialog, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle
|
||||
} from "@/components/ui/alert-dialog"
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Loader2 } from "lucide-react";
|
||||
import { serverApiCall } from "@/lib/server-api";
|
||||
|
||||
interface Props {
|
||||
endpoint?: string
|
||||
onSuccess?: () => void;
|
||||
onCancel?: () => void;
|
||||
title?: string
|
||||
description?: string,
|
||||
method?: any
|
||||
}
|
||||
|
||||
export function ConfirmDelete({ endpoint, title, description, onSuccess, onCancel, method }: Props) {
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
|
||||
const handleDelete = async () => {
|
||||
setIsLoading(true)
|
||||
const toastId = toast.loading('Deleting data...');
|
||||
try {
|
||||
const res = await serverApiCall(method || 'DELETE', endpoint!)
|
||||
|
||||
if (res.success) {
|
||||
toast.success("Data deleted successfully ☺️", { id: toastId });
|
||||
onSuccess!()
|
||||
} else {
|
||||
toast.error("Oops sorry, error has occurred 😢", {
|
||||
description: `(${res.code}) ${res.message || "An unexpected error occurred while saving data. Please try again later."}`,
|
||||
id: toastId
|
||||
})
|
||||
}
|
||||
} catch (error: any) {
|
||||
toast.error(error.message, { id: toastId })
|
||||
} finally {
|
||||
setIsLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<AlertDialog open={true}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>{title || 'Are you absolutely sure?'}</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
{description || "This action cannot be undone. This will permanently delete this data and remove our servers."}
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel onClick={onCancel}>Cancel</AlertDialogCancel>
|
||||
<Button onClick={handleDelete} disabled={isLoading} variant='destructive'>
|
||||
{isLoading && <Loader2 className="animate-spin" />}
|
||||
{isLoading ? "Deleting..." : "Continue"}
|
||||
</Button>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
import { IClient, INITIAL_CLIENTS, IProjectAssignment } from '@/app/(dashboard)/task/types';
|
||||
import { useState, useEffect } from 'react';
|
||||
|
||||
export function useAppState() {
|
||||
const [clients, setClients] = useState<IClient[]>(() => {
|
||||
const saved = localStorage.getItem('clients');
|
||||
return saved ? JSON.parse(saved) : INITIAL_CLIENTS;
|
||||
});
|
||||
|
||||
const [assignments, setAssignments] = useState<IProjectAssignment[]>(() => {
|
||||
const saved = localStorage.getItem('assignments');
|
||||
return saved ? JSON.parse(saved) : [];
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
localStorage.setItem('clients', JSON.stringify(clients));
|
||||
}, [clients]);
|
||||
|
||||
useEffect(() => {
|
||||
localStorage.setItem('assignments', JSON.stringify(assignments));
|
||||
}, [assignments]);
|
||||
|
||||
const addClient = (client: IClient) => {
|
||||
setClients((prev) => [...prev, client]);
|
||||
};
|
||||
|
||||
const addAssignment = (assignment: IProjectAssignment) => {
|
||||
setAssignments((prev) => [...prev, assignment]);
|
||||
};
|
||||
|
||||
const updateAssignment = (id: string, updates: Partial<IProjectAssignment>) => {
|
||||
setAssignments((prev) =>
|
||||
prev.map((a) => (a.id === id ? { ...a, ...updates } : a))
|
||||
);
|
||||
};
|
||||
|
||||
return {
|
||||
clients,
|
||||
assignments,
|
||||
addClient,
|
||||
addAssignment,
|
||||
updateAssignment,
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user