Files
hats-app/app/(dashboard)/task/component/UpdateTechnicalStatus.tsx
T
Ichsan Kurniawan e7c6f1b17b Align technical status schedules and UI
This commit updates the technical status flow to support the newer `data` payload format while preserving legacy `date` handling across timelines, overview helpers, and assignment detail views. It also adds per-interval descriptions for date ranges, improves schedule editing/deletion UX, and refreshes status badge colors and default work-order/client fallback values for a more consistent experience.
2026-10-15 13:23:51 +07:00

693 lines
35 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"use client";
import { useMemo, useState, type FC } from 'react';
import {
Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle
} from "@/components/ui/dialog";
import { Button } from '@/components/ui/button';
import { DatePicker } from '@/components/ui/datepicker';
import { Textarea } from '@/components/ui/textarea';
import {
Table, TableBody, TableCell, TableHead, TableHeader, TableRow
} from "@/components/ui/table";
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import {
AlertCircle, Calendar, Edit2, History, Loader2, Plus, Save, Trash2
} from 'lucide-react';
import { useFetchWithAxios } from '@/lib/axios/useFetch';
import { Skeleton } from '@/components/ui/skeleton';
import { serverApiCall } from '@/lib/server-api';
import { toast } from 'sonner';
import { useRouter } from 'next/navigation';
import BadgeStatus from '@/components/ui/badge-status';
import dayjs from 'dayjs';
export interface IDateInterval {
start_date: string;
end_date: string;
description?: string;
}
export interface IProjectAssignmentTimeline {
id: number;
start_date: string | null;
end_date: string | null;
date?: IDateInterval[] | string | null;
data?: IDateInterval[] | string | null;
description?: string | null;
updated_at?: string | null;
project_assignment_status: ProjectAssignmentStatus;
}
export interface ProjectAssignmentStatus {
id: number;
name: string;
description?: string | null;
remark?: any;
}
export interface StatusItem {
detailId: number;
technicalId: number;
statusName: string;
description: string;
dates: IDateInterval[];
}
type Props = {
assignmentId: string | number;
onClose?: VoidFunction;
};
interface ModalState {
mode: 'ADD' | 'EDIT';
technicalId: number;
detailId: number;
statusName: string;
existingDates: IDateInterval[];
editIndex?: number;
initialStartDate?: Date;
initialEndDate?: Date;
initialDescription: string;
}
function extractDatesFromRow(row: any): IDateInterval[] {
if (!row) return [];
let rawDate = row.data ?? row.date;
if (typeof rawDate === 'string') {
try {
rawDate = JSON.parse(rawDate);
} catch {
rawDate = null;
}
}
if (Array.isArray(rawDate) && rawDate.length > 0) {
return rawDate
.filter(Boolean)
.map((item: any) => ({
start_date: item?.start_date ? dayjs(item.start_date).format('YYYY-MM-DD') : '',
end_date: item?.end_date ? dayjs(item.end_date).format('YYYY-MM-DD') : '',
description: typeof item?.description === 'string'
? item.description.trim()
: typeof row.description === 'string'
? row.description.trim()
: '',
}))
.filter((d: IDateInterval) => Boolean(d.start_date || d.end_date));
}
if (row.start_date || row.end_date) {
return [{
start_date: row.start_date ? dayjs(row.start_date).format('YYYY-MM-DD') : '',
end_date: row.end_date ? dayjs(row.end_date).format('YYYY-MM-DD') : '',
description: typeof row.description === 'string' ? row.description.trim() : '',
}];
}
return [];
}
interface EditModalProps {
assignmentId: string | number;
data: ModalState;
onClose: VoidFunction;
onSuccess: VoidFunction;
}
function EditTechnicalStatusModal({ assignmentId, data, onClose, onSuccess }: EditModalProps) {
const [startDate, setStartDate] = useState<Date | undefined>(data.initialStartDate);
const [endDate, setEndDate] = useState<Date | undefined>(data.initialEndDate);
const [description, setDescription] = useState<string>(data.initialDescription || '');
const [isSaving, setIsSaving] = useState(false);
// Validation: end date must not be earlier than start date
const isDateRangeInvalid = useMemo(() => {
if (!startDate || !endDate) return false;
return dayjs(endDate).isBefore(dayjs(startDate), 'day');
}, [startDate, endDate]);
const isDateMissing = !startDate || !endDate;
const handleSave = async () => {
if (isDateMissing) {
toast.error('Date range required', {
description: 'Please select both a start date and an end date.'
});
return;
}
if (isDateRangeInvalid) {
toast.error('Invalid date interval', {
description: 'End date cannot be earlier than start date.'
});
return;
}
setIsSaving(true);
let finalDates: IDateInterval[] = [...data.existingDates];
if (data.mode === 'ADD') {
const newInterval: IDateInterval = {
start_date: startDate ? dayjs(startDate).format('YYYY-MM-DD') : '',
end_date: endDate ? dayjs(endDate).format('YYYY-MM-DD') : '',
description: description.trim(),
};
// Retain all existing dates and append the new one
finalDates.push(newInterval);
} else if (data.mode === 'EDIT' && typeof data.editIndex === 'number') {
const updatedInterval: IDateInterval = {
start_date: startDate ? dayjs(startDate).format('YYYY-MM-DD') : '',
end_date: endDate ? dayjs(endDate).format('YYYY-MM-DD') : '',
description: description.trim(),
};
// Update only the targeted date, preserve all other existing dates
finalDates = finalDates.map((item, idx) =>
idx === data.editIndex ? updatedInterval : item
);
}
const submitPayload = {
project_assignment_technical_status_id: Number(data.technicalId),
project_assignment_status_detail_id: Number(data.detailId),
data: finalDates,
};
const res = await serverApiCall('PUT', `/project-assignment/technical-status/${assignmentId}`, submitPayload);
setIsSaving(false);
if (res.success) {
toast.success(data.mode === 'ADD' ? 'Schedule interval added successfully' : 'Schedule interval updated successfully');
onSuccess();
} else {
toast.error('Failed to save status', {
description: `(${res.code || '-'}) ${res.message}`
});
}
};
const modalTitle = data.mode === 'ADD' ? 'Add Schedule' : 'Edit Schedule';
const modalDescription = data.mode === 'ADD'
? `Add a new schedule interval and description for ${data.statusName}. Previously recorded dates will be retained.`
: `Update the selected schedule interval and description.`;
return (
<Dialog open={true} onOpenChange={(open) => { if (!open && !isSaving) onClose(); }}>
<DialogContent className="sm:max-w-lg">
<DialogHeader>
<div className="flex items-center gap-2 mb-1">
<BadgeStatus status={data.statusName} />
</div>
<DialogTitle>{modalTitle}</DialogTitle>
<DialogDescription>{modalDescription}</DialogDescription>
</DialogHeader>
<div className="space-y-4 py-2">
{/* Show existing dates overview when adding */}
{data.existingDates.length > 0 && data.mode === 'ADD' && (
<div className="rounded-md border border-border/60 bg-muted/30 p-2.5 space-y-2">
<div className="flex items-center justify-between text-xs text-muted-foreground font-medium">
<span>Existing Schedules ({data.existingDates.length})</span>
<span className="text-[11px] text-his font-normal">+1 new interval will be added</span>
</div>
<div className="space-y-1.5 max-h-36 overflow-y-auto pr-0.5">
{data.existingDates.map((item, idx) => (
<div
key={idx}
className="p-1.5 rounded text-xs border border-border/60 bg-background text-muted-foreground space-y-0.5"
>
<div className="flex items-center gap-1.5 font-mono text-foreground font-medium text-[11px]">
<Calendar className="size-3 text-muted-foreground/70" />
{dayjs(item.start_date).format('DD MMM YYYY')} – {dayjs(item.end_date).format('DD MMM YYYY')}
</div>
{item.description && (
<p className="text-[11px] text-muted-foreground line-clamp-1 italic pl-4.5">
"{item.description}"
</p>
)}
</div>
))}
</div>
</div>
)}
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
<div className="space-y-1.5">
<label className="text-xs font-medium text-foreground">
Start Date <span className="text-destructive">*</span>
</label>
<DatePicker
date={startDate}
setDate={setStartDate}
placeholder="Pick start date"
className="w-full"
/>
</div>
<div className="space-y-1.5">
<label className="text-xs font-medium text-foreground">
End Date <span className="text-destructive">*</span>
</label>
<DatePicker
date={endDate}
setDate={setEndDate}
placeholder="Pick end date"
className="w-full"
/>
</div>
</div>
{isDateRangeInvalid && (
<div className="rounded-md border border-destructive/30 bg-destructive/10 p-2.5 text-xs text-destructive flex items-center gap-2">
<AlertCircle className="size-4 shrink-0" />
<span>End date cannot be earlier than start date.</span>
</div>
)}
<div className="space-y-1.5">
<div className="flex items-center justify-between">
<label className="text-xs font-medium text-foreground">
Description & Progress Notes for this Interval
</label>
<span className="text-[11px] text-muted-foreground">{description.length}/500</span>
</div>
<Textarea
value={description}
onChange={(e) => setDescription(e.target.value)}
maxLength={500}
rows={3}
placeholder="Deskripsi kegiatan atau milestone untuk interval tanggal ini..."
className="text-sm resize-none"
/>
<p className="text-[11px] text-muted-foreground">
Deskripsi ini khusus berlaku untuk rentang tanggal di atas.
</p>
</div>
</div>
<DialogFooter className="gap-2">
<Button
type="button"
variant="outline"
onClick={onClose}
disabled={isSaving}
>
Cancel
</Button>
<Button
type="button"
onClick={handleSave}
disabled={isSaving || isDateRangeInvalid || isDateMissing}
className="bg-his text-white hover:bg-his/90 gap-1.5 shadow-2xs font-medium"
>
{isSaving ? (
<>
<Loader2 className="size-4 animate-spin" />
Saving...
</>
) : (
<>
<Save className="size-4" />
Save
</>
)}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}
interface DeleteTarget {
item: StatusItem;
index: number;
dateEntry: IDateInterval;
}
const UpdateTechnicalStatus: FC<Props> = ({ assignmentId, onClose }) => {
const [modalState, setModalState] = useState<ModalState | null>(null);
const [deleteTarget, setDeleteTarget] = useState<DeleteTarget | null>(null);
const [isDeleting, setIsDeleting] = useState(false);
const { data: existTimeline, isLoading: isLoadingTimeline, mutate } = useFetchWithAxios(`project-assignment/status-detail/${assignmentId}`);
const router = useRouter();
const handleSuccess = () => {
setModalState(null);
mutate();
router.refresh();
};
// Group and consolidate technical statuses with their associated date intervals and descriptions
const statusItems = useMemo<StatusItem[]>(() => {
if (!Array.isArray(existTimeline)) return [];
const map = new Map<number, StatusItem>();
for (const row of existTimeline) {
const technicalId = Number(row.project_assignment_status?.id ?? row.id);
const statusName = row.project_assignment_status?.name ?? 'Status';
const detailId = Number(row.id);
const rowDates = extractDatesFromRow(row);
const description = (row.description ?? '').trim();
if (!map.has(technicalId)) {
map.set(technicalId, {
detailId,
technicalId,
statusName,
description,
dates: [...rowDates]
});
} else {
const existing = map.get(technicalId)!;
for (const d of rowDates) {
const exists = existing.dates.some(
ed => ed.start_date === d.start_date && ed.end_date === d.end_date
);
if (!exists) {
existing.dates.push(d);
}
}
if (!existing.description && description) {
existing.description = description;
}
if (detailId > existing.detailId) {
existing.detailId = detailId;
}
}
}
return Array.from(map.values()).sort((a, b) => a.technicalId - b.technicalId);
}, [existTimeline]);
// Handle clicking Add on status
const handleAddNewDate = (item: StatusItem) => {
setModalState({
mode: 'ADD',
detailId: item.detailId,
technicalId: item.technicalId,
statusName: item.statusName,
existingDates: item.dates,
initialStartDate: undefined,
initialEndDate: undefined,
initialDescription: '',
});
};
// Handle clicking Edit on a specific existing date entry
const handleEditExistingDate = (item: StatusItem, dateIndex: number) => {
const targetDate = item.dates[dateIndex];
setModalState({
mode: 'EDIT',
detailId: item.detailId,
technicalId: item.technicalId,
statusName: item.statusName,
existingDates: item.dates,
editIndex: dateIndex,
initialStartDate: targetDate?.start_date ? new Date(targetDate.start_date) : undefined,
initialEndDate: targetDate?.end_date ? new Date(targetDate.end_date) : undefined,
initialDescription: targetDate?.description || '',
});
};
// Handle confirming date deletion from AlertDialog
const handleConfirmDelete = async () => {
if (!deleteTarget) return;
const { item, index: removeIndex } = deleteTarget;
setIsDeleting(true);
const remainingDates = item.dates.filter((_, idx) => idx !== removeIndex);
const submitPayload = {
project_assignment_technical_status_id: Number(item.technicalId),
project_assignment_status_detail_id: Number(item.detailId),
data: remainingDates,
};
const res = await serverApiCall('PUT', `/project-assignment/technical-status/${assignmentId}`,
submitPayload
);
setIsDeleting(false);
if (res.success) {
toast.success('Schedule interval removed');
setDeleteTarget(null);
mutate();
router.refresh();
} else {
toast.error('Failed to remove schedule interval', {
description: `(${res.code || '-'}) ${res.message}`
});
}
};
return (
<>
<Dialog
open={true}
onOpenChange={(open) => {
if (!open && onClose) onClose();
}}
>
<DialogContent className="sm:max-w-4xl p-0">
<div className="border-b border-border/70 bg-muted/40 px-6 py-5">
<DialogHeader className="space-y-1.5 text-left">
<DialogTitle className="flex items-center gap-2">
<History className="h-5 w-5 text-his" />
Update Technical Status
</DialogTitle>
<DialogDescription className="w-full sm:max-w-140">
Manage timeline schedules and deliverable notes for each technical status. Multiple date intervals can be added to a single status.
</DialogDescription>
</DialogHeader>
</div>
<div className="px-6 py-5 max-h-[65vh] overflow-y-auto">
<div className="rounded-md border bg-card overflow-x-auto">
<Table>
<TableHeader>
<TableRow>
<TableHead className="w-44">Status</TableHead>
<TableHead className="min-w-80">Schedules & Notes</TableHead>
<TableHead className="w-24 text-right">Action</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{isLoadingTimeline ? (
<TableRow>
<TableCell colSpan={3} className="w-full space-y-3 p-4">
<Skeleton className="h-10 w-full" />
<Skeleton className="h-10 w-full" />
<Skeleton className="h-10 w-full" />
</TableCell>
</TableRow>
) : statusItems.length === 0 ? (
<TableRow>
<TableCell colSpan={3} className="w-full h-32 text-center text-muted-foreground">
No technical statuses found.
</TableCell>
</TableRow>
) : (
statusItems.map((item) => {
const hasDates = item.dates.length > 0;
return (
<TableRow key={item.technicalId}>
{/* Status Column - Badge only */}
<TableCell className="align-top py-3.5">
<BadgeStatus status={item.statusName} />
</TableCell>
{/* Schedules & Notes Column */}
<TableCell className="align-top py-3">
<div className="space-y-2">
{hasDates ? (
<div className="space-y-2">
{[...item.dates]
.map((dateEntry, originalIndex) => ({ dateEntry, originalIndex }))
.sort((a, b) => {
const timeA = a.dateEntry.start_date ? dayjs(a.dateEntry.start_date).valueOf() : 0;
const timeB = b.dateEntry.start_date ? dayjs(b.dateEntry.start_date).valueOf() : 0;
return timeA - timeB;
})
.map(({ dateEntry, originalIndex }, idx) => {
const start = dateEntry.start_date ? dayjs(dateEntry.start_date) : null;
const end = dateEntry.end_date ? dayjs(dateEntry.end_date) : null;
const spanDays = start && end ? end.diff(start, 'day') + 1 : null;
return (
<div
key={idx}
className="p-2.5 rounded-lg bg-muted/30 border border-border/70 hover:bg-muted/40 transition-colors space-y-2"
>
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-2">
<div className="flex items-center gap-2 font-mono text-xs text-foreground min-w-0">
<Calendar className="size-3.5 text-his shrink-0" />
<span className="font-semibold">
{start ? start.format('DD MMM YYYY') : 'TBD'} – {end ? end.format('DD MMM YYYY') : 'Present'}
</span>
{spanDays !== null && (
<span className="font-sans text-[11px] px-1.5 py-0.5 rounded bg-muted text-muted-foreground font-normal">
({spanDays} {spanDays === 1 ? 'day' : 'days'})
</span>
)}
</div>
<div className="flex items-center gap-1 shrink-0 self-end sm:self-center">
<Button
variant="outline"
size="sm"
className="h-7 w-7 p-0 text-teal-600 hover:text-teal-700 hover:bg-teal-50 dark:hover:bg-teal-950/40"
onClick={() => handleEditExistingDate(item, originalIndex)}
title="Edit schedule & description"
>
<Edit2 className="size-3.5" />
</Button>
<Button
variant="outline"
size="sm"
className="h-7 w-7 p-0 text-red-600 hover:text-red-700 hover:bg-red-50 dark:hover:bg-red-950/40"
onClick={() => setDeleteTarget({ item, index: originalIndex, dateEntry })}
title="Delete this schedule"
>
<Trash2 className="size-3.5" />
</Button>
</div>
</div>
{/* Individual date description */}
{dateEntry.description ? (
<div className="rounded border border-border/50 bg-background/80 px-2.5 py-1.5 text-xs text-muted-foreground leading-relaxed wrap-break-word">
<span className="text-foreground/80 font-medium">Note: </span>
{dateEntry.description}
</div>
) : (
<div className="text-[11px] text-muted-foreground/60 italic pl-0.5">
No description provided for this date.
</div>
)}
</div>
);
})}
</div>
) : (
<span className="text-xs text-muted-foreground/70 italic py-1 block">
No dates scheduled
</span>
)}
</div>
</TableCell>
{/* Action Column - Always Add button with HIS accent */}
<TableCell className="align-top py-3 text-right">
<Button
variant="outline"
size="sm"
className="h-8 gap-1.5 text-xs border-border hover:bg-muted text-foreground"
onClick={() => handleAddNewDate(item)}
>
<Plus className="size-3.5 text-his" />
Add
</Button>
</TableCell>
</TableRow>
);
})
)}
</TableBody>
</Table>
</div>
</div>
<div className="pb-5 px-6">
<DialogFooter>
<Button variant="outline" onClick={onClose}>Close</Button>
</DialogFooter>
</div>
</DialogContent>
</Dialog>
{/* Sub-Modal: Add / Edit Date */}
{modalState ? (
<EditTechnicalStatusModal
assignmentId={assignmentId}
data={modalState}
onClose={() => setModalState(null)}
onSuccess={handleSuccess}
/>
) : null}
{/* Confirmation Dialog: Delete Date Interval */}
<AlertDialog
open={Boolean(deleteTarget)}
onOpenChange={(open) => {
if (!open && !isDeleting) setDeleteTarget(null);
}}
>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle className="flex items-center gap-2 text-destructive">
<Trash2 className="size-4" />
Delete Schedule
</AlertDialogTitle>
<AlertDialogDescription className="space-y-2 pt-1 text-left">
{deleteTarget && (
<>
<span>
Are you sure you want to delete the schedule{' '}
<strong className="font-mono text-foreground">
{deleteTarget.dateEntry.start_date ? dayjs(deleteTarget.dateEntry.start_date).format('DD MMM YYYY') : 'TBD'} – {deleteTarget.dateEntry.end_date ? dayjs(deleteTarget.dateEntry.end_date).format('DD MMM YYYY') : 'Present'}
</strong>{' '}
from <strong className="text-foreground">{deleteTarget.item.statusName}</strong>?
</span>
{deleteTarget.dateEntry.description && (
<div className="rounded-md border border-border/60 bg-muted/40 p-2 text-xs text-muted-foreground italic mt-2">
"{deleteTarget.dateEntry.description}"
</div>
)}
</>
)}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel disabled={isDeleting}>Cancel</AlertDialogCancel>
<AlertDialogAction
onClick={(e) => {
e.preventDefault();
handleConfirmDelete();
}}
disabled={isDeleting}
className="bg-destructive text-white hover:bg-destructive/90 gap-1.5"
>
{isDeleting ? (
<>
<Loader2 className="size-3.5 animate-spin" />
Deleting...
</>
) : (
'Delete'
)}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</>
);
};
export default UpdateTechnicalStatus;