Files
hats-app/app/(dashboard)/task/component/ManageTeam.tsx
T
Ichsan Kurniawan d61e424012 Refactor task UI, forms and team/status flows
Consolidate and improve client/task UI and related forms:

- Replace/rename modal components: use ManageTeam and UpdateTimelineStatus consistently (replace previous ManageEmployee/FormUpdateStatus imports/usages).
- ClientDetail: update grid layout, add End User column in table view, guard status with optional chaining, adjust avatar size, and minor label tweaks.
- Project/Assignment forms: add end_user_id to assignment schema and form, fetch end-users, integrate ComboboxCustomUI and lazy image rendering for end-user selection, allow creating end-user inline, and fix autofill mappings for project selection. Improve loading handling and payload construction for create/update flows.
- Project assignments page: switch to fetching project list endpoint and pass correct project type to form.
- WorkOrderCard & AssignmentDetail: optional chaining for status, use correct selected IDs for modals, and ensure ManageTeam receives real assignment id.
- ManageTeam: update data shape (field renames: fullname, position, start_date, end_date, status strings), change PUT endpoint for updating assignment user, improve empty-state copy and avatar/fallback handling, adjust status select values.
- UpdateTimelineStatus: remove unused form, adjust payload mapping, make dialog scrollable, tweak layout and textarea sizing.
- AssignmentTable & ClientDetail table: adjust column widths, truncation classes, and use assignment.end_user where appropriate.
- Small UX/cleanup: hide category filter on HomeTask, comment out end_user in FormClient, minor spacing/formatting cleanups, and a temporary console.log in page.tsx.

These changes improve UI consistency, add explicit end-user handling across forms, harden status access with optional chaining, and align API usages and data shapes for team/status operations.
2026-04-27 18:33:20 +07:00

252 lines
14 KiB
TypeScript

"use client"
import { useState } from "react";
import {
Edit2, Trash2, Save, X, Loader2, UserPlus
} from "lucide-react";
import {
Table, TableBody, TableCell, TableHead, TableHeader, TableRow
} from "@/components/ui/table";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import {
Select, SelectContent, SelectItem, SelectTrigger, SelectValue
} from "@/components/ui/select";
import { DatePicker } from "@/components/ui/datepicker";
import BadgeStatus from "@/components/ui/badge-status";
import {
AlertDialog, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle
} from "@/components/ui/alert-dialog"
import AddTeam from "./AddTeam";
import { useFetchWithAxios } from "@/lib/axios/useFetch";
import { Skeleton } from "@/components/ui/skeleton";
import { ConfirmDelete } from "@/components/modal/ConfirmDelete";
import { useRouter } from "next/navigation";
import { toast } from "sonner";
import { serverApiCall } from "@/lib/server-api";
export interface ITableData {
id: string;
fullname: string;
email: string;
avatar: string;
position: any;
start_date: string;
end_date: string;
status: string
}
export function ManageTeam({ assignmentId, onClose }: { assignmentId: number, onClose: VoidFunction }) {
const [editingId, setEditingId] = useState<string | null>(null);
const [draftData, setDraftData] = useState<Partial<ITableData>>({});
const [isSaving, setIsSaving] = useState(false);
const [showAddTeamDialog, setShowAddTeamDialog] = useState(false);
const [deletedId, setDeletedId] = useState<string | null>(null);
const { data: existUserAssign, isLoading, mutate } = useFetchWithAxios(`/project-assignment/assign-user/${assignmentId}`)
const router = useRouter()
const handleEdit = (row: ITableData) => {
setEditingId(row.id);
setDraftData({
start_date: row.start_date,
end_date: row.end_date,
status: row.status,
});
};
const handleSave = async () => {
setIsSaving(true);
const submitPayload = {
"project_assignment_id": assignmentId,
"status": draftData.status,
"start_date": draftData.start_date ? new Date(draftData.start_date).toISOString() : '',
"end_date": draftData.end_date ? new Date(draftData.end_date).toISOString() : '',
}
console.log(submitPayload)
const res = await serverApiCall('PUT', `/project-assignment/assign-user/update/${draftData.id}`, submitPayload)
setIsSaving(false);
if (res.success) {
toast.success('Team updated successfully')
handleSuccess!()
} else {
toast.error(`Fail to save team`, { description: `(${res.code || '-'}) ${res.message}` })
}
};
const handleDraftChange = (field: keyof ITableData, value: string) => {
setDraftData((prev) => ({ ...prev, [field]: value }));
};
const handleCancel = () => {
setEditingId(null);
setDraftData({});
setShowAddTeamDialog(false);
setDeletedId(null)
};
const handleSuccess = () => {
handleCancel()
mutate()
router.refresh()
}
return (
<>
<AlertDialog open={true} >
<AlertDialogContent className="min-w-full md:min-w-max">
<div className="flex flex-col sm:flex-row justify-between gap-3">
<AlertDialogHeader>
<AlertDialogTitle>Manage Team</AlertDialogTitle>
<AlertDialogDescription>
Add team members and manage who is working on each project assignment.
</AlertDialogDescription>
</AlertDialogHeader>
<Button size='sm' variant='outline' onClick={() => setShowAddTeamDialog(true)}><UserPlus /> Add Team</Button>
</div>
<div className="rounded-md border bg-card overflow-x-auto my-3">
<Table>
<TableHeader>
<TableRow>
<TableHead className="w-75">Name</TableHead>
<TableHead>Start Date</TableHead>
<TableHead>End Date</TableHead>
<TableHead>Status</TableHead>
<TableHead className="text-right">Action</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{isLoading ?
<TableRow>
<TableCell colSpan={5} className="w-full space-y-3">
<Skeleton className='h-10 w-full' />
<Skeleton className='h-10 w-full' />
<Skeleton className='h-10 w-full' />
</TableCell>
</TableRow>
:
existUserAssign.length === 0 ?
<TableRow>
<TableCell colSpan={5} className="w-full py-6">
<div className="text-center text-muted-foreground flex flex-col items-center justify-center gap-4">
No team members have been added yet.<br />Create a team to get started with project assignments
<Button variant='outline' className="w-max" onClick={() => setShowAddTeamDialog(true)}><UserPlus /> Add Team</Button>
</div>
</TableCell>
</TableRow>
:
existUserAssign.map((row: ITableData) => {
const isEditing = editingId === row.id;
const isOtherRowEditing = editingId !== null && editingId !== row.id;
return (
<TableRow key={row.id}>
<TableCell>
<div className="flex items-center gap-3">
<Avatar className="h-9 w-9">
<AvatarImage src={row.avatar} alt={row.fullname} />
<AvatarFallback>{row.fullname?.charAt(0)}</AvatarFallback>
</Avatar>
<div className="flex flex-col">
<div className="flex items-center gap-1">
<span className="font-medium text-sm leading-none">{row.fullname}</span>
<Badge variant="secondary" className="ml-auto">{row.position?.name}</Badge>
</div>
<span className="text-xs text-muted-foreground mt-1">{row.email}</span>
</div>
</div>
</TableCell>
<TableCell>
{isEditing ?
<DatePicker date={draftData.start_date as Date | undefined} setDate={(date) => handleDraftChange("start_date", date as any)} />
:
<span className="text-sm">{row.start_date}</span>
}
</TableCell>
<TableCell>
{isEditing ?
<DatePicker date={draftData.end_date as Date | undefined} setDate={(date) => handleDraftChange("end_date", date as any)} />
:
<span className="text-sm">{row.end_date}</span>
}
</TableCell>
<TableCell>
{isEditing ?
<Select value={draftData.status} onValueChange={(value) => handleDraftChange("status", value)}>
<SelectTrigger className="h-8 w-32.5 dark:bg-zinc-950">
<SelectValue placeholder="Select status" />
</SelectTrigger>
<SelectContent>
<SelectItem value="ACTIVE">Active</SelectItem>
<SelectItem value="INACTIVE">In Active</SelectItem>
</SelectContent>
</Select>
:
<BadgeStatus status={row.status} />
}
</TableCell>
<TableCell className="text-right">
<div className="flex justify-end gap-0.5">
{isEditing ?
<>
<Button variant="outline" className="h-10 w-10 text-green-600 hover:text-green-700 hover:bg-green-100" onClick={handleSave} disabled={isSaving}>
{isSaving ? <Loader2 className=" animate-spin" /> : <Save className="" />}
</Button>
<Button variant="outline" className="h-10 w-10" onClick={handleCancel} disabled={isSaving}>
<X className="" />
</Button>
</>
:
!isOtherRowEditing && (
<>
<Button variant="outline" className="h-8 w-8 text-blue-600 hover:text-blue-700 hover:bg-blue-100" onClick={() => handleEdit(row)}>
<Edit2 className="size-3.5" />
</Button>
<Button variant="outline" className="h-8 w-8 text-red-600 hover:text-red-700 hover:bg-red-100" onClick={() => setDeletedId(row.id)}>
<Trash2 className="size-3.5" />
</Button>
</>
)
}
</div>
</TableCell>
</TableRow>
);
})
}
</TableBody>
</Table>
</div>
<AlertDialogFooter>
<AlertDialogCancel onClick={onClose} disabled={isSaving}>Close</AlertDialogCancel>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
{showAddTeamDialog ?
<AddTeam assignmentId={assignmentId} existingTeam={existUserAssign} onCancel={() => setShowAddTeamDialog(false)} onSuccess={handleSuccess} />
: null
}
{deletedId ?
<ConfirmDelete description="This action cannot be undone. This will permanently delete this user from this assignment." endpoint={`/project-assignment/assign-user/delete/${deletedId}`}
onCancel={handleCancel} onSuccess={handleSuccess}
/>
: null
}
</>
);
}