import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'; import { useTranslation } from 'react-i18next'; import { Loader2, Trash2, Clock } from 'lucide-react'; import { api } from '../api/client'; import type { SpoolUsageRecord } from '../api/client'; import { Button } from './Button'; import { useToast } from '../contexts/ToastContext'; import { parseUTCDate } from '../utils/date'; import { ownRecords } from '../utils/usageHistory'; function formatDate(dateStr: string): string { const date = parseUTCDate(dateStr); if (!date) return ''; return date.toLocaleDateString('en-GB', { day: '2-digit', month: '2-digit', year: '2-digit' }) + ' ' + date.toLocaleTimeString('en-GB', { hour: '2-digit', minute: '2-digit' }); } interface SpoolUsageHistoryProps { spoolId: number; // A Spoolman spool: the rows Bambuddy wrote for the prints it charged (#3407). spoolman?: boolean; // When the spool was created: older rows are an earlier spool's that had its id. createdAt?: string | null; } const STATUS_COLORS: Record = { completed: 'text-bambu-green', failed: 'text-red-700 dark:text-red-400', aborted: 'text-yellow-700 dark:text-yellow-400', }; export function SpoolUsageHistory({ spoolId, spoolman = false, createdAt = null }: SpoolUsageHistoryProps) { const { t } = useTranslation(); const queryClient = useQueryClient(); const { showToast } = useToast(); const { data: fetched, isLoading } = useQuery({ queryKey: ['spool-usage', spoolman, spoolId], queryFn: () => (spoolman ? api.getSpoolmanSpoolUsageHistory(spoolId) : api.getSpoolUsageHistory(spoolId)), }); const history = fetched && spoolman ? ownRecords({ created_at: createdAt }, fetched) : fetched; const clearMutation = useMutation({ mutationFn: () => (spoolman ? api.clearSpoolmanSpoolUsageHistory(spoolId) : api.clearSpoolUsageHistory(spoolId)), onSuccess: () => { queryClient.invalidateQueries({ queryKey: ['spool-usage', spoolman, spoolId] }); showToast(t('inventory.historyCleared'), 'success'); }, }); if (isLoading) { return (
); } if (!history || history.length === 0) { return (
{t('inventory.noUsageHistory')}
); } return (

{t('inventory.usageHistory')}

{history.map((record: SpoolUsageRecord) => (
{formatDate(record.created_at)} {record.print_name && ( {record.print_name} )}
{record.weight_used.toFixed(1)}g ({record.percent_used}%) {record.status}
))}
); }