90 lines
2.9 KiB
JavaScript
90 lines
2.9 KiB
JavaScript
// seniorendienst-frontend/src/components/CSVImport.jsx
|
|
import React, { useRef, useState } from 'react';
|
|
import { parse } from 'csv-parse/browser/esm/sync';
|
|
|
|
const CSVImport = ({ onImport }) => {
|
|
const fileInputRef = useRef(null);
|
|
const [isProcessing, setIsProcessing] = useState(false);
|
|
|
|
const handleFileUpload = async (event) => {
|
|
const file = event.target.files[0];
|
|
if (!file) return;
|
|
|
|
setIsProcessing(true);
|
|
|
|
try {
|
|
const text = await file.text();
|
|
|
|
// Führendes Semikolon aus jeder Zeile entfernen
|
|
const cleanedText = text
|
|
.split('\n')
|
|
.map(line => line.startsWith(';') ? line.substring(1) : line)
|
|
.join('\n');
|
|
|
|
// CSV mit csv-parse parsen
|
|
const records = parse(cleanedText, {
|
|
delimiter: ';',
|
|
skip_empty_lines: true,
|
|
from_line: 2, // Erste Zeile (Header) überspringen
|
|
relax_column_count: true, // Erlaubt unterschiedliche Spaltenanzahlen
|
|
trim: true,
|
|
});
|
|
|
|
const entries = records.map(columns => {
|
|
// Erwartetes Format: Name,Vorname,Straße,PLZ/Ort,Telefon,Email,Anfrage,Termin,Dauer,Fahrtzeit,Strecke,Transport,Bezahlt,Durchgeführt,Bemerkungen
|
|
return {
|
|
name: columns[0] || '',
|
|
firstName: columns[1] || '',
|
|
street: columns[2] || '',
|
|
zipCity: columns[3] || '',
|
|
phone: columns[4] || '',
|
|
email: columns[5] || '',
|
|
requestDate: columns[6] ? new Date(columns[6]) : new Date(),
|
|
appointmentDate: columns[7] ? new Date(columns[7]) : new Date(),
|
|
workDuration: Number(columns[8]) || 0,
|
|
travelTime: Number(columns[9]) || 0,
|
|
distance: Number(columns[10]) || 0,
|
|
transport: columns[11] || 'Auto',
|
|
paidAmount: Number(columns[12]) || 0,
|
|
taskDone: columns[13] || '',
|
|
remarks: columns[14] || '',
|
|
};
|
|
});
|
|
|
|
await onImport(entries);
|
|
alert(`${entries.length} Einträge erfolgreich importiert!`);
|
|
|
|
// Input zurücksetzen
|
|
if (fileInputRef.current) {
|
|
fileInputRef.current.value = '';
|
|
}
|
|
} catch (error) {
|
|
console.error('Fehler beim Import:', error);
|
|
alert('Fehler beim Importieren der CSV-Datei. Bitte überprüfen Sie das Format.');
|
|
} finally {
|
|
setIsProcessing(false);
|
|
}
|
|
};
|
|
|
|
return (
|
|
<div className="csv-import-container">
|
|
<input
|
|
ref={fileInputRef}
|
|
type="file"
|
|
accept=".csv"
|
|
onChange={handleFileUpload}
|
|
style={{ display: 'none' }}
|
|
id="csv-file-input"
|
|
/>
|
|
<label htmlFor="csv-file-input" className="csv-import-button">
|
|
{isProcessing ? '⏳ Importiere...' : '📁 CSV importieren'}
|
|
</label>
|
|
<small className="csv-hint">
|
|
Format: Name,Vorname,Straße,PLZ/Ort,Telefon,Email,Anfrage,Termin (YYYY-MM-DD HH:MM),Dauer,Fahrtzeit,Strecke,Transport,Bezahlt,Durchgeführt,Bemerkungen
|
|
</small>
|
|
</div>
|
|
);
|
|
};
|
|
|
|
export default CSVImport;
|