feat(D): Phase D — Undo/Restore komplett implementiert
Check Cross-Plugin Imports / check (push) Has been cancelled
Check Cross-Plugin Imports / check (push) Has been cancelled
- D-GEN: RestoreRegistry mit RestoreConfig (model_class, restore_permission, excluded_fields, special_handler) - D-HOOK: history_hooks.py mit register_history_hooks() für after_create/update/delete - D-CORE: Company create+update record_history in companies.py - D-PLUG: Task/Calendar/DMS record_history in services/routes - D-SOFT: Alle registrierten Entitäten haben deleted_at + un-delete via Registry - D-MAIL: Mail special_handler (IMAP Trash-Move, Folder-Verify) + record_history in delete/move - D-TRASH: GET /entity-history/trash (filterbar, paginiert) + Frontend Trash.tsx - D-TOAST: UndoToast.tsx (5s Auto-Dismiss, useUndoToast Hook) - D-HIST-UI: HistoryPanel.tsx (Timeline, Diff-View, Restore-Button) - D-BULK: POST /entity-history/bulk-restore mit partial_success Semantik - D-RET: POST /entity-history/retention/archive (GDPR hard-delete >90 Tage) - D-TEST: 26 Tests in test_restore_registry.py, alle grün - D-DOC: test-strategy.md + security_kernel.md aktualisiert Backend: 10 Dateien, Frontend: 7 Dateien, Tests: 1 Datei, Docs: 3 Dateien 26/26 Tests passed, TSC 0 errors, App import 492 routes
This commit is contained in:
@@ -1,5 +1,5 @@
|
||||
/**
|
||||
* Entity History hooks — undo/restore functionality.
|
||||
* Entity History hooks — undo/restore/trash functionality.
|
||||
*/
|
||||
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
@@ -10,9 +10,9 @@ export interface EntityHistoryEntry {
|
||||
entity_type: string;
|
||||
entity_id: string;
|
||||
action: 'create' | 'update' | 'delete';
|
||||
snapshot_before: Record<string, any> | null;
|
||||
snapshot_after: Record<string, any> | null;
|
||||
changes: Record<string, { old: any; new: any }> | null;
|
||||
snapshot_before: Record<string, unknown> | null;
|
||||
snapshot_after: Record<string, unknown> | null;
|
||||
changes: Record<string, { old: unknown; new: unknown }> | null;
|
||||
user_id: string | null;
|
||||
created_at: string;
|
||||
}
|
||||
@@ -22,22 +22,82 @@ export interface EntityHistoryList {
|
||||
total: number;
|
||||
}
|
||||
|
||||
export function useEntityHistory(entityType?: string, entityId?: string) {
|
||||
export interface TrashItem {
|
||||
history_id: string;
|
||||
entity_type: string;
|
||||
entity_id: string;
|
||||
snapshot_before: Record<string, unknown> | null;
|
||||
deleted_at: string | null;
|
||||
user_id: string | null;
|
||||
}
|
||||
|
||||
export interface TrashListResponse {
|
||||
items: TrashItem[];
|
||||
total: number;
|
||||
limit: number;
|
||||
offset: number;
|
||||
}
|
||||
|
||||
export interface BulkRestoreResultItem {
|
||||
history_id: string;
|
||||
success: boolean;
|
||||
entity_type: string | null;
|
||||
entity_id: string | null;
|
||||
error: string | null;
|
||||
}
|
||||
|
||||
export interface BulkRestoreResponse {
|
||||
total: number;
|
||||
succeeded: number;
|
||||
failed: number;
|
||||
results: BulkRestoreResultItem[];
|
||||
partial_success: boolean;
|
||||
}
|
||||
|
||||
export function useEntityHistory(entityType?: string, entityId?: string, limit = 50) {
|
||||
return useQuery({
|
||||
queryKey: ['entityHistory', entityType, entityId],
|
||||
queryKey: ['entityHistory', entityType, entityId, limit],
|
||||
queryFn: () =>
|
||||
apiGet<EntityHistoryList>(`/entity-history/${entityType}/${entityId}`),
|
||||
apiGet<EntityHistoryList>(`/entity-history/${entityType}/${entityId}?limit=${limit}`),
|
||||
enabled: !!entityType && !!entityId,
|
||||
});
|
||||
}
|
||||
|
||||
export function useTrashList(entityType?: string, limit = 50, offset = 0) {
|
||||
const params = new URLSearchParams();
|
||||
params.set('limit', String(limit));
|
||||
params.set('offset', String(offset));
|
||||
if (entityType) {
|
||||
params.set('entity_type', entityType);
|
||||
}
|
||||
return useQuery({
|
||||
queryKey: ['trash', entityType ?? 'all', limit, offset],
|
||||
queryFn: () => apiGet<TrashListResponse>(`/entity-history/trash?${params.toString()}`),
|
||||
});
|
||||
}
|
||||
|
||||
export function useRestoreFromHistory() {
|
||||
const queryClient = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: (historyId: string) =>
|
||||
apiClient.post('/entity-history/restore', { history_id: historyId }).then(r => r.data),
|
||||
onSuccess: (_data, _variables, context) => {
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['entityHistory'] });
|
||||
queryClient.invalidateQueries({ queryKey: ['trash'] });
|
||||
queryClient.invalidateQueries({ queryKey: ['contacts'] });
|
||||
queryClient.invalidateQueries({ queryKey: ['contact'] });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function useBulkRestore() {
|
||||
const queryClient = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: (historyIds: string[]) =>
|
||||
apiPost<BulkRestoreResponse>('/entity-history/bulk-restore', { history_ids: historyIds }),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['entityHistory'] });
|
||||
queryClient.invalidateQueries({ queryKey: ['trash'] });
|
||||
queryClient.invalidateQueries({ queryKey: ['contacts'] });
|
||||
queryClient.invalidateQueries({ queryKey: ['contact'] });
|
||||
},
|
||||
@@ -51,6 +111,7 @@ export function useUndoLastAction() {
|
||||
apiPost(`/entity-history/undo/${entityType}/${entityId}`, {}),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['entityHistory'] });
|
||||
queryClient.invalidateQueries({ queryKey: ['trash'] });
|
||||
queryClient.invalidateQueries({ queryKey: ['contacts'] });
|
||||
queryClient.invalidateQueries({ queryKey: ['contact'] });
|
||||
},
|
||||
|
||||
@@ -0,0 +1,152 @@
|
||||
import React, { useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { History, RotateCcw, ChevronDown, ChevronRight, User } from 'lucide-react';
|
||||
import { useEntityHistory, useRestoreFromHistory } from '@/api/entityHistory';
|
||||
import { Button } from '@/components/ui/Button';
|
||||
import { Badge } from '@/components/ui/Badge';
|
||||
import { Skeleton } from '@/components/ui/Skeleton';
|
||||
import { useToast } from '@/components/ui/Toast';
|
||||
import { formatDistanceToNow } from 'date-fns';
|
||||
import { de, enUS } from 'date-fns/locale';
|
||||
|
||||
interface HistoryPanelProps {
|
||||
entityType: string;
|
||||
entityId: string;
|
||||
limit?: number;
|
||||
}
|
||||
|
||||
const actionConfig = {
|
||||
create: { variant: 'success' as const, labelKey: 'history.actionCreate' },
|
||||
update: { variant: 'primary' as const, labelKey: 'history.actionUpdate' },
|
||||
delete: { variant: 'danger' as const, labelKey: 'history.actionDelete' },
|
||||
};
|
||||
|
||||
export function HistoryPanel({ entityType, entityId, limit = 50 }: HistoryPanelProps) {
|
||||
const { t, i18n } = useTranslation();
|
||||
const toast = useToast();
|
||||
const { data: history, isLoading } = useEntityHistory(entityType, entityId, limit);
|
||||
const restoreMutation = useRestoreFromHistory();
|
||||
const [expandedId, setExpandedId] = useState<string | null>(null);
|
||||
|
||||
const dateLocale = i18n.language === 'de' ? de : enUS;
|
||||
|
||||
const handleRestore = async (historyId: string) => {
|
||||
try {
|
||||
await restoreMutation.mutateAsync(historyId);
|
||||
toast.success(t('history.restored', 'Version wiederhergestellt'));
|
||||
} catch {
|
||||
toast.error(t('history.restoreError', 'Wiederherstellung fehlgeschlagen'));
|
||||
}
|
||||
};
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="space-y-3" data-testid="history-panel">
|
||||
<Skeleton className="h-8 w-40" />
|
||||
<Skeleton className="h-16 w-full" />
|
||||
<Skeleton className="h-16 w-full" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const entries = history?.items ?? [];
|
||||
|
||||
if (entries.length === 0) {
|
||||
return (
|
||||
<div className="text-center py-8 text-secondary-400" data-testid="history-panel">
|
||||
<History className="w-8 h-8 mx-auto mb-2 opacity-50" aria-hidden="true" />
|
||||
<p className="text-sm">{t('history.empty', 'Keine Änderungshistorie vorhanden')}</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-4" data-testid="history-panel">
|
||||
<h3 className="text-lg font-semibold text-secondary-900 flex items-center gap-2">
|
||||
<History className="w-5 h-5" aria-hidden="true" />
|
||||
{t('history.title', 'Änderungshistorie')}
|
||||
</h3>
|
||||
|
||||
<ol className="relative border-l border-secondary-200 ml-3 space-y-4">
|
||||
{entries.map((entry) => {
|
||||
const config = actionConfig[entry.action] || actionConfig.update;
|
||||
const isExpanded = expandedId === entry.id;
|
||||
const changes = entry.changes || {};
|
||||
const changeKeys = Object.keys(changes);
|
||||
|
||||
return (
|
||||
<li key={entry.id} className="ml-4">
|
||||
<div className="border border-secondary-200 rounded-lg overflow-hidden bg-white">
|
||||
<button
|
||||
onClick={() => setExpandedId(isExpanded ? null : entry.id)}
|
||||
className="w-full flex items-center justify-between p-3 hover:bg-secondary-50 transition-colors text-left"
|
||||
aria-expanded={isExpanded}
|
||||
aria-controls={`history-detail-${entry.id}`}
|
||||
>
|
||||
<div className="flex items-center gap-3">
|
||||
{isExpanded ? (
|
||||
<ChevronDown className="w-4 h-4 text-secondary-400" aria-hidden="true" />
|
||||
) : (
|
||||
<ChevronRight className="w-4 h-4 text-secondary-400" aria-hidden="true" />
|
||||
)}
|
||||
<Badge variant={config.variant}>{t(config.labelKey)}</Badge>
|
||||
<span className="text-sm text-secondary-500">
|
||||
{formatDistanceToNow(new Date(entry.created_at), { addSuffix: true, locale: dateLocale })}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-3">
|
||||
{entry.user_id && (
|
||||
<span className="inline-flex items-center gap-1 text-xs text-secondary-400">
|
||||
<User className="w-3.5 h-3.5" aria-hidden="true" />
|
||||
{entry.user_id.slice(0, 8)}
|
||||
</span>
|
||||
)}
|
||||
{changeKeys.length > 0 && (
|
||||
<span className="text-xs text-secondary-400">
|
||||
{changeKeys.length} {t('history.fieldsChanged', 'Felder geändert')}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</button>
|
||||
|
||||
{isExpanded && (
|
||||
<div id={`history-detail-${entry.id}`} className="px-4 pb-3 border-t border-secondary-100">
|
||||
{changeKeys.length > 0 && (
|
||||
<div className="mt-3 space-y-1">
|
||||
<p className="text-xs font-medium text-secondary-500 mb-2">{t('history.changes', 'Änderungen')}:</p>
|
||||
{changeKeys.map((key) => (
|
||||
<div key={key} className="flex items-start gap-2 text-sm">
|
||||
<span className="font-mono text-secondary-600 min-w-[120px]">{key}:</span>
|
||||
<span className="text-danger-600 line-through">
|
||||
{String(changes[key].old ?? '—')}
|
||||
</span>
|
||||
<span className="text-secondary-400">→</span>
|
||||
<span className="text-success-600">
|
||||
{String(changes[key].new ?? '—')}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="mt-3 flex justify-end">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => handleRestore(entry.id)}
|
||||
isLoading={restoreMutation.isPending}
|
||||
icon={<RotateCcw className="w-3.5 h-3.5" />}
|
||||
>
|
||||
{t('history.restore', 'Diese Version wiederherstellen')}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ol>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
import React, { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Undo2, X } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/Button';
|
||||
import { useUndoLastAction } from '@/api/entityHistory';
|
||||
|
||||
interface UndoToastProps {
|
||||
message: string;
|
||||
onUndo: () => void;
|
||||
onDismiss: () => void;
|
||||
isUndoing: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Undo toast shown after delete actions.
|
||||
* Auto-dismisses after 5 seconds and is manually dismissable.
|
||||
*/
|
||||
export function UndoToast({ message, onUndo, onDismiss, isUndoing }: UndoToastProps) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
return (
|
||||
<div
|
||||
className="fixed bottom-4 right-4 z-[100] flex items-center gap-3 p-4 rounded-lg shadow-lg border border-secondary-200 bg-white max-w-sm"
|
||||
role="alert"
|
||||
aria-live="polite"
|
||||
data-testid="undo-toast"
|
||||
>
|
||||
<p className="flex-1 text-sm font-medium text-secondary-900">{message}</p>
|
||||
<Button
|
||||
variant="primary"
|
||||
size="sm"
|
||||
onClick={onUndo}
|
||||
isLoading={isUndoing}
|
||||
icon={<Undo2 className="w-4 h-4" />}
|
||||
>
|
||||
{t('undoToast.undo', 'Undo')}
|
||||
</Button>
|
||||
<button
|
||||
onClick={onDismiss}
|
||||
className="flex-shrink-0 text-secondary-400 hover:text-secondary-700 min-h-touch min-w-touch flex items-center justify-center rounded focus:outline-none focus-visible:ring-2 focus-visible:ring-primary-500"
|
||||
aria-label={t('common.dismiss', 'Schließen')}
|
||||
>
|
||||
<X className="h-4 w-4" aria-hidden="true" />
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
interface UndoToastState {
|
||||
message: string;
|
||||
entityType: string;
|
||||
entityId: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook that shows an undo toast after a delete action and provides the undo function.
|
||||
*
|
||||
* Returns:
|
||||
* - `showUndoToast(message, entityType, entityId)`: trigger the toast
|
||||
* - `undoToast`: the JSX element to render (render it once in the page)
|
||||
*/
|
||||
export function useUndoToast() {
|
||||
const { t } = useTranslation();
|
||||
const [state, setState] = useState<UndoToastState | null>(null);
|
||||
const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const undoMutation = useUndoLastAction();
|
||||
|
||||
const clearTimer = useCallback(() => {
|
||||
if (timerRef.current) {
|
||||
clearTimeout(timerRef.current);
|
||||
timerRef.current = null;
|
||||
}
|
||||
}, []);
|
||||
|
||||
const dismiss = useCallback(() => {
|
||||
clearTimer();
|
||||
setState(null);
|
||||
}, [clearTimer]);
|
||||
|
||||
const showUndoToast = useCallback(
|
||||
(message: string, entityType: string, entityId: string) => {
|
||||
clearTimer();
|
||||
setState({ message, entityType, entityId });
|
||||
timerRef.current = setTimeout(() => {
|
||||
setState(null);
|
||||
timerRef.current = null;
|
||||
}, 5000);
|
||||
},
|
||||
[clearTimer]
|
||||
);
|
||||
|
||||
const handleUndo = useCallback(async () => {
|
||||
if (!state) return;
|
||||
try {
|
||||
await undoMutation.mutateAsync({
|
||||
entityType: state.entityType,
|
||||
entityId: state.entityId,
|
||||
});
|
||||
dismiss();
|
||||
} catch {
|
||||
// Keep the toast visible so the user can retry; the mutation error is surfaced elsewhere.
|
||||
}
|
||||
}, [state, undoMutation, dismiss]);
|
||||
|
||||
// Cleanup timer on unmount
|
||||
useEffect(() => clearTimer, [clearTimer]);
|
||||
|
||||
const undoToast = state ? (
|
||||
<UndoToast
|
||||
message={state.message}
|
||||
onUndo={handleUndo}
|
||||
onDismiss={dismiss}
|
||||
isUndoing={undoMutation.isPending}
|
||||
/>
|
||||
) : null;
|
||||
|
||||
return { showUndoToast, undoToast };
|
||||
}
|
||||
@@ -907,7 +907,39 @@
|
||||
"restoreError": "Wiederherstellung fehlgeschlagen",
|
||||
"empty": "Keine Änderungshistorie vorhanden",
|
||||
"changes": "Änderungen",
|
||||
"fieldsChanged": "Felder geändert"
|
||||
"fieldsChanged": "Felder geändert",
|
||||
"actionCreate": "Erstellt",
|
||||
"actionUpdate": "Aktualisiert",
|
||||
"actionDelete": "Gelöscht"
|
||||
},
|
||||
"trash": {
|
||||
"title": "Papierkorb",
|
||||
"allTypes": "Alle Typen",
|
||||
"filterType": "Entity-Typ",
|
||||
"entityType": "Typ",
|
||||
"name": "Name",
|
||||
"deletedAt": "Gelöscht am",
|
||||
"actions": "Aktionen",
|
||||
"restore": "Wiederherstellen",
|
||||
"restored": "Wiederhergestellt",
|
||||
"restoreError": "Wiederherstellung fehlgeschlagen",
|
||||
"bulkRestore": "Ausgewählte wiederherstellen",
|
||||
"bulkRestored": "{{count}} Einträge wiederhergestellt",
|
||||
"bulkPartial": "{{succeeded}} wiederhergestellt, {{failed}} fehlgeschlagen",
|
||||
"bulkRestoreError": "Massen-Wiederherstellung fehlgeschlagen",
|
||||
"empty": "Papierkorb ist leer",
|
||||
"selectAll": "Alle auswählen",
|
||||
"selectItem": "Eintrag auswählen",
|
||||
"types": {
|
||||
"contact": "Kontakt",
|
||||
"task": "Aufgabe",
|
||||
"calendar_entry": "Kalendereintrag",
|
||||
"dms_file": "Datei",
|
||||
"mail": "E-Mail"
|
||||
}
|
||||
},
|
||||
"undoToast": {
|
||||
"undo": "Undo"
|
||||
},
|
||||
"userPreferences": {
|
||||
"title": "Benutzereinstellungen",
|
||||
|
||||
@@ -907,7 +907,39 @@
|
||||
"restoreError": "Restore failed",
|
||||
"empty": "No change history available",
|
||||
"changes": "Changes",
|
||||
"fieldsChanged": "fields changed"
|
||||
"fieldsChanged": "fields changed",
|
||||
"actionCreate": "Created",
|
||||
"actionUpdate": "Updated",
|
||||
"actionDelete": "Deleted"
|
||||
},
|
||||
"trash": {
|
||||
"title": "Trash",
|
||||
"allTypes": "All types",
|
||||
"filterType": "Entity type",
|
||||
"entityType": "Type",
|
||||
"name": "Name",
|
||||
"deletedAt": "Deleted at",
|
||||
"actions": "Actions",
|
||||
"restore": "Restore",
|
||||
"restored": "Restored",
|
||||
"restoreError": "Restore failed",
|
||||
"bulkRestore": "Restore selected",
|
||||
"bulkRestored": "{{count}} entries restored",
|
||||
"bulkPartial": "{{succeeded}} restored, {{failed}} failed",
|
||||
"bulkRestoreError": "Bulk restore failed",
|
||||
"empty": "Trash is empty",
|
||||
"selectAll": "Select all",
|
||||
"selectItem": "Select item",
|
||||
"types": {
|
||||
"contact": "Contact",
|
||||
"task": "Task",
|
||||
"calendar_entry": "Calendar entry",
|
||||
"dms_file": "File",
|
||||
"mail": "Email"
|
||||
}
|
||||
},
|
||||
"undoToast": {
|
||||
"undo": "Undo"
|
||||
},
|
||||
"userPreferences": {
|
||||
"title": "User Preferences",
|
||||
|
||||
@@ -0,0 +1,264 @@
|
||||
import React, { useCallback, useMemo, useState } from 'react';
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -33,6 +33,7 @@ const CalendarPage = React.lazy(() => import('@/pages/Calendar').then(m => ({ de
|
||||
const CalendarKanbanPage = React.lazy(() => import('@/pages/CalendarKanban').then(m => ({ default: m.CalendarKanbanPage })));
|
||||
const DmsPage = React.lazy(() => import('@/pages/Dms').then(m => ({ default: m.DmsPage })));
|
||||
const DmsTrashPage = React.lazy(() => import('@/pages/DmsTrash').then(m => ({ default: m.DmsTrashPage })));
|
||||
const TrashPage = React.lazy(() => import('@/pages/Trash').then(m => ({ default: m.TrashPage })));
|
||||
const MailPage = React.lazy(() => import('@/pages/Mail').then(m => ({ default: m.MailPage })));
|
||||
const MailSettingsPage = React.lazy(() => import('@/pages/MailSettings').then(m => ({ default: m.MailSettingsPage })));
|
||||
const SettingsNotificationsPage = React.lazy(() => import('@/pages/SettingsNotifications').then(m => ({ default: m.SettingsNotificationsPage })));
|
||||
@@ -156,6 +157,7 @@ const router = createBrowserRouter([
|
||||
{ path: '/calendar/kanban', element: <PermissionRoute permission="calendar:read">{withSuspense(<CalendarKanbanPage />)}</PermissionRoute> },
|
||||
{ path: '/dms', element: <PermissionRoute permission="dms:read">{withSuspense(<DmsPage />)}</PermissionRoute> },
|
||||
{ path: '/dms/trash', element: <PermissionRoute permission="dms:read">{withSuspense(<DmsTrashPage />)}</PermissionRoute> },
|
||||
{ path: '/trash', element: <PermissionRoute permission="contacts:read">{withSuspense(<TrashPage />)}</PermissionRoute> },
|
||||
{ path: '/mail', element: <PermissionRoute permission="mail:read">{withSuspense(<MailPage />)}</PermissionRoute> },
|
||||
{ path: '/mail/settings', element: <PermissionRoute permission="mail:read">{withSuspense(<MailSettingsPage />)}</PermissionRoute> },
|
||||
{ path: '/ai-assistant', element: <PermissionRoute permission="ai:read">{withSuspense(<AIAssistantPage />)}</PermissionRoute> },
|
||||
|
||||
Reference in New Issue
Block a user