import { client } from '@/ui/api/client' import type { TaskInfo } from '@shumai/dtos' import { useTeamId } from '@/ui/hooks/use-team-id' import { useInfiniteQuery } from '@tanstack/react-query' import { useUploadStore } from '@/ui/stores/upload' import { Loader2, CheckCircle2, Clock, UploadCloud } from 'lucide-react' import { useEffect, useMemo } from 'react' import { useInView } from 'react-intersection-observer' import { format, parseISO, isToday, isYesterday } from 'date-fns' import { Progress } from '@/ui/components/ui/progress' import { formatTimeAgo } from '@/ui/lib/time' import { m } from '@/ui/paraglide/messages.js' function formatDayHeader(dateString: string): string { const date = parseISO(dateString) if (isNaN(date.getTime())) { return m.unknown_date() } if (isToday(date)) { return m.today() } if (isYesterday(date)) { return m.yesterday() } return format(date, m.date_format_long()) } function formatBytes(bytes: number): string { if (bytes === 0) return '0 B' const k = 1024 const sizes = ['B', 'KB', 'MB', 'GB', 'TB'] const i = Math.floor(Math.log(bytes) / Math.log(k)) return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i] } function UploadTaskItem({ task }: { task: TaskInfo }) { const clientProgress = useUploadStore((state) => state.tasks[task.id]) const isCompleted = clientProgress ? clientProgress.loaded === clientProgress.total && task.uploaded === task.total : task.uploaded === task.total const percent = clientProgress ? clientProgress.total > 0 ? (clientProgress.loaded / clientProgress.total) * 100 : 0 : task.total > 0 ? (task.uploaded / task.total) * 100 : 0 let formattedTime: string try { formattedTime = formatTimeAgo(task.createdAt) } catch { formattedTime = m.unknown() } return (
{/* Top row: Name & Status Badge */}
{task.name || m.untitled_upload()}
{isCompleted ? ( {m.done()} ) : ( {m.uploading_status()} )}
{/* Middle row: Created Time (Date & Time together) */}
{formattedTime}
{/* Bottom row: Progress Bar and Fraction */}
{clientProgress ? `${formatBytes(clientProgress.loaded)} / ${formatBytes(clientProgress.total)} (${m.files_progress({ uploaded: task.uploaded, total: task.total })})` : m.files_progress({ uploaded: task.uploaded, total: task.total })} {!isCompleted && ( {Math.round(percent)}% )}
) } interface TaskGroup { day: string tasks: TaskInfo[] } export function UploadTasks() { const teamId = useTeamId() const uploading = useUploadStore((state) => state.uploading) const clientActiveTasks = useUploadStore((state) => state.tasks) const { data: tasksData, fetchNextPage, hasNextPage, isFetchingNextPage, isLoading, } = useInfiniteQuery({ queryKey: ['teams', teamId, 'upload', 'tasks'], queryFn: async ({ pageParam }) => { const res = await client.api.teams[':teamId'].upload.tasks.$get({ param: { teamId: teamId! }, query: { after: pageParam as string }, }) if (!res.ok) throw new Error('Failed to fetch upload tasks') return await res.json() }, initialPageParam: '', getNextPageParam: (lastPage) => { return lastPage.pageInfo?.cursor || undefined }, enabled: !!teamId, refetchInterval: uploading > 0 ? 2000 : false, }) const { ref, inView } = useInView() useEffect(() => { if (inView && hasNextPage && !isFetchingNextPage) { fetchNextPage() } }, [inView, hasNextPage, isFetchingNextPage, fetchNextPage]) const tasks = tasksData?.pages.flatMap((page) => page.data ?? []) ?? [] const combinedTasks = useMemo(() => { const serverTaskIds = new Set(tasks.map((t) => t.id)) const clientOnlyTasks: TaskInfo[] = Object.values(clientActiveTasks) .filter((ct) => !serverTaskIds.has(ct.taskId)) .map((ct) => { const completedCount = Object.values(ct.files).filter( (f) => f.status === 'completed' || f.status === 'failed', ).length return { id: ct.taskId, name: ct.name, total: Object.keys(ct.files).length, uploaded: completedCount, createdAt: new Date().toISOString(), } }) return [...clientOnlyTasks, ...tasks].sort((a, b) => b.id.localeCompare(a.id)) }, [tasks, clientActiveTasks]) if (isLoading) { return (
) } if (combinedTasks.length === 0) { return (

{m.no_uploads_yet()}

{m.no_uploads_hint()}

) } // Group tasks by day (maintaining desc ordering) const taskGroups: TaskGroup[] = [] combinedTasks.forEach((task) => { const day = formatDayHeader(task.createdAt) let group = taskGroups.find((g) => g.day === day) if (!group) { group = { day, tasks: [] } taskGroups.push(group) } group.tasks.push(task) }) return (
{taskGroups.map((group) => (
{/* Day Sticky Header */}
{group.day} {group.tasks.length === 1 ? m.n_tasks_singular({ count: group.tasks.length }) : m.n_tasks_plural({ count: group.tasks.length })}
{/* Tasks in Day */}
{group.tasks.map((task) => ( ))}
))} {hasNextPage && (
{isFetchingNextPage && }
)}
) }