import { useEffect, useMemo, useState } from 'react'; import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'; import { useTranslation } from 'react-i18next'; import { AlertTriangle, Combine, Loader2, X } from 'lucide-react'; import { api } from '../api/client'; import type { ArchiveMergeGroup, ArchiveMergeMember, ArchiveMergeResult } from '../api/client'; import { Button } from './Button'; import { useToast } from '../contexts/ToastContext'; interface MergeDuplicatesModalProps { onClose: () => void; } function memberName(member: ArchiveMergeMember): string { return member.print_name || member.filename; } /** * "Merge duplicates" (archive redesign P2): the archives that hold the same * file merge into the oldest. The server finds the groups and says which it * leaves out for now; the user picks the groups, confirms, and gets a report. */ export function MergeDuplicatesModal({ onClose }: MergeDuplicatesModalProps) { const { t, i18n } = useTranslation(); const queryClient = useQueryClient(); const { showToast } = useToast(); const previewQuery = useQuery({ queryKey: ['archive-merge-preview'], queryFn: () => api.previewArchiveMerge(), // Each opening asks again: groups change as prints start and end. Not // behind the user's back while it is open: what they confirm is what // they saw. staleTime: 0, gcTime: 0, refetchOnWindowFocus: false, }); const groups = useMemo(() => previewQuery.data?.groups ?? [], [previewQuery.data]); const mergeable = useMemo(() => groups.filter((g) => g.skipped === null), [groups]); const waiting = useMemo(() => groups.filter((g) => g.skipped !== null), [groups]); // Every mergeable group is ticked once the preview arrives. const [unticked, setUnticked] = useState>(new Set()); const selected = mergeable.filter((g) => !unticked.has(g.survivor.id)); const [confirming, setConfirming] = useState(false); // The groups the merge itself left out, and why, shown before closing. const [result, setResult] = useState(null); const mergeMutation = useMutation({ mutationFn: () => api.mergeArchives(selected.map((g) => g.survivor.id)), onSuccess: (result: ArchiveMergeResult) => { const merged = result.merged.length; const left = result.skipped.length; // Runs moved between archives: every list of archives and runs. for (const key of ['archives', 'archive', 'archiveStats', 'archives-stats', 'print-log', 'archive-runs', 'calendar-runs', 'archive-merge-count']) { queryClient.invalidateQueries({ queryKey: [key] }); } if (left === 0) { showToast(t('archiveMerge.toast.merged', { count: merged }), 'success'); onClose(); } else { showToast(t('archiveMerge.toast.mergedSome', { count: merged, left }), merged > 0 ? 'warning' : 'error'); setResult(result); } }, onError: (e: Error) => showToast(e.message || t('archiveMerge.toast.failed'), 'error'), }); useEffect(() => { const handleKey = (e: KeyboardEvent) => { if (e.key === 'Escape' && !mergeMutation.isPending) onClose(); }; window.addEventListener('keydown', handleKey); return () => window.removeEventListener('keydown', handleKey); }, [onClose, mergeMutation.isPending]); const toggle = (group: ArchiveMergeGroup) => { setConfirming(false); setUnticked((current) => { const next = new Set(current); if (next.has(group.survivor.id)) next.delete(group.survivor.id); else next.add(group.survivor.id); return next; }); }; const formatDate = (iso: string | null) => iso ? new Date(iso.endsWith('Z') || iso.includes('+') ? iso : `${iso}Z`).toLocaleDateString(i18n.language) : ''; const renderGroup = (group: ArchiveMergeGroup) => { const ticked = group.skipped === null && !unticked.has(group.survivor.id); return (
  • ); }; return (

    {t('archiveMerge.title')}

    {t('archiveMerge.effectsTitle')}
    • {t('archiveMerge.effect1')}
    • {t('archiveMerge.effect2')}
    • {t('archiveMerge.effect3')}
    {result ? (
    {t('archiveMerge.leftOutTitle')}
      {result.skipped.map((skip) => { const group = groups.find((g) => g.survivor.id === skip.survivor_id); return (
    • {group ? memberName(group.survivor) : `#${skip.survivor_id}`}
      {t(`archiveMerge.skipped.${skip.reason}`)}
    • ); })}
    ) : previewQuery.isLoading ? (
    {t('archiveMerge.previewLoading')}
    ) : previewQuery.isError ? (
    {(previewQuery.error as Error | null)?.message ?? t('archiveMerge.previewFailed')}
    ) : groups.length === 0 ? (
    {t('archiveMerge.none')}
    ) : ( <> {mergeable.length > 0 &&
      {mergeable.map(renderGroup)}
    } {waiting.length > 0 && (
    {t('archiveMerge.waitingTitle')}
      {waiting.map(renderGroup)}
    )} )} {confirming && !result && (
    {t('archiveMerge.confirmWarning', { count: selected.length })}
    )}
    {!result && ( )}
    ); }