Refactor technical status workflow

Replace the legacy timeline status modal with a technical-status editor that supports multiple date intervals and descriptive notes. Update task views to use the new Update Technical Status action, normalize status-history parsing for array-based date records, and improve badge formatting for technical stages like SIT, UAT, PTR, Go-Live, and BAST.
This commit is contained in:
Ichsan Kurniawan
2026-10-09 18:37:26 +07:00
parent 98ce715ac6
commit f07990a3fb
12 changed files with 660 additions and 228 deletions
@@ -10,7 +10,7 @@ import { IProjectAssignment } from '../../../type.assignment';
import { useRouter, useSearchParams } from 'next/navigation';
import FilterComponent from '../../../component/FilterComponent';
import { ConfirmDeleteWithInput } from '@/components/modal/ConfirmDeleteWithInput';
import UpdateTimelineStatus from '../../../component/UpdateTimelineStatus';
import UpdateTechnicalStatus from '../../../component/UpdateTechnicalStatus';
import { ManageTeam } from '../../../component/ManageTeam';
import AssignmentGrid from '../../../component/project-assignment/AssignmentGrid';
import AssignmentList from '../../../component/project-assignment/AssignmentList';
@@ -113,7 +113,7 @@ export default function ClientDetailComponent({ clientId, assignmentLists }: Pro
) : null}
{action === 'UPDATE_STATUS' && selectedData ? (
<UpdateTimelineStatus assignmentId={selectedData.id} onClose={handleClose} />
<UpdateTechnicalStatus assignmentId={selectedData.id} onClose={handleClose} />
) : null}
{action === 'DELETE' && selectedData ? (
@@ -25,7 +25,7 @@ import { cn } from '@/lib/utils';
import { IClient, CLIENT_FALLBACK_IMAGE, END_USER_FALLBACK_IMAGE } from '../../../types';
import { IProjectAssignment, ProjectAssignmentWorkOrderDetail } from '../../../type.assignment';
import { ManageTeam } from '../../../component/ManageTeam';
import UpdateTimelineStatus from '../../../component/UpdateTimelineStatus';
import UpdateTechnicalStatus from '../../../component/UpdateTechnicalStatus';
import Reveal from '@/components/ui/reveal';
interface Props {
@@ -80,8 +80,8 @@ export default function AssignmentDetail({ client, initialAssignment: assignment
const visibleTeam = showAllTeam ? team : team.slice(0, TEAM_PREVIEW_LIMIT);
const hiddenTeamCount = team.length - visibleTeam.length;
const statusHistory = assignment.project_assignment_status_detail?.filter(s => s.start_date) ?? [];
const currentEntry = statusHistory.find(s => !s.end_date) ?? statusHistory[0];
const statusHistory = assignment.project_assignment_status_detail?.filter(s => Boolean(s.start_date || (Array.isArray(s.date) && s.date.length > 0))) ?? [];
const currentEntry = statusHistory.find(s => !s.end_date && !(Array.isArray(s.date) && s.date[s.date.length - 1]?.end_date)) ?? statusHistory[0];
const duration = formatSpan(assignmentStartDate, assignmentEndDate);
const positionCount = new Set(team.map(m => m.user?.position?.name).filter(Boolean)).size;
@@ -147,7 +147,7 @@ export default function AssignmentDetail({ client, initialAssignment: assignment
className="w-full shrink-0 gap-2 transition-transform active:scale-[0.98] md:w-auto"
>
<History className="h-4 w-4" />
Update status
Update Technical Status
</Button>
</div>
@@ -363,7 +363,7 @@ export default function AssignmentDetail({ client, initialAssignment: assignment
<Surface title="Status history">
{statusHistory.length === 0 ? (
<p className="text-sm leading-relaxed text-muted-foreground">
No status changes recorded yet. Use Update status to log the first one.
No status changes recorded yet. Use Update Technical Status to log the first one.
</p>
) : (
<ol className="relative space-y-6 before:absolute before:bottom-2 before:left-1.75 before:top-2 before:w-px before:bg-border">
@@ -395,6 +395,11 @@ export default function AssignmentDetail({ client, initialAssignment: assignment
{span ? (
<p className="mt-0.5 text-xs text-muted-foreground/80">{span}</p>
) : null}
{entry.description ? (
<p className="mt-1.5 rounded-lg border border-border/50 bg-muted/30 p-2 text-xs leading-relaxed text-foreground/90 italic">
{entry.description}
</p>
) : null}
</li>
);
})}
@@ -406,7 +411,7 @@ export default function AssignmentDetail({ client, initialAssignment: assignment
</div>
{action === 'UPDATE_STATUS' ? (
<UpdateTimelineStatus assignmentId={assignment.id} onClose={handleClose} />
<UpdateTechnicalStatus assignmentId={assignment.id} onClose={handleClose} />
) : null}
{action === 'MANAGE_EMPLOYEE' ? (
@@ -15,6 +15,8 @@ export default async function AssignmentDetailPage({ params }: Props) {
const [client, assignment] = await Promise.all([getClientById, getAssignmentById]);
// console.log(assignment)
// 3. Handle 404 Securely on the server
if (!assignment) {
return (
@@ -25,13 +25,26 @@ export default function StatusTimeline({ history }: StatusTimelineProps) {
</div>
<p className="mt-2 text-sm font-medium text-foreground">No status changes recorded</p>
<p className="mt-0.5 text-xs text-muted-foreground">
Use the Update Status action to record the current stage of this work order.
Use the Update Technical Status action to record the current stage of this work order.
</p>
</div>
);
}
const currentEntry = history.find(s => !s.end_date) ?? history[0];
const getEntryDates = (entry: ProjectAssignmentStatusDetail) => {
if (Array.isArray(entry.date) && entry.date.length > 0) {
const start = entry.date[0]?.start_date ?? entry.start_date;
const end = entry.date[entry.date.length - 1]?.end_date ?? entry.end_date;
return { start, end, allDates: entry.date };
}
return {
start: entry.start_date,
end: entry.end_date,
allDates: entry.start_date || entry.end_date ? [{ start_date: entry.start_date, end_date: entry.end_date }] : []
};
};
const currentEntry = history.find(s => !getEntryDates(s).end) ?? history[0];
const visibleHistory = showAll ? history : history.slice(0, TIMELINE_PREVIEW_LIMIT);
const hiddenCount = history.length - visibleHistory.length;
@@ -40,8 +53,9 @@ export default function StatusTimeline({ history }: StatusTimelineProps) {
<ol className="relative space-y-5 before:absolute before:bottom-2 before:left-1.75 before:top-2 before:w-px before:bg-border">
{visibleHistory.map(entry => {
const isCurrent = entry.id === currentEntry?.id;
const span = formatSpan(entry.start_date, entry.end_date);
const remarks = (entry as any).status_remarks || (entry as any).remarks;
const { start, end, allDates } = getEntryDates(entry);
const span = formatSpan(start, end);
const remarks = entry.description || (entry as any).status_remarks || (entry as any).remarks;
return (
<li key={entry.id} className="relative pl-7">
@@ -64,9 +78,19 @@ export default function StatusTimeline({ history }: StatusTimelineProps) {
<span className="text-xs text-muted-foreground">Current</span>
) : null}
</div>
<p className="mt-1 font-mono text-xs text-muted-foreground">
{formatDate(entry.start_date)} - {entry.end_date ? formatDate(entry.end_date) : 'Present'}
</p>
{allDates.length > 1 ? (
<div className="mt-1 space-y-1">
{allDates.map((d, i) => (
<p key={i} className="font-mono text-xs text-muted-foreground">
{formatDate(d.start_date)} - {d.end_date ? formatDate(d.end_date) : 'Present'}
</p>
))}
</div>
) : (
<p className="mt-1 font-mono text-xs text-muted-foreground">
{formatDate(start)} - {end ? formatDate(end) : 'Present'}
</p>
)}
{span ? (
<p className="mt-0.5 text-xs text-muted-foreground/80">{span}</p>
) : null}
@@ -17,7 +17,7 @@ import StatusTimeline from './StatusTimeline';
import AssignedPeople from './AssignedPeople';
import BadgeStatus from '@/components/ui/badge-status';
import { IProjectAssignment } from '@/app/(dashboard)/task/type.assignment';
import UpdateTimelineStatus from '@/app/(dashboard)/task/component/UpdateTimelineStatus';
import UpdateTimelineStatus from '@/app/(dashboard)/task/component/UpdateTechnicalStatus';
import { ManageTeam } from '@/app/(dashboard)/task/component/ManageTeam';
import { cn } from '@/lib/utils';
import { COMPLETE_STATUS_LIST, ONPROGRESS_STATUS_LIST } from '@/app/(dashboard)/task/data';
@@ -40,7 +40,7 @@ export default function WorkOrderCard({ workOrder, index, defaultOpen = false }:
setAction(undefined);
};
const statusList = workOrder.project_assignment_status_detail?.filter(status => status.start_date) || [];
const statusList = workOrder.project_assignment_status_detail?.filter(status => Boolean(status.start_date || (Array.isArray(status.date) && status.date.length > 0))) || [];
const team = workOrder.project_assignment_work_order_detail ?? [];
const span = formatSpan(workOrder.wo_start_date, workOrder.wo_end_date);
const shownAvatars = team.slice(0, 4);
@@ -241,7 +241,7 @@ export default function WorkOrderCard({ workOrder, index, defaultOpen = false }:
}}
>
<IterationCcw className="h-3.5 w-3.5 text-his" />
Update Status
Update Technical Status
</Button>
}
/>
@@ -0,0 +1,571 @@
"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 {
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;
}
export interface IProjectAssignmentTimeline {
id: number;
start_date: string | null;
end_date: string | null;
date?: 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.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') : ''
}))
.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') : ''
}];
}
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') : '',
};
// 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') : '',
};
// 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),
date: finalDates,
description: description.trim()
};
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 for ${data.statusName}. Previously recorded dates will be retained.`
: `Update the selected schedule interval and deliverable notes.`;
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-1.5">
<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="flex flex-wrap gap-1.5">
{data.existingDates.map((item, idx) => (
<span
key={idx}
className="inline-flex items-center gap-1.5 px-2 py-0.5 rounded text-[11px] font-mono border border-border/60 bg-background text-muted-foreground"
>
<Calendar className="size-3 text-muted-foreground/70" />
{dayjs(item.start_date).format('DD MMM YYYY')} – {dayjs(item.end_date).format('DD MMM YYYY')}
</span>
))}
</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
</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="Deliverable summary or progress notes..."
className="text-sm resize-none"
/>
</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>
);
}
const UpdateTimelineStatus: FC<Props> = ({ assignmentId, onClose }) => {
const [modalState, setModalState] = useState<ModalState | null>(null);
const [deletingId, setDeletingId] = useState<string | null>(null);
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: item.description
});
};
// 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: item.description
});
};
// Handle deleting a specific date entry from the status
const handleDeleteDate = async (item: StatusItem, removeIndex: number) => {
const itemKey = `${item.technicalId}-${removeIndex}`;
setDeletingId(itemKey);
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),
date: remainingDates,
description: item.description.trim()
};
const res = await serverApiCall('PUT', `/project-assignment/technical-status/${assignmentId}`,
submitPayload
);
setDeletingId(null);
if (res.success) {
toast.success('Schedule interval removed');
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 max-h-[90vh] overflow-y-auto">
<DialogHeader className="pr-6">
<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 className="rounded-md border bg-card overflow-x-auto my-3">
<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-1.5">
{item.dates.map((dateEntry, idx) => {
const isDeletingThis = deletingId === `${item.technicalId}-${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="flex flex-col sm:flex-row sm:items-center justify-between gap-2 p-2 rounded-md bg-muted/30 border border-border/60 hover:bg-muted/40 transition-colors"
>
<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-medium">
{start ? start.format('DD MMM YYYY') : 'TBD'} – {end ? end.format('DD MMM YYYY') : 'Present'}
</span>
{spanDays !== null && (
<span className="font-sans text-[11px] text-muted-foreground">
({spanDays} {spanDays === 1 ? 'day' : 'days'})
</span>
)}
</div>
<div className="flex items-center gap-1 shrink-0 self-end sm:self-center">
<Button variant="outline" className="h-8 w-8 text-teal-600 hover:text-teal-700 hover:bg-teal-100" onClick={() => handleEditExistingDate(item, idx)}>
<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={() => handleDeleteDate(item, idx)}>
<Trash2 className="size-3.5" />
</Button>
</div>
</div>
);
})}
</div>
) : (
<span className="text-xs text-muted-foreground/70 italic py-1 block">
No dates scheduled
</span>
)}
{/* Description / Notes Display */}
{item.description ? (
<div className="rounded-md border border-border/40 bg-muted/20 px-2.5 py-1.5 text-xs text-muted-foreground leading-relaxed wrap-break-word italic">
"{item.description}"
</div>
) : null}
</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>
<DialogFooter>
<Button variant="outline" onClick={onClose}>
Close
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
{/* Sub-Modal: Add / Edit Date */}
{modalState ? (
<EditTechnicalStatusModal
assignmentId={assignmentId}
data={modalState}
onClose={() => setModalState(null)}
onSuccess={handleSuccess}
/>
) : null}
</>
);
};
export default UpdateTimelineStatus;
@@ -1,199 +0,0 @@
import { 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 { Edit2, Loader2, Save, X } 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 {
Table, TableBody, TableCell, TableHead, TableHeader, TableRow
} from "@/components/ui/table";
import BadgeStatus from '@/components/ui/badge-status';
import dayjs from 'dayjs';
export interface IProjectAssignmentTimeline {
id: number
end_date: any
start_date: any
project_assignment_status: ProjectAssignmentStatus
}
export interface ProjectAssignmentStatus {
id: number
name: string
remark: any
}
type Props = {
assignmentId: string | number
onClose?: VoidFunction
};
const UpdateTimelineStatus: FC<Props> = ({ assignmentId, onClose }) => {
const [editingId, setEditingId] = useState<number | null>(null);
const [draftData, setDraftData] = useState<any>({});
const [isSaving, setIsSaving] = useState(false);
const { data: existTimeline, isLoading: isLoadingTimeline, mutate } = useFetchWithAxios(`project-assignment/status-detail/${assignmentId}`)
const router = useRouter()
const handleEdit = (row: IProjectAssignmentTimeline) => {
setEditingId(row.id);
setDraftData({
detailId: Number(row.id),
masterId: Number(row.project_assignment_status.id),
start_date_assign: row.start_date,
end_date_assign: row.end_date,
});
};
const handleSave = async () => {
setIsSaving(true);
const submitPayload = {
"project_assignment_status_detail_id": Number(draftData.detailId),
"project_assignment_status_id": Number(draftData.masterId),
"start_date": draftData.start_date_assign ? dayjs(draftData.start_date_assign).format("YYYY-MM-DD") : '',
"end_date": draftData.end_date_assign ? dayjs(draftData.end_date_assign).format("YYYY-MM-DD") : '',
"note": draftData.note,
"remarks": draftData.note
}
console.log(submitPayload)
const res = await serverApiCall('PUT', `/project-assignment/status/${assignmentId}`, submitPayload)
setIsSaving(false);
if (res.success) {
toast.success('Status updated successfully')
handleSuccess!()
} else {
toast.error(`Fail to save status`, { description: `(${res.code || '-'}) ${res.message}` })
}
};
const handleDraftChange = (field: any, value: string) => {
setDraftData((prev: any) => ({ ...prev, [field]: value }));
};
const handleCancel = () => {
setEditingId(null);
setDraftData({});
};
const handleSuccess = () => {
handleCancel()
mutate()
router.refresh()
}
return (
<>
<Dialog open={true} onOpenChange={(open) => { if (!open && onClose) onClose(); }}>
<DialogContent className="min-w-full md:min-w-max max-h-[90vh] overflow-y-auto">
<DialogHeader className="pr-6">
<DialogTitle>Update Status</DialogTitle>
<DialogDescription className='w-full sm:max-w-140'>
Update the timeline status for this assignment. You can also add a note or remark regarding this status change. This will help to keep track of the progress.
</DialogDescription>
</DialogHeader>
<div className="rounded-md border bg-card overflow-x-auto my-3">
<Table>
<TableHeader>
<TableRow>
<TableHead>Status</TableHead>
<TableHead>Start Date</TableHead>
<TableHead>End Date</TableHead>
<TableHead className="text-right">Action</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{isLoadingTimeline ?
<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>
:
existTimeline.length === 0 ?
<TableRow>
<TableCell colSpan={5} className="w-full h-32">
<div className="text-center text-muted-foreground flex flex-col items-center justify-center gap-2">
No team members have been added yet.<br />Create a team to get started with project assignments
</div>
</TableCell>
</TableRow>
:
existTimeline.sort((a: any, b: any) => a.id - b.id).map((row: IProjectAssignmentTimeline) => {
const isEditing = editingId === row.id;
const isOtherRowEditing = editingId !== null && editingId !== row.id;
return (
<TableRow key={row.id}>
<TableCell>
<BadgeStatus status={row.project_assignment_status.name} />
</TableCell>
<TableCell>
{isEditing ?
<DatePicker date={draftData.start_date_assign as Date | undefined} setDate={(date) => handleDraftChange("start_date_assign", date as any)} />
:
<span className="text-sm">{row.start_date ? dayjs(row.start_date).format('MMM DD, YYYY') : null}</span>
}
</TableCell>
<TableCell>
{isEditing ?
<DatePicker date={draftData.end_date_assign as Date | undefined} setDate={(date) => handleDraftChange("end_date_assign", date as any)} />
:
<span className="text-sm">{row.end_date ? dayjs(row.end_date).format('MMM DD, YYYY') : null}</span>
}
</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>
}
</div>
</TableCell>
</TableRow>
);
})
}
</TableBody>
</Table>
</div>
<DialogFooter>
<Button variant="outline" onClick={onClose} disabled={isSaving}>Close</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</>
);
}
export default UpdateTimelineStatus;
@@ -146,7 +146,7 @@ export default function AssignmentGrid({
)}
{onUpdateStatus && (
<DropdownMenuItem onSelect={() => onUpdateStatus(assignment)}>
Update Status
Update Technical Status
</DropdownMenuItem>
)}
{onDelete && (
@@ -259,7 +259,7 @@ export default function AssignmentList({
)}
{onUpdateStatus && (
<DropdownMenuItem onSelect={() => onUpdateStatus(assignment)}>
Update Status
Update Technical Status
</DropdownMenuItem>
)}
{onDelete && (
+6 -3
View File
@@ -59,15 +59,18 @@ export interface ProjectStatus {
export interface ProjectAssignmentStatusDetail {
id: number
end_date?: string
start_date?: string
updated_at?: string
end_date?: string | null
start_date?: string | null
updated_at?: string | null
date?: Array<{ start_date?: string; end_date?: string }> | string | null
description?: string | null
project_assignment_status: ProjectAssignmentStatus
}
export interface ProjectAssignmentStatus {
id: number
name: string
description?: string | null
}
export interface Status {
+11 -2
View File
@@ -16,16 +16,25 @@ export function formatStatusText(status?: any): string {
if (!trimmed) return "";
// Tetap UPPERCASE jika seluruh teks status hanya 3 huruf (SIT, UAT, PTR, dll) atau akronim BAST
const upperAcronyms = new Set(["SIT", "UAT", "PTR", "BAST", "POC", "WIP", "WO", "IM"]);
const upperAcronyms = new Set([
"SIT", "UAT", "PTR", "BAST", "POC", "WIP", "WO", "IM",
"(SIT)", "(UAT)", "(PTR)", "(BAST)"
]);
if (trimmed.length === 3 || upperAcronyms.has(trimmed.toUpperCase())) {
return trimmed.toUpperCase();
}
// Capitalize setiap kata untuk teks status lainnya
// Capitalize setiap kata untuk teks status lainnya dengan memperhatikan akronim teknis
return trimmed
.split(/\s+/)
.map(word => {
if (!word) return "";
if (word.toUpperCase() === "GO-LIVE" || word.toLowerCase() === "go-live") return "Go-Live";
if (word === "&") return "&";
const stripped = word.replace(/[^a-zA-Z]/g, '').toUpperCase();
if (upperAcronyms.has(stripped) || upperAcronyms.has(word.toUpperCase())) {
return word.toUpperCase();
}
return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase();
})
.join(" ");
+21 -4
View File
@@ -57,11 +57,28 @@ export const STATUS_BADGE_MAP: Record<string, VariantProps<typeof badgeVariants>
"issue": "statusDanger",
"canceled": "statusDanger",
"sit": "statusTesting",
"uat": "statusTesting",
"ptr": "statusTesting",
// Technical progression stages
"development": "info",
"bast": "statusSuccess", // Handover/Sign-off
"sit": "statusTesting",
"system integration testing (sit)": "statusTesting",
"system integration testing": "statusTesting",
"uat": "violet",
"user acceptance testing (uat)": "violet",
"user acceptance testing": "violet",
"ptr": "statusWarning",
"production trial run (ptr)": "statusWarning",
"production trial run": "statusWarning",
"go-live": "statusSuccess",
"go live": "statusSuccess",
"golive": "statusSuccess",
"bast": "statusActive",
"project handover & bast": "statusActive",
"project handover and bast": "statusActive",
"warranty": "statusMaintenance",