Files
leocrm/frontend/src/components/import-export/ImportWizard.tsx
T
Agent Zero a3a5a10514 Phase 1: Workflows UI, Dedup/Merge UI, Import/Export UI, Print/PDF
- Workflows UI: full page with definitions/instances tabs, step editor, instance detail with approve/reject
- Dedup/Merge UI: duplicate detection, side-by-side comparison, field-level merge dialog, merge history
- Import/Export UI: import wizard (dry-run preview), export panel (CSV/XLSX), backend export route added
- Print/PDF: PrintButton component, print.css, integrated in Contacts/Calendar/Reports/ContactDetail
- Backend: GET /api/v1/export endpoint, export_companies_csv() service function
- Routes: /workflows, /contacts/dedup, /import-export registered
- Menu items: Workflows, Import/Export, Duplikate added to automation plugin manifest
- IMPLEMENTATION_PLAN.md: audit-corrected plan for all 14 remaining features
2026-07-26 02:35:44 +02:00

594 lines
25 KiB
TypeScript

import React, { useCallback, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import {
AlertCircle,
CheckCircle,
FileText,
Loader2,
Upload,
RotateCcw,
ArrowLeft,
Eye,
Play,
} from 'lucide-react';
import clsx from 'clsx';
import { Card } from '@/components/ui/Card';
import { Button } from '@/components/ui/Button';
import { Select } from '@/components/ui/Select';
import { Badge } from '@/components/ui/Badge';
import { useToast } from '@/components/ui/Toast';
import { importCsv, type ImportResult } from '@/api/importExport';
// ─── Constants ──────────────────────────────────────────────────────────────
const MAX_FILE_SIZE = 10 * 1024 * 1024; // 10 MB
const ACCEPTED_EXTENSIONS = ['.csv'];
const ENTITY_OPTIONS = [
{ value: 'contacts', label: 'Kontakte' },
{ value: 'companies', label: 'Firmen' },
];
type WizardStep = 'upload' | 'preview' | 'review' | 'result';
// ─── Component ──────────────────────────────────────────────────────────────
export function ImportWizard() {
const { t } = useTranslation();
const toast = useToast();
const [step, setStep] = useState<WizardStep>('upload');
const [file, setFile] = useState<File | null>(null);
const [entityType, setEntityType] = useState<string>('contacts');
const [previewResult, setPreviewResult] = useState<ImportResult | null>(null);
const [importResult, setImportResult] = useState<ImportResult | null>(null);
const [previewConfirmed, setPreviewConfirmed] = useState(false);
const [isDragOver, setIsDragOver] = useState(false);
const [isLoadingPreview, setIsLoadingPreview] = useState(false);
const [isLoadingImport, setIsLoadingImport] = useState(false);
const [fileError, setFileError] = useState<string | null>(null);
const inputRef = useRef<HTMLInputElement>(null);
// ─── File validation ────────────────────────────────────────────────────
const validateFile = useCallback((f: File): string | null => {
const ext = f.name.toLowerCase().substring(f.name.lastIndexOf('.'));
if (!ACCEPTED_EXTENSIONS.includes(ext)) {
return t('importExport.onlyCsvAllowed', 'Nur CSV-Dateien sind erlaubt');
}
if (f.size > MAX_FILE_SIZE) {
return t('importExport.fileTooLarge', 'Datei ist größer als 10 MB');
}
return null;
}, [t]);
const handleFileSelect = useCallback((f: File | null) => {
if (!f) return;
const error = validateFile(f);
if (error) {
setFileError(error);
setFile(null);
return;
}
setFileError(null);
setFile(f);
}, [validateFile]);
const handleDrop = useCallback((e: React.DragEvent) => {
e.preventDefault();
setIsDragOver(false);
const droppedFile = e.dataTransfer.files?.[0];
if (droppedFile) handleFileSelect(droppedFile);
}, [handleFileSelect]);
const handleDragOver = useCallback((e: React.DragEvent) => {
e.preventDefault();
setIsDragOver(true);
}, []);
const handleDragLeave = useCallback((e: React.DragEvent) => {
e.preventDefault();
setIsDragOver(false);
}, []);
const handleFileInputChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
const selected = e.target.files?.[0] ?? null;
handleFileSelect(selected);
}, [handleFileSelect]);
// ─── Preview ────────────────────────────────────────────────────────────
const handlePreview = async () => {
if (!file) return;
setIsLoadingPreview(true);
try {
const result = await importCsv(file, entityType, true);
setPreviewResult(result);
setStep('preview');
} catch (err: any) {
toast.error(err?.message || t('importExport.previewFailed', 'Vorschau fehlgeschlagen'));
} finally {
setIsLoadingPreview(false);
}
};
// ─── Import ─────────────────────────────────────────────────────────────
const handleImport = async () => {
if (!file) return;
setIsLoadingImport(true);
try {
const result = await importCsv(file, entityType, false);
setImportResult(result);
setStep('result');
toast.success(t('importExport.importSuccess', 'Import erfolgreich abgeschlossen'));
} catch (err: any) {
setImportResult({
errors: [err?.message || t('importExport.importFailed', 'Import fehlgeschlagen')],
});
setStep('result');
} finally {
setIsLoadingImport(false);
}
};
// ─── Reset ──────────────────────────────────────────────────────────────
const handleReset = () => {
setStep('upload');
setFile(null);
setPreviewResult(null);
setImportResult(null);
setPreviewConfirmed(false);
setFileError(null);
if (inputRef.current) inputRef.current.value = '';
};
const handleBack = () => {
if (step === 'preview') setStep('upload');
else if (step === 'review') setStep('preview');
};
// ─── Step indicator ─────────────────────────────────────────────────────
const steps: { key: WizardStep; label: string }[] = [
{ key: 'upload', label: t('importExport.stepUpload', 'Datei hochladen') },
{ key: 'preview', label: t('importExport.stepPreview', 'Vorschau') },
{ key: 'review', label: t('importExport.stepReview', 'Überprüfung') },
{ key: 'result', label: t('importExport.stepResult', 'Ergebnis') },
];
const currentStepIndex = steps.findIndex((s) => s.key === step);
// ─── Render ─────────────────────────────────────────────────────────────
return (
<div className="space-y-6">
{/* Step indicator */}
<div className="flex items-center justify-between max-w-2xl">
{steps.map((s, idx) => (
<React.Fragment key={s.key}>
<div className="flex items-center gap-2">
<span
className={clsx(
'flex items-center justify-center w-8 h-8 rounded-full text-sm font-medium transition-colors',
idx <= currentStepIndex
? 'bg-primary-600 text-white'
: 'bg-secondary-200 text-secondary-500'
)}
>
{idx < currentStepIndex ? (
<CheckCircle className="w-4 h-4" />
) : (
idx + 1
)}
</span>
<span
className={clsx(
'text-sm font-medium hidden sm:inline',
idx <= currentStepIndex ? 'text-secondary-900' : 'text-secondary-400'
)}
>
{s.label}
</span>
</div>
{idx < steps.length - 1 && (
<div
className={clsx(
'flex-1 h-0.5 mx-2 transition-colors',
idx < currentStepIndex ? 'bg-primary-600' : 'bg-secondary-200'
)}
/>
)}
</React.Fragment>
))}
</div>
{/* Step: Upload */}
{step === 'upload' && (
<Card
title={t('importExport.uploadTitle', 'Datei hochladen')}
description={t('importExport.uploadDescription', 'Wählen Sie eine CSV-Datei und den Entitätstyp für den Import')}
>
<div className="space-y-4">
{/* Entity type */}
<Select
label={t('importExport.entityType', 'Entitätstyp')}
options={ENTITY_OPTIONS}
value={entityType}
onChange={(e) => setEntityType(e.target.value)}
required
/>
{/* Drag & drop zone */}
<div
onDrop={handleDrop}
onDragOver={handleDragOver}
onDragLeave={handleDragLeave}
onClick={() => inputRef.current?.click()}
className={clsx(
'border-2 border-dashed rounded-lg p-8 text-center cursor-pointer transition-colors',
isDragOver
? 'border-primary-500 bg-primary-50'
: 'border-secondary-300 hover:border-secondary-400 bg-secondary-50'
)}
>
<input
ref={inputRef}
type="file"
accept=".csv"
onChange={handleFileInputChange}
className="hidden"
/>
{file ? (
<div className="flex flex-col items-center gap-2">
<FileText className="w-10 h-10 text-primary-600" />
<p className="text-sm font-medium text-secondary-900">{file.name}</p>
<p className="text-xs text-secondary-500">
{(file.size / 1024).toFixed(1)} KB
</p>
</div>
) : (
<div className="flex flex-col items-center gap-2">
<Upload className="w-10 h-10 text-secondary-400" />
<p className="text-sm font-medium text-secondary-700">
{t('importExport.dropFileHere', 'CSV-Datei hierher ziehen oder klicken zum Auswählen')}
</p>
<p className="text-xs text-secondary-500">
{t('importExport.fileConstraints', 'Max. 10 MB, nur .csv')}
</p>
</div>
)}
</div>
{fileError && (
<div className="flex items-center gap-2 text-sm text-danger-600">
<AlertCircle className="w-4 h-4 flex-shrink-0" />
<span>{fileError}</span>
</div>
)}
{/* Action */}
<div className="flex justify-end">
<Button
onClick={handlePreview}
disabled={!file || isLoadingPreview}
isLoading={isLoadingPreview}
icon={!isLoadingPreview ? <Eye className="w-4 h-4" /> : undefined}
>
{t('importExport.preview', 'Vorschau')}
</Button>
</div>
</div>
</Card>
)}
{/* Step: Preview */}
{step === 'preview' && previewResult && (
<Card
title={t('importExport.previewTitle', 'Vorschau der Daten')}
description={t('importExport.previewDescription', 'Überprüfen Sie das Ergebnis des Dry-Run-Imports')}
actions={
<Button variant="ghost" size="sm" onClick={handleBack} icon={<ArrowLeft className="w-4 h-4" />}>
{t('common.back', 'Zurück')}
</Button>
}
>
<div className="space-y-4">
{/* Summary stats */}
<div className="grid grid-cols-2 sm:grid-cols-3 gap-4">
<StatBox
label={t('importExport.totalRows', 'Gesamtzeilen')}
value={previewResult.total ?? 0}
icon={<FileText className="w-5 h-5 text-secondary-400" />}
/>
<StatBox
label={t('importExport.created', 'Neu')}
value={previewResult.created ?? 0}
icon={<CheckCircle className="w-5 h-5 text-success-500" />}
/>
<StatBox
label={t('importExport.updated', 'Aktualisiert')}
value={previewResult.updated ?? 0}
icon={<RotateCcw className="w-5 h-5 text-accent-500" />}
/>
</div>
{/* Errors */}
{previewResult.errors && previewResult.errors.length > 0 && (
<div className="space-y-2">
<div className="flex items-center gap-2">
<AlertCircle className="w-5 h-5 text-danger-500" />
<h4 className="text-sm font-semibold text-danger-700">
{t('importExport.errors', 'Fehler')} ({previewResult.errors.length})
</h4>
</div>
<ul className="space-y-1 max-h-48 overflow-y-auto">
{previewResult.errors.map((err, idx) => (
<li key={idx} className="text-sm text-danger-600 bg-danger-50 rounded px-3 py-1.5">
{err}
</li>
))}
</ul>
</div>
)}
{/* Warnings */}
{previewResult.warnings && previewResult.warnings.length > 0 && (
<div className="space-y-2">
<div className="flex items-center gap-2">
<AlertCircle className="w-5 h-5 text-warning-500" />
<h4 className="text-sm font-semibold text-warning-700">
{t('importExport.warnings', 'Warnungen')} ({previewResult.warnings.length})
</h4>
</div>
<ul className="space-y-1 max-h-48 overflow-y-auto">
{previewResult.warnings.map((warn, idx) => (
<li key={idx} className="text-sm text-warning-700 bg-warning-50 rounded px-3 py-1.5">
{warn}
</li>
))}
</ul>
</div>
)}
{/* Preview rows */}
{previewResult.rows && previewResult.rows.length > 0 && (
<div className="space-y-2">
<h4 className="text-sm font-semibold text-secondary-700">
{t('importExport.previewRows', 'Vorschau der ersten Zeilen')}
</h4>
<div className="overflow-x-auto border border-secondary-200 rounded-lg">
<table className="min-w-full divide-y divide-secondary-200">
<thead className="bg-secondary-50">
<tr>
{Object.keys(previewResult.rows[0]).slice(0, 6).map((key) => (
<th key={key} className="px-3 py-2 text-left text-xs font-medium text-secondary-500 uppercase tracking-wider">
{key}
</th>
))}
</tr>
</thead>
<tbody className="bg-white divide-y divide-secondary-200">
{previewResult.rows.slice(0, 5).map((row, idx) => (
<tr key={idx}>
{Object.values(row).slice(0, 6).map((val, vidx) => (
<td key={vidx} className="px-3 py-2 text-sm text-secondary-900 whitespace-nowrap">
{String(val ?? '')}
</td>
))}
</tr>
))}
</tbody>
</table>
</div>
</div>
)}
{/* Action */}
<div className="flex justify-end">
<Button onClick={() => setStep('review')} icon={<CheckCircle className="w-4 h-4" />}>
{t('importExport.continue', 'Weiter')}
</Button>
</div>
</div>
</Card>
)}
{/* Step: Review */}
{step === 'review' && (
<Card
title={t('importExport.reviewTitle', 'Überprüfung')}
description={t('importExport.reviewDescription', 'Bestätigen Sie, dass Sie die Vorschau geprüft haben')}
actions={
<Button variant="ghost" size="sm" onClick={handleBack} icon={<ArrowLeft className="w-4 h-4" />}>
{t('common.back', 'Zurück')}
</Button>
}
>
<div className="space-y-4">
{/* Summary */}
<div className="bg-secondary-50 rounded-lg p-4 space-y-2">
<div className="flex items-center justify-between">
<span className="text-sm text-secondary-600">{t('importExport.entityType', 'Entitätstyp')}</span>
<Badge variant="primary">
{entityType === 'contacts' ? 'Kontakte' : 'Firmen'}
</Badge>
</div>
<div className="flex items-center justify-between">
<span className="text-sm text-secondary-600">{t('importExport.file', 'Datei')}</span>
<span className="text-sm font-medium text-secondary-900">{file?.name}</span>
</div>
{previewResult && (
<>
<div className="flex items-center justify-between">
<span className="text-sm text-secondary-600">{t('importExport.totalRows', 'Gesamtzeilen')}</span>
<span className="text-sm font-medium text-secondary-900">{previewResult.total ?? 0}</span>
</div>
<div className="flex items-center justify-between">
<span className="text-sm text-secondary-600">{t('importExport.created', 'Neu')}</span>
<span className="text-sm font-medium text-success-600">{previewResult.created ?? 0}</span>
</div>
<div className="flex items-center justify-between">
<span className="text-sm text-secondary-600">{t('importExport.updated', 'Aktualisiert')}</span>
<span className="text-sm font-medium text-accent-600">{previewResult.updated ?? 0}</span>
</div>
{previewResult.errors && previewResult.errors.length > 0 && (
<div className="flex items-center justify-between">
<span className="text-sm text-secondary-600">{t('importExport.errors', 'Fehler')}</span>
<Badge variant="danger">{previewResult.errors.length}</Badge>
</div>
)}
{previewResult.warnings && previewResult.warnings.length > 0 && (
<div className="flex items-center justify-between">
<span className="text-sm text-secondary-600">{t('importExport.warnings', 'Warnungen')}</span>
<Badge variant="warning">{previewResult.warnings.length}</Badge>
</div>
)}
</>
)}
</div>
{/* Confirmation checkbox */}
<label className="flex items-start gap-3 cursor-pointer">
<input
type="checkbox"
checked={previewConfirmed}
onChange={(e) => setPreviewConfirmed(e.target.checked)}
className="mt-1 w-4 h-4 rounded border-secondary-300 text-primary-600 focus:ring-primary-500"
/>
<span className="text-sm text-secondary-700">
{t('importExport.confirmPreview', 'Ich habe die Vorschau geprüft und bin mir der Folgen bewusst')}
</span>
</label>
{/* Actions */}
<div className="flex justify-between">
<Button variant="ghost" onClick={handleReset} icon={<RotateCcw className="w-4 h-4" />}>
{t('importExport.restart', 'Neu starten')}
</Button>
<Button
onClick={handleImport}
disabled={!previewConfirmed || isLoadingImport}
isLoading={isLoadingImport}
icon={!isLoadingImport ? <Play className="w-4 h-4" /> : undefined}
>
{t('importExport.executeImport', 'Import ausführen')}
</Button>
</div>
</div>
</Card>
)}
{/* Step: Result */}
{step === 'result' && importResult && (
<Card
title={t('importExport.resultTitle', 'Import-Ergebnis')}
actions={
<Button variant="ghost" size="sm" onClick={handleReset} icon={<RotateCcw className="w-4 h-4" />}>
{t('importExport.newImport', 'Neuer Import')}
</Button>
}
>
<div className="space-y-4">
{/* Success / Error indicator */}
{importResult.errors && importResult.errors.length > 0 && !importResult.created && !importResult.updated ? (
<div className="flex items-center gap-3 bg-danger-50 rounded-lg p-4">
<AlertCircle className="w-6 h-6 text-danger-600" />
<span className="text-sm font-medium text-danger-700">
{t('importExport.importFailed', 'Import fehlgeschlagen')}
</span>
</div>
) : (
<div className="flex items-center gap-3 bg-success-50 rounded-lg p-4">
<CheckCircle className="w-6 h-6 text-success-600" />
<span className="text-sm font-medium text-success-700">
{t('importExport.importSuccess', 'Import erfolgreich abgeschlossen')}
</span>
</div>
)}
{/* Stats */}
{(importResult.created !== undefined || importResult.updated !== undefined || importResult.total !== undefined) && (
<div className="grid grid-cols-2 sm:grid-cols-3 gap-4">
{importResult.total !== undefined && (
<StatBox
label={t('importExport.totalRows', 'Gesamtzeilen')}
value={importResult.total}
icon={<FileText className="w-5 h-5 text-secondary-400" />}
/>
)}
{importResult.created !== undefined && (
<StatBox
label={t('importExport.created', 'Neu')}
value={importResult.created}
icon={<CheckCircle className="w-5 h-5 text-success-500" />}
/>
)}
{importResult.updated !== undefined && (
<StatBox
label={t('importExport.updated', 'Aktualisiert')}
value={importResult.updated}
icon={<RotateCcw className="w-5 h-5 text-accent-500" />}
/>
)}
</div>
)}
{/* Errors */}
{importResult.errors && importResult.errors.length > 0 && (
<div className="space-y-2">
<div className="flex items-center gap-2">
<AlertCircle className="w-5 h-5 text-danger-500" />
<h4 className="text-sm font-semibold text-danger-700">
{t('importExport.errors', 'Fehler')} ({importResult.errors.length})
</h4>
</div>
<ul className="space-y-1 max-h-48 overflow-y-auto">
{importResult.errors.map((err, idx) => (
<li key={idx} className="text-sm text-danger-600 bg-danger-50 rounded px-3 py-1.5">
{err}
</li>
))}
</ul>
</div>
)}
{/* Warnings */}
{importResult.warnings && importResult.warnings.length > 0 && (
<div className="space-y-2">
<div className="flex items-center gap-2">
<AlertCircle className="w-5 h-5 text-warning-500" />
<h4 className="text-sm font-semibold text-warning-700">
{t('importExport.warnings', 'Warnungen')} ({importResult.warnings.length})
</h4>
</div>
<ul className="space-y-1 max-h-48 overflow-y-auto">
{importResult.warnings.map((warn, idx) => (
<li key={idx} className="text-sm text-warning-700 bg-warning-50 rounded px-3 py-1.5">
{warn}
</li>
))}
</ul>
</div>
)}
</div>
</Card>
)}
</div>
);
}
// ─── Helper sub-component ───────────────────────────────────────────────────
function StatBox({ label, value, icon }: { label: string; value: number; icon: React.ReactNode }) {
return (
<div className="bg-secondary-50 rounded-lg p-4 flex items-center gap-3">
{icon}
<div>
<p className="text-xs text-secondary-500">{label}</p>
<p className="text-lg font-semibold text-secondary-900">{value}</p>
</div>
</div>
);
}