Files
hats-app/app/(dashboard)/task/component/ManageTeam.tsx
T
Ichsan Kurniawan fccb901e2a Fix assignment deletion and team removal
This update changes assignment deletion labels to prefer WO/IM names, adds a configurable payload to ConfirmDelete for non-DELETE API calls, and switches team member removal to a PUT endpoint with status REMOVED. It also shortens project autofill toast duration, cleans out stale commented code on the client detail page, and updates the task error badge wording to better reflect app-level failures.
2026-10-13 16:56:20 +07:00

329 lines
20 KiB
TypeScript

"use client"
import { useState } from "react";
import {
Edit2, Trash2, Save, X, Loader2, UserPlus,
UserGroup
} 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 {
Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle
} from "@/components/ui/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";
import dayjs from "dayjs";
export interface IProjectAssignmentAssignUserDetail {
id: number
end_date: any
start_date: any
status: string
user: User
}
export interface User {
id: number
fullname: string
position: Position
email: string
avatar: string
}
export interface Position {
name: string
}
export function ManageTeam({ assignmentId, onClose, startDate, endDate }: { assignmentId: number, onClose: VoidFunction, startDate?: any, endDate?: any }) {
const [editingId, setEditingId] = useState<number | null>(null);
const [draftData, setDraftData] = useState<Partial<any>>({});
const [isSaving, setIsSaving] = useState(false);
const [showAddTeamDialog, setShowAddTeamDialog] = useState(false);
const [deletedId, setDeletedId] = useState<number | null>(null);
const { data: existUserAssign, isLoading, mutate } = useFetchWithAxios(`/project-assignment/assign-user/${assignmentId}`)
const router = useRouter()
const handleEdit = (row: IProjectAssignmentAssignUserDetail) => {
setEditingId(row.id);
setDraftData({
id: row.id,
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 ? dayjs(draftData.start_date).format("YYYY-MM-DD") : '',
"end_date": draftData.end_date ? dayjs(draftData.end_date).format("YYYY-MM-DD") : '',
}
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: any, value: string) => {
setDraftData((prev) => ({ ...prev, [field]: value }));
};
const handleCancel = () => {
setEditingId(null);
setDraftData({});
setShowAddTeamDialog(false);
setDeletedId(null)
};
const handleSuccess = () => {
handleCancel()
mutate()
router.refresh()
}
return (
<>
<Dialog open={true} onOpenChange={(open) => { if (!open) onClose(); }}>
<DialogContent className="min-w-full md:min-w-max p-0">
<div className="border-b border-border/70 bg-muted/40 px-6 py-5">
<div className="flex flex-col sm:flex-row justify-between gap-3 pr-6">
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
<UserGroup className="h-5 w-5 text-his" />
Manage Team
</DialogTitle>
<DialogDescription>
Add team members and manage who is working on each project assignment.
</DialogDescription>
</DialogHeader>
<Button size='sm' variant='outline' onClick={() => setShowAddTeamDialog(true)}><UserPlus className="h-4 w-4" /> Add Team</Button>
</div>
</div>
<div className="px-6 py-5 max-h-[70vh] overflow-y-auto">
<div className="rounded-md border bg-card overflow-x-auto">
<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: IProjectAssignmentAssignUserDetail) => {
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={`${process.env.BASE_URL_IMG}/${row.user.avatar}`} alt={row.user.fullname} />
<AvatarFallback>{row.user.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.user.fullname}</span>
<Badge variant="secondary" className="ml-auto">{row.user.position?.name}</Badge>
</div>
<span className="text-xs text-muted-foreground mt-1">{row.user.email}</span>
</div>
</div>
</TableCell>
<TableCell>
{isEditing ?
<DatePicker date={draftData.start_date as Date | undefined} setDate={(date) => handleDraftChange("start_date", date as any)}
disabledDate={(date: Date) => {
// const assStartDate = startDate
// const assEndDate = endDate
// return assStartDate ? (date <= new Date(assStartDate) || date > new Date(assEndDate)) : false;
if (!startDate || !endDate) return false;
// 1. Normalize all dates to midnight (00:00:00) to strip out time differences
const targetDate = new Date(date).setHours(0, 0, 0, 0);
const minDate = new Date(startDate).setHours(0, 0, 0, 0);
const maxDate = new Date(endDate).setHours(0, 0, 0, 0);
// 2. Disable if strictly BEFORE (<) the start date, or strictly AFTER (>) the end date
return targetDate < minDate || targetDate > maxDate;
}}
/>
:
<span className="text-sm">{row.start_date ? dayjs(row.start_date).format('DD MMM YYYY') : ''}</span>
}
</TableCell>
<TableCell>
{isEditing ?
<DatePicker date={draftData.end_date as Date | undefined} setDate={(date) => handleDraftChange("end_date", date as any)}
disabledDate={(date: Date) => {
// 1. Normalize the calendar date we are currently checking
const targetDate = new Date(date).setHours(0, 0, 0, 0);
const assStartDate = startDate;
const assEndDate = endDate;
const userStartDate = draftData.start_date;
// 2. Check against the User's selected Start Date (if it exists)
if (userStartDate) {
const minUserDate = new Date(userStartDate).setHours(0, 0, 0, 0);
if (targetDate < minUserDate) return true; // Disable if before user's start date
}
// 3. Check against the overall Assignment Start boundary (if it exists)
if (assStartDate) {
const minAssDate = new Date(assStartDate).setHours(0, 0, 0, 0);
if (targetDate < minAssDate) return true; // Disable if before assignment start limit
}
// 4. Check against the overall Assignment End boundary (if it exists)
if (assEndDate) {
const maxAssDate = new Date(assEndDate).setHours(0, 0, 0, 0);
if (targetDate > maxAssDate) return true; // Disable if AFTER assignment end limit
}
// If it passes all existing checks, it is a valid date!
return false;
}}
/>
:
<span className="text-sm">{row.end_date ? dayjs(row.end_date).format('DD MMM YYYY') : ''}</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>
:
<Badge variant={row.status === "ACTIVE" ? 'statusActive' : "destructive"} className='inline-block lowercase first-letter:uppercase' >{row.status}</Badge>
}
</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-teal-600 hover:text-teal-700 hover:bg-teal-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>
</div>
<div className="pb-5 px-6">
<DialogFooter>
<Button variant="outline" onClick={onClose} disabled={isSaving}>Close</Button>
</DialogFooter>
</div>
</DialogContent>
</Dialog>
{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/update/${deletedId}`}
method='PUT'
payload={
{
"project_assignment_id": assignmentId,
"status": "REMOVED",
}
}
onCancel={handleCancel} onSuccess={handleSuccess}
/>
: null
}
</>
);
}