import { useRef, useState } from 'react' import { useScrollIntoView } from '../../hooks/useScrollIntoView' import { Button, Dialog, Field } from '../ui' const FIELDS = ['provider', 'purpose', 'cost', 'costInterval', 'startDate', 'termMonths', 'renewalMonths', 'noticeValue', 'noticeUnit', 'note'] const NUMBERS = ['termMonths', 'renewalMonths', 'noticeValue'] function toForm(contract) { const form = { costInterval: 'month', noticeUnit: 'months' } for (const key of FIELDS) { if (contract?.[key] !== null && contract?.[key] !== undefined) form[key] = String(contract[key]) } return form } /** Leere Felder werden null, damit die Fristenlogik "Fristen fehlen" erkennt. */ function toDoc(form) { const doc = {} for (const key of FIELDS) { const raw = (form[key] ?? '').trim() if (raw === '') doc[key] = null else if (NUMBERS.includes(key)) doc[key] = parseInt(raw, 10) else if (key === 'cost') doc[key] = parseFloat(raw.replace(',', '.')) else doc[key] = raw } return doc } export default function ContractForm({ contract, onSave, onClose }) { const [form, setForm] = useState(() => toForm(contract)) const [files, setFiles] = useState([]) const [saving, setSaving] = useState(false) const [error, setError] = useState(null) const errorRef = useRef(null) useScrollIntoView(errorRef, error) const set = (key) => (e) => setForm((f) => ({ ...f, [key]: e.target.value })) const submit = async (e) => { e.preventDefault() setSaving(true) setError(null) try { await onSave(toDoc(form), files) onClose() } catch (err) { setError(err.message) setSaving(false) } } const input = (key, label, props = {}) => ( ) return ( Abbrechen {saving ? 'Speichert …' : 'Speichern'} > } > {error && {error}} {input('provider', 'Anbieter', { required: true })} {input('purpose', 'Wofür')} {input('cost', 'Kosten (€)', { inputMode: 'decimal' })} Monat Jahr {input('startDate', 'Vertragsbeginn', { type: 'date' })} {input('termMonths', 'Laufzeit (Monate, 0 = jederzeit kündbar)', { type: 'number', min: 0 })} {input('renewalMonths', 'Verlängert sich um (Monate, 0 = endet)', { type: 'number', min: 0 })} {input('noticeValue', 'Kündigungsfrist', { type: 'number', min: 0 })} Monate Tage setFiles([...e.target.files])} /> ) }