feat(D): Phase D — Undo/Restore komplett implementiert
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:
Agent Zero
2026-08-13 23:08:29 +02:00
parent 29410f19d3
commit a4d0f0c35d
22 changed files with 2175 additions and 91 deletions
+152
View File
@@ -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>
);
}
+118
View File
@@ -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 };
}