feat: add figma make components

This commit is contained in:
ValdiANS
2026-01-07 10:59:12 +07:00
parent 88c6c863e7
commit 770f363c60
56 changed files with 11887 additions and 0 deletions
@@ -0,0 +1,938 @@
'use client';
import { useState, useEffect } from 'react';
import { Eye, CheckCircle, XCircle, Search, Trash2 } from 'lucide-react';
import { Card, CardContent } from '@/figma-make/components/base/card';
import { Button } from '@/figma-make/components/base/button';
import { Badge } from '@/figma-make/components/base/badge';
import { Input } from '@/figma-make/components/base/input';
import { Label } from '@/figma-make/components/base/label';
import { Textarea } from '@/figma-make/components/base/textarea';
import { DateRangePicker } from '@/figma-make/components/base/date-range-picker';
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/figma-make/components/base/select';
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogDescription,
DialogFooter,
} from '@/figma-make/components/base/dialog';
import { toast } from 'sonner';
import { supabase, isSupabaseConfigured } from '@/figma-make/lib/supabase';
import { useRouter } from 'next/navigation';
interface ChecklistItem {
checklist_id: string;
date: string;
kandang_name: string;
kandang_id: string; // ✅ Add kandang_id
category: string;
status: string;
progress_percent: number;
total_phases: number;
total_activities: number;
updated_at: string;
}
interface Kandang {
id: string;
name: string;
}
interface ChecklistQueryResult {
id: string;
date: string;
kandang_id: string;
category: string;
status: string;
updated_at: string;
kandang: {
id: string;
name: string;
} | null;
}
const STATUS_OPTIONS = [
{ value: 'ALL', label: 'Semua Status' },
{ value: 'DRAFT', label: 'Draft' },
{ value: 'SUBMITTED', label: 'Submitted' },
{ value: 'APPROVED', label: 'Approved' },
{ value: 'REJECTED', label: 'Rejected' },
];
const CATEGORY_LABELS: { [key: string]: string } = {
pullet_open: 'Pullet Open',
pullet_close: 'Pullet Close',
produksi_open: 'Produksi Open',
produksi_close: 'Produksi Close',
};
export function ListDailyChecklistContent() {
const router = useRouter();
const [checklistList, setChecklistList] = useState<ChecklistItem[]>([]);
const [filteredList, setFilteredList] = useState<ChecklistItem[]>([]);
const [loading, setLoading] = useState(true);
// Master data
const [kandangList, setKandangList] = useState<Kandang[]>([]);
// Filters
const [statusFilter, setStatusFilter] = useState('ALL');
const [kandangFilter, setKandangFilter] = useState('ALL');
const [searchText, setSearchText] = useState('');
const [dateFrom, setDateFrom] = useState('');
const [dateTo, setDateTo] = useState('');
// Modals
const [showApproveModal, setShowApproveModal] = useState(false);
const [showRejectModal, setShowRejectModal] = useState(false);
const [showDeleteModal, setShowDeleteModal] = useState(false);
const [selectedItem, setSelectedItem] = useState<ChecklistItem | null>(null);
const [rejectReason, setRejectReason] = useState('');
const [actionLoading, setActionLoading] = useState(false);
useEffect(() => {
fetchKandangList();
fetchChecklistList();
}, []);
useEffect(() => {
applyFilters();
}, [
checklistList,
statusFilter,
kandangFilter,
searchText,
dateFrom,
dateTo,
]);
const fetchKandangList = async () => {
if (!isSupabaseConfigured()) return;
try {
const { data, error } = await supabase
.from('kandang')
.select('id, name')
.order('name', { ascending: true });
if (error) {
console.error('Error fetching kandang:', error);
return;
}
setKandangList(data || []);
} catch (error) {
console.error('Error fetching kandang:', error);
}
};
const fetchChecklistList = async () => {
if (!isSupabaseConfigured()) {
console.warn('Supabase not configured');
setLoading(false);
return;
}
try {
setLoading(true);
// ✅ Fetch checklists with joins to get complete data
const { data: checklists, error } = await supabase
.from('daily_checklists')
.select(
`
id,
date,
kandang_id,
category,
status,
updated_at,
kandang:kandang_id (
id,
name
)
`
)
.order('date', { ascending: false })
.order('updated_at', { ascending: false });
if (error) {
console.error('Error fetching checklist list:', error);
toast.error('Gagal memuat data checklist');
return;
}
// ✅ For each checklist, fetch phases, activities, and assignments count
const enrichedData: ChecklistItem[] = await Promise.all(
((checklists as unknown as ChecklistQueryResult[]) || [])
.filter((checklist) => checklist.id) // ✅ Skip checklists with null ID
.map(async (checklist) => {
// Count phases
const { count: phaseCount } = await supabase
.from('daily_checklist_phases')
.select('*', { count: 'exact', head: true })
.eq('checklist_id', checklist.id);
// Count activities (tasks)
const { count: activityCount } = await supabase
.from('daily_checklist_activity_tasks')
.select('*', { count: 'exact', head: true })
.eq('checklist_id', checklist.id);
// ✅ NEW LOGIC: Calculate progress based on phase coverage
// Step 1: Get total phases in master data for this category
const { count: totalPhasesInMaster } = await supabase
.from('phases')
.select('*', { count: 'exact', head: true })
.eq('category_id', checklist.category);
// Step 2: Get phases that have at least 1 CHECKED assignment
// First, get all tasks for this checklist
const { data: tasks } = await supabase
.from('daily_checklist_activity_tasks')
.select('id, phase_id')
.eq('checklist_id', checklist.id);
const taskIds = (tasks || []).map((t) => t.id);
const uniquePhasesWithChecked = new Set<string>();
if (taskIds.length > 0) {
// Get assignments that are CHECKED
const { data: checkedAssignments } = await supabase
.from('daily_checklist_activity_task_assignments')
.select('task_id')
.in('task_id', taskIds)
.eq('checked', true); // ✅ Only get checked assignments
if (checkedAssignments && checkedAssignments.length > 0) {
// Map task_ids back to phase_ids
const checkedTaskIds = new Set(
checkedAssignments.map((a) => a.task_id)
);
tasks?.forEach((task) => {
if (checkedTaskIds.has(task.id)) {
uniquePhasesWithChecked.add(task.phase_id);
}
});
}
}
const phasesWithCheckedCount = uniquePhasesWithChecked.size;
// Step 3: Calculate progress
const progressPercent =
totalPhasesInMaster && totalPhasesInMaster > 0
? Math.round(
(phasesWithCheckedCount / totalPhasesInMaster) * 100
)
: 0;
return {
checklist_id: checklist.id,
date: checklist.date,
kandang_name: checklist.kandang?.name || '-',
kandang_id: checklist.kandang_id,
category: checklist.category,
status: checklist.status,
progress_percent: progressPercent,
total_phases: phaseCount || 0,
total_activities: activityCount || 0,
updated_at: checklist.updated_at,
};
})
);
setChecklistList(enrichedData);
} catch (error) {
console.error('Error fetching checklist list:', error);
toast.error('Terjadi kesalahan');
} finally {
setLoading(false);
}
};
const applyFilters = () => {
let filtered = [...checklistList];
// Filter by status
if (statusFilter && statusFilter !== 'ALL') {
filtered = filtered.filter((item) => item.status === statusFilter);
}
// ✅ Filter by kandang - use kandang_id directly from item
if (kandangFilter && kandangFilter !== 'ALL') {
filtered = filtered.filter((item) => item.kandang_id === kandangFilter);
}
// Filter by search text (kandang_name or category)
if (searchText) {
const searchLower = searchText.toLowerCase();
filtered = filtered.filter(
(item) =>
item.kandang_name.toLowerCase().includes(searchLower) ||
item.category.toLowerCase().includes(searchLower) ||
(CATEGORY_LABELS[item.category] || '')
.toLowerCase()
.includes(searchLower)
);
}
// Filter by date range
if (dateFrom) {
filtered = filtered.filter((item) => item.date >= dateFrom);
}
if (dateTo) {
filtered = filtered.filter((item) => item.date <= dateTo);
}
setFilteredList(filtered);
};
const handleDetail = (item: ChecklistItem) => {
router.push(
`/daily-checklist/list-daily-checklist/detail?checklistId=${item.checklist_id}`
);
};
const handleApprove = (item: ChecklistItem) => {
setSelectedItem(item);
setShowApproveModal(true);
};
const handleReject = (item: ChecklistItem) => {
setSelectedItem(item);
setRejectReason('');
setShowRejectModal(true);
};
const handleDelete = (item: ChecklistItem) => {
// ✅ VALIDATION: Only DRAFT can be deleted
if (item.status !== 'DRAFT') {
toast.error('Hanya checklist dengan status DRAFT yang bisa dihapus', {
description: `Status saat ini: ${item.status}`,
});
return;
}
setSelectedItem(item);
setShowDeleteModal(true);
};
const confirmApprove = async () => {
if (!selectedItem || !isSupabaseConfigured()) return;
try {
setActionLoading(true);
const { error } = await supabase
.from('daily_checklists')
.update({
status: 'APPROVED',
updated_at: new Date().toISOString(),
})
.eq('id', selectedItem.checklist_id);
if (error) {
console.error('Error approving checklist:', error);
toast.error('Gagal approve checklist');
return;
}
toast.success('Checklist berhasil di-approve');
setShowApproveModal(false);
setSelectedItem(null);
await fetchChecklistList();
} catch (error) {
console.error('Error approving checklist:', error);
toast.error('Terjadi kesalahan');
} finally {
setActionLoading(false);
}
};
const confirmReject = async () => {
if (!selectedItem || !isSupabaseConfigured()) return;
if (!rejectReason.trim()) {
toast.error('Alasan reject harus diisi');
return;
}
try {
setActionLoading(true);
const { error } = await supabase
.from('daily_checklists')
.update({
status: 'REJECTED',
reject_reason: rejectReason,
updated_at: new Date().toISOString(),
})
.eq('id', selectedItem.checklist_id);
if (error) {
console.error('Error rejecting checklist:', error);
toast.error('Gagal reject checklist');
return;
}
toast.success('Checklist berhasil di-reject');
setShowRejectModal(false);
setSelectedItem(null);
setRejectReason('');
await fetchChecklistList();
} catch (error) {
console.error('Error rejecting checklist:', error);
toast.error('Terjadi kesalahan');
} finally {
setActionLoading(false);
}
};
const confirmDelete = async () => {
if (!selectedItem || !isSupabaseConfigured()) return;
try {
setActionLoading(true);
const { error } = await supabase
.from('daily_checklists')
.delete()
.eq('id', selectedItem.checklist_id);
if (error) {
console.error('Error deleting checklist:', error);
toast.error('Gagal hapus checklist');
return;
}
toast.success('Checklist berhasil dihapus');
setShowDeleteModal(false);
setSelectedItem(null);
await fetchChecklistList();
} catch (error) {
console.error('Error deleting checklist:', error);
toast.error('Terjadi kesalahan');
} finally {
setActionLoading(false);
}
};
const getStatusBadge = (status: string) => {
switch (status) {
case 'DRAFT':
return (
<Badge
variant='outline'
className='border-gray-300 text-gray-700 bg-white'
>
Draft
</Badge>
);
case 'SUBMITTED':
return (
<Badge
variant='outline'
className='border-orange-300 text-orange-700 bg-white'
>
Submitted
</Badge>
);
case 'APPROVED':
return (
<Badge
variant='outline'
className='border-green-300 text-green-700 bg-white'
>
Approved
</Badge>
);
case 'REJECTED':
return (
<Badge
variant='outline'
className='border-red-300 text-red-700 bg-white'
>
Rejected
</Badge>
);
default:
return (
<Badge
variant='outline'
className='border-gray-300 text-gray-700 bg-white'
>
{status}
</Badge>
);
}
};
const formatDate = (dateString: string) => {
const date = new Date(dateString);
return date.toLocaleDateString('id-ID', {
day: '2-digit',
month: 'short',
year: 'numeric',
});
};
const formatDateTime = (dateString: string) => {
const date = new Date(dateString);
return date.toLocaleString('id-ID', {
day: '2-digit',
month: 'short',
year: 'numeric',
hour: '2-digit',
minute: '2-digit',
});
};
return (
<div className='min-h-screen'>
<div className='p-6'>
{/* Page Title */}
<div className='mb-6'>
<h1 className='text-2xl font-semibold text-gray-900'>
List Daily Checklist
</h1>
<p className='text-sm text-gray-600 mt-1'>
Daftar semua checklist harian
</p>
</div>
{/* Main Card */}
<Card className='border-gray-200/60 shadow-sm rounded-xl bg-white'>
<CardContent className='p-6'>
{/* Filters Section */}
<div className='grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 mb-6 pb-6 border-b border-gray-200'>
<div>
<Label>Periode Tanggal</Label>
<div className='mt-1.5'>
<DateRangePicker
dateFrom={dateFrom}
dateTo={dateTo}
onDateChange={(from, to) => {
setDateFrom(from);
setDateTo(to);
}}
/>
</div>
</div>
<div>
<Label htmlFor='kandang-filter'>Kandang</Label>
<div className='mt-1.5'>
<Select
value={kandangFilter}
onValueChange={setKandangFilter}
>
<SelectTrigger
id='kandang-filter'
className='border-gray-200'
>
<SelectValue placeholder='Semua Kandang' />
</SelectTrigger>
<SelectContent>
<SelectItem value='ALL'>Semua Kandang</SelectItem>
{kandangList.map((kandang) => (
<SelectItem key={kandang.id} value={kandang.id}>
{kandang.name}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
</div>
<div>
<Label htmlFor='status-filter'>Status</Label>
<div className='mt-1.5'>
<Select value={statusFilter} onValueChange={setStatusFilter}>
<SelectTrigger
id='status-filter'
className='border-gray-200'
>
<SelectValue placeholder='Semua Status' />
</SelectTrigger>
<SelectContent>
{STATUS_OPTIONS.map((option) => (
<SelectItem key={option.value} value={option.value}>
{option.label}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
</div>
<div>
<Label htmlFor='search-text'>Cari</Label>
<div className='relative mt-1.5'>
<Input
id='search-text'
type='text'
placeholder='Kandang / Kategori...'
value={searchText}
onChange={(e) => setSearchText(e.target.value)}
className='border-gray-200 pl-9'
/>
<Search className='absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400' />
</div>
</div>
</div>
{/* Table Section */}
{loading ? (
<div className='text-center py-12 text-gray-500'>
Memuat data...
</div>
) : filteredList.length > 0 ? (
<div className='overflow-x-auto'>
<table className='w-full border border-gray-200 rounded-lg'>
<thead>
<tr className='bg-gray-50 border-b border-gray-200'>
<th className='text-left py-3 px-4 text-sm font-semibold text-gray-700'>
Tanggal
</th>
<th className='text-left py-3 px-4 text-sm font-semibold text-gray-700'>
Kandang
</th>
<th className='text-left py-3 px-4 text-sm font-semibold text-gray-700'>
Kategori
</th>
<th className='text-left py-3 px-4 text-sm font-semibold text-gray-700'>
Status
</th>
<th className='text-center py-3 px-4 text-sm font-semibold text-gray-700'>
Total Phase
</th>
<th className='text-center py-3 px-4 text-sm font-semibold text-gray-700'>
Total Aktivitas
</th>
<th className='text-center py-3 px-4 text-sm font-semibold text-gray-700'>
Progress
</th>
<th className='text-left py-3 px-4 text-sm font-semibold text-gray-700'>
Updated At
</th>
<th className='text-center py-3 px-4 text-sm font-semibold text-gray-700'>
Aksi
</th>
</tr>
</thead>
<tbody>
{filteredList.map((item, index) => (
<tr
key={`${item.checklist_id}-${index}`}
className={
index % 2 === 0 ? 'bg-white' : 'bg-gray-50/50'
}
>
<td className='py-3 px-4 text-sm text-gray-900'>
{formatDate(item.date)}
</td>
<td className='py-3 px-4 text-sm text-gray-900'>
{item.kandang_name}
</td>
<td className='py-3 px-4 text-sm text-gray-900'>
{CATEGORY_LABELS[item.category] || item.category}
</td>
<td className='py-3 px-4'>
{getStatusBadge(item.status)}
</td>
<td className='py-3 px-4 text-center text-sm text-gray-900'>
{item.total_phases}
</td>
<td className='py-3 px-4 text-center text-sm text-gray-900'>
{item.total_activities}
</td>
<td className='py-3 px-4 text-center'>
<div className='flex items-center justify-center gap-2'>
<div className='w-24 bg-gray-200 rounded-full h-2'>
<div
className='bg-[#0069e0] h-2 rounded-full transition-all'
style={{ width: `${item.progress_percent}%` }}
/>
</div>
<span className='text-sm text-gray-700 font-medium'>
{item.progress_percent}%
</span>
</div>
</td>
<td className='py-3 px-4 text-sm text-gray-600'>
{formatDateTime(item.updated_at)}
</td>
<td className='py-3 px-4'>
<div className='flex items-center justify-center gap-2'>
<Button
size='sm'
variant='outline'
onClick={() => handleDetail(item)}
className='border-gray-200 text-gray-700 hover:bg-gray-50'
>
<Eye className='w-4 h-4 mr-1' />
Detail
</Button>
{item.status === 'SUBMITTED' && (
<>
<Button
size='sm'
onClick={() => handleApprove(item)}
className='bg-green-600 hover:bg-green-700 text-white'
>
<CheckCircle className='w-4 h-4 mr-1' />
Approve
</Button>
<Button
size='sm'
variant='destructive'
onClick={() => handleReject(item)}
className='bg-red-600 hover:bg-red-700 text-white'
>
<XCircle className='w-4 h-4 mr-1' />
Reject
</Button>
</>
)}
<Button
size='sm'
variant='destructive'
onClick={() => handleDelete(item)}
className='bg-red-600 hover:bg-red-700 text-white'
>
<Trash2 className='w-4 h-4 mr-1' />
Hapus
</Button>
</div>
</td>
</tr>
))}
</tbody>
</table>
</div>
) : (
<div className='text-center py-12 text-gray-500'>
{searchText ||
dateFrom ||
dateTo ||
statusFilter !== 'ALL' ||
kandangFilter !== 'ALL'
? 'Tidak ada data yang sesuai dengan filter'
: 'Belum ada data checklist'}
</div>
)}
</CardContent>
</Card>
</div>
{/* Approve Modal */}
<Dialog open={showApproveModal} onOpenChange={setShowApproveModal}>
<DialogContent className='sm:max-w-md bg-white rounded-xl shadow-lg'>
<DialogHeader>
<DialogTitle>Approve Checklist</DialogTitle>
<DialogDescription>
Apakah Anda yakin ingin approve checklist ini?
</DialogDescription>
</DialogHeader>
{selectedItem && (
<div className='bg-gray-50 rounded-lg p-4 space-y-2'>
<div className='flex justify-between text-sm'>
<span className='text-gray-600'>Tanggal:</span>
<span className='font-medium text-gray-900'>
{formatDate(selectedItem.date)}
</span>
</div>
<div className='flex justify-between text-sm'>
<span className='text-gray-600'>Kandang:</span>
<span className='font-medium text-gray-900'>
{selectedItem.kandang_name}
</span>
</div>
<div className='flex justify-between text-sm'>
<span className='text-gray-600'>Kategori:</span>
<span className='font-medium text-gray-900'>
{CATEGORY_LABELS[selectedItem.category] ||
selectedItem.category}
</span>
</div>
<div className='flex justify-between text-sm'>
<span className='text-gray-600'>Progress:</span>
<span className='font-medium text-gray-900'>
{selectedItem.progress_percent}%
</span>
</div>
</div>
)}
<DialogFooter className='flex gap-2'>
<Button
variant='outline'
onClick={() => setShowApproveModal(false)}
disabled={actionLoading}
className='border-gray-200'
>
Batal
</Button>
<Button
onClick={confirmApprove}
disabled={actionLoading}
className='bg-green-600 hover:bg-green-700 text-white'
>
{actionLoading ? 'Memproses...' : 'Ya, Approve'}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
{/* Reject Modal */}
<Dialog open={showRejectModal} onOpenChange={setShowRejectModal}>
<DialogContent className='sm:max-w-md bg-white rounded-xl shadow-lg'>
<DialogHeader>
<DialogTitle>Reject Checklist</DialogTitle>
<DialogDescription>
Berikan alasan reject untuk checklist ini
</DialogDescription>
</DialogHeader>
{selectedItem && (
<div className='bg-gray-50 rounded-lg p-4 space-y-2 mb-4'>
<div className='flex justify-between text-sm'>
<span className='text-gray-600'>Tanggal:</span>
<span className='font-medium text-gray-900'>
{formatDate(selectedItem.date)}
</span>
</div>
<div className='flex justify-between text-sm'>
<span className='text-gray-600'>Kandang:</span>
<span className='font-medium text-gray-900'>
{selectedItem.kandang_name}
</span>
</div>
<div className='flex justify-between text-sm'>
<span className='text-gray-600'>Kategori:</span>
<span className='font-medium text-gray-900'>
{CATEGORY_LABELS[selectedItem.category] ||
selectedItem.category}
</span>
</div>
</div>
)}
<div>
<Label htmlFor='reject-reason'>
Alasan Reject <span className='text-red-500'>*</span>
</Label>
<Textarea
id='reject-reason'
value={rejectReason}
onChange={(e) => setRejectReason(e.target.value)}
placeholder='Tuliskan alasan reject...'
className='mt-1.5 border-gray-200 min-h-[100px]'
disabled={actionLoading}
/>
</div>
<DialogFooter className='flex gap-2'>
<Button
variant='outline'
onClick={() => setShowRejectModal(false)}
disabled={actionLoading}
className='border-gray-200'
>
Batal
</Button>
<Button
onClick={confirmReject}
disabled={actionLoading}
variant='destructive'
className='bg-red-600 hover:bg-red-700 text-white'
>
{actionLoading ? 'Memproses...' : 'Ya, Reject'}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
{/* Delete Modal */}
<Dialog open={showDeleteModal} onOpenChange={setShowDeleteModal}>
<DialogContent className='sm:max-w-md bg-white rounded-xl shadow-lg'>
<DialogHeader>
<DialogTitle className='text-red-600'>
Hapus Checklist
</DialogTitle>
<DialogDescription>
Apakah Anda yakin ingin menghapus checklist ini? Data yang dihapus
tidak dapat dikembalikan.
</DialogDescription>
</DialogHeader>
{selectedItem && (
<>
<div className='bg-red-50 border border-red-200 rounded-lg p-4 space-y-2 mb-2'>
<div className='flex justify-between text-sm'>
<span className='text-gray-600'>Tanggal:</span>
<span className='font-medium text-gray-900'>
{formatDate(selectedItem.date)}
</span>
</div>
<div className='flex justify-between text-sm'>
<span className='text-gray-600'>Kandang:</span>
<span className='font-medium text-gray-900'>
{selectedItem.kandang_name}
</span>
</div>
<div className='flex justify-between text-sm'>
<span className='text-gray-600'>Kategori:</span>
<span className='font-medium text-gray-900'>
{CATEGORY_LABELS[selectedItem.category] ||
selectedItem.category}
</span>
</div>
<div className='flex justify-between text-sm'>
<span className='text-gray-600'>Status:</span>
{getStatusBadge(selectedItem.status)}
</div>
</div>
<div className='bg-yellow-50 border border-yellow-200 rounded-lg p-3'>
<p className='text-xs text-yellow-800'>
<strong>Peringatan:</strong> Semua data terkait (phases,
activities, assignments) akan ikut terhapus secara permanen.
</p>
</div>
</>
)}
<DialogFooter className='flex gap-2'>
<Button
variant='outline'
onClick={() => setShowDeleteModal(false)}
disabled={actionLoading}
className='border-gray-200'
>
Batal
</Button>
<Button
onClick={confirmDelete}
disabled={actionLoading}
variant='destructive'
className='bg-red-600 hover:bg-red-700 text-white'
>
{actionLoading ? 'Memproses...' : 'Ya, Hapus'}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</div>
);
}