Files
leocrm/frontend/src/pages/Trash.tsx
T
Agent Zero abbe7a18fc fix(audit): P0-P3 audit fixes — 838 ruff errors → 0, 30 F821 bugs fixed, 118 files changed
- P0: hooks.py 3-tuple fix, trigger_dispatcher Contract, contacts/plugin unregister_actions_by_owner
- P0: 5 test files — check_permission mocks removed, hardcoded DB credential → env var
- P1: attachment_service DmsFile via Contract helper, restore_registry/history_hooks dedup
- P1: mail/plugin restore unregister, mcp_client datetime.now(UTC), saved_views/filters patterns
- P1: ProtectedRoute fail-closed, 13 test assertion fixes (bcrypt, DB-URLs, SECRET_KEYs)
- P2: deprecated notifications → post_system_message (3 files), forgejo Base, report_generator lazy import
- P2: webhooks permissions, deps.py/roles.py plugin perms removed, import_export default
- P2: address/tags/entity_links patterns removed, worker.py Contract-Umgehungen fixed
- P2: 28 frontend TODOs (hardcoded constants, deprecated notification API)
- P3: dead code, duplicates, deprecated imports, private attr, __import__ inline
- P3: 8 frontend TODOs (LucideIcons, inline styles, XSS, i18n)
- ruff: 838 → 0 (612 auto-fix + 246 manual + 27 F821 regression fix)
- F821: 30 → 0 (AutomationDefinition, DmsFile, user_id, Path, Any, String)
- Contract-Umgehungen: 2 neue gefunden (worker.py:169, worker.py:280) und gefixt
2026-08-16 01:17:18 +02:00

266 lines
10 KiB
TypeScript

import React, { useCallback, useMemo, useState } from 'react';
// TODO: P2-F24 — Replace hardcoded ENTITY_TYPES with dynamic config
import { useTranslation } from 'react-i18next';
import { Trash2, RotateCcw } from 'lucide-react';
import { Button } from '@/components/ui/Button';
import { Card } from '@/components/ui/Card';
import { Select } from '@/components/ui/Select';
import { Pagination } from '@/components/ui/Pagination';
import { EmptyState } from '@/components/ui/EmptyState';
import { Skeleton } from '@/components/ui/Skeleton';
import { Badge } from '@/components/ui/Badge';
import { useToast } from '@/components/ui/Toast';
import { useTrashList, useRestoreFromHistory, useBulkRestore, type TrashItem } from '@/api/entityHistory';
import { formatDateShort } from '@/utils/date';
const PAGE_SIZE = 50;
const ENTITY_TYPES = ['contact', 'task', 'calendar_entry', 'dms_file', 'mail'] as const;
type EntityType = (typeof ENTITY_TYPES)[number];
/** Coerce an unknown snapshot value to a string, or '' when null/undefined. */
function str(value: unknown): string {
return value === null || value === undefined ? '' : String(value);
}
/** Extract a display name/subject from the snapshot_before payload per entity type. */
function getDisplayName(item: TrashItem): string {
const snap = item.snapshot_before ?? {};
switch (item.entity_type) {
case 'contact': {
const first = str(snap.first_name);
const last = str(snap.last_name);
const company = str(snap.company_name);
const full = [first, last].filter(Boolean).join(' ');
return full || company || str(snap.name) || '—';
}
case 'task':
case 'calendar_entry':
return str(snap.title) || str(snap.subject) || str(snap.name) || '—';
case 'dms_file':
return str(snap.name) || str(snap.filename) || str(snap.original_name) || '—';
case 'mail':
return str(snap.subject) || str(snap.name) || '—';
default:
return str(snap.name) || str(snap.title) || str(snap.subject) || '—';
}
}
export function TrashPage() {
const { t } = useTranslation();
const toast = useToast();
const [entityType, setEntityType] = useState<string>('');
const [page, setPage] = useState(1);
const [selected, setSelected] = useState<Set<string>>(new Set());
const offset = (page - 1) * PAGE_SIZE;
const { data, isLoading, isFetching } = useTrashList(entityType || undefined, PAGE_SIZE, offset);
const restoreMutation = useRestoreFromHistory();
const bulkRestoreMutation = useBulkRestore();
const items = data?.items ?? [];
const total = data?.total ?? 0;
const totalPages = Math.max(1, Math.ceil(total / PAGE_SIZE));
const entityTypeOptions = useMemo(
() => [
{ value: '', label: t('trash.allTypes', 'Alle Typen') },
...ENTITY_TYPES.map((type) => ({ value: type, label: t(`trash.types.${type}`) })),
],
[t]
);
const handleFilterChange = useCallback((value: string) => {
setEntityType(value);
setPage(1);
setSelected(new Set());
}, []);
const toggleSelect = useCallback((historyId: string) => {
setSelected((prev) => {
const next = new Set(prev);
if (next.has(historyId)) {
next.delete(historyId);
} else {
next.add(historyId);
}
return next;
});
}, []);
const toggleSelectAll = useCallback(() => {
setSelected((prev) => {
if (prev.size === items.length && items.length > 0) {
return new Set();
}
return new Set(items.map((item) => item.history_id));
});
}, [items]);
const handleSingleRestore = useCallback(
async (historyId: string) => {
try {
await restoreMutation.mutateAsync(historyId);
toast.success(t('trash.restored', 'Wiederhergestellt'));
setSelected((prev) => {
const next = new Set(prev);
next.delete(historyId);
return next;
});
} catch {
toast.error(t('trash.restoreError', 'Wiederherstellung fehlgeschlagen'));
}
},
[restoreMutation, toast, t]
);
const handleBulkRestore = useCallback(async () => {
if (selected.size === 0) return;
try {
const result = await bulkRestoreMutation.mutateAsync(Array.from(selected));
if (result.failed > 0) {
toast.warning(
t('trash.bulkPartial', '{{succeeded}} wiederhergestellt, {{failed}} fehlgeschlagen', {
succeeded: result.succeeded,
failed: result.failed,
})
);
} else {
toast.success(t('trash.bulkRestored', '{{count}} Einträge wiederhergestellt', { count: result.succeeded }));
}
setSelected(new Set());
} catch {
toast.error(t('trash.bulkRestoreError', 'Massen-Wiederherstellung fehlgeschlagen'));
}
}, [selected, bulkRestoreMutation, toast, t]);
const handlePageChange = useCallback((nextPage: number) => {
setPage(nextPage);
setSelected(new Set());
}, []);
return (
<div className="p-6 max-w-7xl mx-auto" data-testid="trash-page">
<div className="flex items-center justify-between mb-6">
<div className="flex items-center gap-3">
<Trash2 className="w-6 h-6 text-secondary-500" aria-hidden="true" />
<h1 className="text-2xl font-bold text-secondary-900">{t('trash.title', 'Papierkorb')}</h1>
</div>
<Button
variant="primary"
onClick={handleBulkRestore}
disabled={selected.size === 0}
isLoading={bulkRestoreMutation.isPending}
icon={<RotateCcw className="w-4 h-4" />}
>
{t('trash.bulkRestore', 'Ausgewählte wiederherstellen')}
{selected.size > 0 ? ` (${selected.size})` : ''}
</Button>
</div>
<div className="mb-4 max-w-xs">
<Select
label={t('trash.filterType', 'Entity-Typ')}
value={entityType}
onChange={(e) => handleFilterChange(e.target.value)}
options={entityTypeOptions}
aria-label={t('trash.filterType', 'Entity-Typ')}
/>
</div>
{isLoading ? (
<div className="space-y-3">
<Skeleton className="h-12 w-full" />
<Skeleton className="h-12 w-full" />
<Skeleton className="h-12 w-full" />
</div>
) : items.length === 0 ? (
<Card>
<EmptyState
title={t('trash.empty', 'Papierkorb ist leer')}
icon={<Trash2 className="w-12 h-12" aria-hidden="true" strokeWidth={1.5} />}
/>
</Card>
) : (
<Card>
<div className="overflow-x-auto" role="region" aria-label={t('trash.title', 'Papierkorb')}>
<table className="min-w-full divide-y divide-secondary-200">
<thead>
<tr>
<th scope="col" className="px-4 py-3 w-12">
<input
type="checkbox"
checked={selected.size === items.length && items.length > 0}
onChange={toggleSelectAll}
className="h-5 w-5 rounded border-secondary-300 text-primary-600 focus:ring-primary-500"
aria-label={t('trash.selectAll', 'Alle auswählen')}
/>
</th>
<th scope="col" className="px-6 py-3 text-left text-xs font-semibold text-secondary-600 uppercase tracking-wider">
{t('trash.entityType', 'Typ')}
</th>
<th scope="col" className="px-6 py-3 text-left text-xs font-semibold text-secondary-600 uppercase tracking-wider">
{t('trash.name', 'Name')}
</th>
<th scope="col" className="px-6 py-3 text-left text-xs font-semibold text-secondary-600 uppercase tracking-wider">
{t('trash.deletedAt', 'Gelöscht am')}
</th>
<th scope="col" className="px-6 py-3 text-right text-xs font-semibold text-secondary-600 uppercase tracking-wider">
{t('trash.actions', 'Aktionen')}
</th>
</tr>
</thead>
<tbody className="divide-y divide-secondary-100">
{items.map((item) => {
const isSelected = selected.has(item.history_id);
return (
<tr key={item.history_id} className="hover:bg-secondary-50 motion-safe:transition-colors">
<td className="px-4 py-4">
<input
type="checkbox"
checked={isSelected}
onChange={() => toggleSelect(item.history_id)}
className="h-5 w-5 rounded border-secondary-300 text-primary-600 focus:ring-primary-500"
aria-label={t('trash.selectItem', 'Eintrag auswählen')}
/>
</td>
<td className="px-6 py-4 text-sm">
<Badge variant="secondary">{t(`trash.types.${item.entity_type}`)}</Badge>
</td>
<td className="px-6 py-4 text-sm font-medium text-secondary-900">
{getDisplayName(item)}
</td>
<td className="px-6 py-4 text-sm text-secondary-500">
{item.deleted_at ? formatDateShort(item.deleted_at) || '—' : '—'}
</td>
<td className="px-6 py-4 text-right">
<Button
variant="secondary"
size="sm"
onClick={() => handleSingleRestore(item.history_id)}
isLoading={restoreMutation.isPending}
icon={<RotateCcw className="w-3.5 h-3.5" />}
>
{t('trash.restore', 'Wiederherstellen')}
</Button>
</td>
</tr>
);
})}
</tbody>
</table>
</div>
<Pagination
currentPage={page}
totalPages={totalPages}
total={total}
pageSize={PAGE_SIZE}
onPageChange={handlePageChange}
/>
</Card>
)}
</div>
);
}