import { useEffect, useMemo, useState } from 'react' import { Link, useNavigate, useParams } from 'react-router-dom' import { ArrowLeft, FileSpreadsheet, Loader2, Save, Trash2 } from 'lucide-react' import { api } from '../utils/api' import { csvPreviewTdStyle } from '../utils/csvPreviewCells' const MODULE_LABEL = { nutrition: 'Ernährung', weight: 'Gewicht', blood_pressure: 'Blutdruck', activity: 'Aktivität', sleep: 'Schlaf', vitals_baseline: 'Vitalwerte (Baseline)', } /** Erlaubt Eingaben wie 1,03 oder 1.03 während des Tippens; Finale normalisiert bei Blur/Speichern. */ function normalizeDecimalInputString(raw) { let s = String(raw).trim().replace(/\s/g, '') if (s === '') return '' const lastComma = s.lastIndexOf(',') const lastDot = s.lastIndexOf('.') if (lastComma >= 0 && lastDot >= 0) { if (lastComma > lastDot) { s = s.replace(/\./g, '').replace(',', '.') } else { s = s.replace(/,/g, '') } } else if (lastComma >= 0) { s = s.replace(',', '.') } return s } function applyCustomFactorToTcObject(tc, fieldKey, raw) { const base = tc[fieldKey] && typeof tc[fieldKey] === 'object' ? { ...tc[fieldKey] } : { type: 'float', decimal_separator: 'auto', flexible: true } const normalized = normalizeDecimalInputString(raw) if (normalized === '') { delete base.conversion_factor } else { const num = Number(normalized) if (Number.isNaN(num)) { return { ok: false, message: `Konvertierungsfaktor (${fieldKey}): keine gültige Zahl.` } } base.conversion_factor = num base.source_unit = 'custom' } delete base.target_unit tc[fieldKey] = base return { ok: true } } function SampleTable({ sampleRows, columns }) { if (!sampleRows?.length || !columns?.length) return null const showCols = columns.slice(0, 8) return (
{showCols.map((c) => ( ))} {sampleRows.slice(0, 5).map((row, i) => ( {showCols.map((c) => ( ))} ))}
{c}
{row[c] ?? '—'}
) } export default function AdminCsvTemplateEditorPage() { const { id: routeId } = useParams() const navigate = useNavigate() const isNew = routeId === 'new' const templateId = isNew ? null : Number(routeId) const [modules, setModules] = useState([]) const [module, setModule] = useState('nutrition') const [mappingName, setMappingName] = useState('') const [description, setDescription] = useState('') const [delimiter, setDelimiter] = useState(';') const [encoding, setEncoding] = useState('utf-8') const [hasHeader, setHasHeader] = useState(true) const [columnSignature, setColumnSignature] = useState([]) const [columns, setColumns] = useState([]) const [fieldMappings, setFieldMappings] = useState({}) const [typeConversionsText, setTypeConversionsText] = useState('{}') const [sampleRows, setSampleRows] = useState([]) const [seedHint, setSeedHint] = useState(null) const [file, setFile] = useState(null) const [delimiterOverride, setDelimiterOverride] = useState('') const [seedTemplateId, setSeedTemplateId] = useState('') const [seedOptions, setSeedOptions] = useState([]) const [loading, setLoading] = useState(!isNew) const [analyzing, setAnalyzing] = useState(false) const [saving, setSaving] = useState(false) const [error, setError] = useState(null) /** Lokaler Text für Konvertierungsfaktor (nur bei source_unit custom), Commit bei Blur/Speichern — verhindert 1. → 1 beim Tippen. */ const [customFactorDraftByField, setCustomFactorDraftByField] = useState({}) const modMeta = useMemo(() => modules.find((m) => m.id === module), [modules, module]) const aggregateSleepImport = modMeta?.import_mode === 'apple_sleep_aggregate' const targetOptions = useMemo(() => { if (!modMeta?.fields || aggregateSleepImport) return [] return Object.entries(modMeta.fields).map(([key, meta]) => ({ value: key, label: `${key}${meta.required ? ' *' : ''}`, })) }, [modMeta, aggregateSleepImport]) const requiredTargets = useMemo(() => { if (!modMeta?.fields) return [] return Object.entries(modMeta.fields) .filter(([, v]) => v.required) .map(([k]) => k) }, [modMeta]) useEffect(() => { api .getCsvModules() .then((r) => setModules(r.modules || [])) .catch(() => {}) }, []) useEffect(() => { if (!module) return api .adminListCsvTemplates(module) .then((d) => setSeedOptions(d.templates || [])) .catch(() => setSeedOptions([])) }, [module]) useEffect(() => { if (isNew || !templateId) return let ok = true setLoading(true) setError(null) api .adminGetCsvTemplate(templateId) .then((t) => { if (!ok) return setModule(t.module) setMappingName(t.mapping_name || '') setDescription(t.description || '') setDelimiter(t.delimiter || ',') setEncoding(t.encoding || 'utf-8') setHasHeader(!!t.has_header) setColumnSignature(t.column_signature || []) const fm = t.field_mappings || {} setFieldMappings(fm) setColumns(Object.keys(fm)) setTypeConversionsText(JSON.stringify(t.type_conversions || {}, null, 2)) setCustomFactorDraftByField({}) setSampleRows([]) setSeedHint(null) }) .catch((e) => { if (ok) setError(e.message) }) .finally(() => { if (ok) setLoading(false) }) return () => { ok = false } }, [isNew, templateId]) const assignedTargets = useMemo(() => { return new Set( Object.values(fieldMappings).filter((v) => v && v !== '-' && v !== '_skip'), ) }, [fieldMappings]) const missingRequired = useMemo(() => { return requiredTargets.filter((r) => !assignedTargets.has(r)) }, [requiredTargets, assignedTargets]) const unitTargets = useMemo(() => { if (!modMeta?.fields || aggregateSleepImport) return [] const list = [] const seen = new Set() for (const t of assignedTargets) { const opts = modMeta.fields[t]?.source_unit_options if (!opts?.length || seen.has(t)) continue seen.add(t) list.push({ field: t, options: opts }) } return list.sort((a, b) => a.field.localeCompare(b.field)) }, [modMeta, assignedTargets, aggregateSleepImport]) const getSourceUnitSelectValue = (fieldKey) => { let tc try { tc = JSON.parse(typeConversionsText || '{}') } catch { return null } const opts = modMeta?.fields?.[fieldKey]?.source_unit_options || [] const canonical = opts.find((o) => o.is_canonical)?.id || opts[0]?.id const su = tc[fieldKey]?.source_unit if (su != null && su !== '') { const sid = String(su).toLowerCase() const hit = opts.find((o) => o.id === sid) if (hit) return hit.id } if (tc[fieldKey]?.conversion_factor != null && tc[fieldKey]?.conversion_factor !== '') { const hasCustomOpt = opts.some((o) => o.id === 'custom') if (hasCustomOpt) return 'custom' } return canonical || '' } const updateSourceUnit = (fieldKey, sourceUnitId) => { let tc try { tc = JSON.parse(typeConversionsText || '{}') } catch { setError('type_conversions: ungültiges JSON (Quelleinheit kann nicht gesetzt werden).') return } const opts = modMeta?.fields?.[fieldKey]?.source_unit_options || [] const canonical = opts.find((o) => o.is_canonical)?.id const base = tc[fieldKey] && typeof tc[fieldKey] === 'object' ? { ...tc[fieldKey] } : { type: 'float', decimal_separator: 'auto', flexible: true } delete base.target_unit if (sourceUnitId === canonical || sourceUnitId === '' || sourceUnitId == null) { delete base.source_unit delete base.conversion_factor } else if (sourceUnitId === 'custom') { base.source_unit = 'custom' // conversion_factor nur per Eingabefeld setzen/löschen } else { base.source_unit = sourceUnitId delete base.conversion_factor } tc[fieldKey] = base setTypeConversionsText(JSON.stringify(tc, null, 2)) setCustomFactorDraftByField((prev) => { const next = { ...prev } delete next[fieldKey] return next }) setError(null) } const getCustomConversionFactorInputValue = (fieldKey) => { let tc try { tc = JSON.parse(typeConversionsText || '{}') } catch { return '' } const v = tc[fieldKey]?.conversion_factor if (v == null || v === '') return '' return String(v) } const getCustomFactorFieldDisplay = (fieldKey) => { if (Object.prototype.hasOwnProperty.call(customFactorDraftByField, fieldKey)) { return customFactorDraftByField[fieldKey] } return getCustomConversionFactorInputValue(fieldKey) } const commitCustomFactorOnBlur = (fieldKey, raw) => { if (getSourceUnitSelectValue(fieldKey) !== 'custom') { setCustomFactorDraftByField((prev) => { const next = { ...prev } delete next[fieldKey] return next }) return } let tc try { tc = JSON.parse(typeConversionsText || '{}') } catch { setError('type_conversions: ungültiges JSON (Faktor kann nicht gesetzt werden).') return } const result = applyCustomFactorToTcObject(tc, fieldKey, raw) if (!result.ok) { setError(result.message || 'Konvertierungsfaktor ungültig.') return } setTypeConversionsText(JSON.stringify(tc, null, 2)) setCustomFactorDraftByField((prev) => { const next = { ...prev } delete next[fieldKey] return next }) setError(null) } const handleAnalyze = async () => { if (!file) { setError('Bitte eine CSV-Datei wählen.') return } setAnalyzing(true) setError(null) try { const delim = delimiterOverride || null const seed = seedTemplateId === '' ? null : Number(seedTemplateId) const res = await api.adminAnalyzeCsvTemplate(file, module, delim, seed) setColumns(res.columns || []) setColumnSignature(res.column_signature_normalized || []) setFieldMappings(res.field_mappings || {}) setTypeConversionsText(JSON.stringify(res.type_conversions || {}, null, 2)) setSampleRows(res.sample_rows || []) setDelimiter(res.delimiter || ';') setEncoding(res.encoding || 'utf-8') setSeedHint(res.seed_template || null) setCustomFactorDraftByField({}) } catch (e) { setError(e.message || 'Analyse fehlgeschlagen') } finally { setAnalyzing(false) } } const updateMapping = (col, dbField) => { setFieldMappings((prev) => ({ ...prev, [col]: dbField || '-' })) } const handleSave = async () => { setError(null) let textForTc = typeConversionsText const pendingFactorDrafts = { ...customFactorDraftByField } if (Object.keys(pendingFactorDrafts).length > 0) { try { const tco = JSON.parse(textForTc || '{}') for (const [fk, raw] of Object.entries(pendingFactorDrafts)) { const su = String(tco[fk]?.source_unit || '').toLowerCase() if (su !== 'custom') continue const result = applyCustomFactorToTcObject(tco, fk, raw) if (!result.ok) { setError(result.message || 'Konvertierungsfaktor ungültig.') return } } textForTc = JSON.stringify(tco, null, 2) setTypeConversionsText(textForTc) setCustomFactorDraftByField({}) } catch { setError('type_conversions: ungültiges JSON.') return } } let tc = null try { tc = JSON.parse(textForTc || '{}') if (tc !== null && typeof tc !== 'object') throw new Error() } catch { setError('type_conversions: ungültiges JSON.') return } if (!mappingName.trim()) { setError('Bitte einen Namen für die Vorlage eingeben.') return } if (!columns.length || !Object.keys(fieldMappings).length) { setError('Keine Spalten-Zuordnung: CSV analysieren oder Vorlage laden.') return } if (missingRequired.length) { setError(`Pflicht-Zielfelder fehlen: ${missingRequired.join(', ')}`) return } const payload = { module, mapping_name: mappingName.trim(), description: description.trim() || null, column_signature: columnSignature.length ? columnSignature : null, delimiter, encoding: encoding || 'utf-8', has_header: hasHeader, field_mappings: fieldMappings, type_conversions: tc, } if (!payload.column_signature?.length) { setError('column_signature fehlt — bitte CSV erneut analysieren.') return } setSaving(true) try { if (isNew) { await api.adminCreateCsvTemplate(payload) } else { const { module: _m, ...patch } = payload await api.adminUpdateCsvTemplate(templateId, patch) } navigate('/admin/csv-templates') } catch (e) { setError(e.message || 'Speichern fehlgeschlagen') } finally { setSaving(false) } } const handleDelete = async () => { if (isNew || !templateId) return if (!confirm('System-Vorlage wirklich löschen?')) return setError(null) try { await api.adminDeleteCsvTemplate(templateId) navigate('/admin/csv-templates') } catch (e) { setError(e.message || 'Löschen fehlgeschlagen') } } if (loading) { return (
) } return (
Zur Liste

{isNew ? 'Neue CSV-Vorlage' : 'Vorlage bearbeiten'}

{error && (
{error}
)}
Modul
{!isNew && (

Modul bestehender Vorlagen kann nicht geändert werden. System-Vorlagen können hier bearbeitet und gespeichert werden (Signatur, Trennzeichen, Zuordnungen).

)} {aggregateSleepImport && (

Schlaf (Apple-Aggregat): Die Zeilen werden nicht über Spalten-Ziele importiert, sondern vom Apple-Schlaf-Parser ausgewertet (Schlafanalyse oder Segment-Export). Alle CSV-Spalten bleiben auf „ignorieren“. Wichtig sind die{' '} gespeicherte Spalten-Signatur und das passende Datei-Format — damit die Datei in der Nutzer-Auswahl erkannt wird.

)}
1. Beispiel-CSV (wie Import)
setFile(e.target.files?.[0] || null)} />
{seedHint && (

Seed: {seedHint.mapping_name} · Vorlage abgedeckt{' '} {Math.round((seedHint.confidence || 0) * 100)} % {seedHint.columns_matched != null && seedHint.columns_in_template != null ? ` (${seedHint.columns_matched}/${seedHint.columns_in_template} Spalten)` : ''} {seedHint.jaccard != null && ( <> {' '} · Jaccard {Math.round(seedHint.jaccard * 100)} % )}

)} {sampleRows.length > 0 && }
2. Stammdaten
setMappingName(e.target.value)} placeholder="z. B. FDDB Export 2026" />