fix: add error handling, empty name guard, and input validation to data module

This commit is contained in:
Ferdinand
2026-04-08 13:03:54 +02:00
parent 0a1f30553a
commit b0dfd1f716

View File

@@ -1,9 +1,22 @@
export function loadFromJSON(json) { export function loadFromJSON(json) {
const parsed = JSON.parse(json); let parsed;
try {
parsed = JSON.parse(json);
} catch (e) {
throw new Error('Ungültige JSON-Datei: ' + e.message);
}
if (typeof parsed !== 'object' || parsed === null) {
throw new Error('Ungültiges Dateiformat: Objekt erwartet');
}
return { return {
employees: parsed.employees ?? [], employees: Array.isArray(parsed.employees) ? parsed.employees : [],
calendar: parsed.calendar ?? { holidays: [], companyClosures: [] }, calendar: (parsed.calendar && typeof parsed.calendar === 'object')
history: parsed.history ?? [] ? {
holidays: Array.isArray(parsed.calendar.holidays) ? parsed.calendar.holidays : [],
companyClosures: Array.isArray(parsed.calendar.companyClosures) ? parsed.calendar.companyClosures : []
}
: { holidays: [], companyClosures: [] },
history: Array.isArray(parsed.history) ? parsed.history : []
}; };
} }
@@ -16,9 +29,11 @@ export function saveToJSON(state) {
} }
export function createEmployee(name) { export function createEmployee(name) {
const trimmed = (name ?? '').trim();
if (!trimmed) throw new Error('Mitarbeitername darf nicht leer sein');
return { return {
id: crypto.randomUUID(), id: crypto.randomUUID(),
name: name.trim(), name: trimmed,
constraints: { constraints: {
neverDays: [], neverDays: [],
lowPriorityDays: [], lowPriorityDays: [],
@@ -48,6 +63,7 @@ export function toggleClosure(state, isoDate) {
// Adds entries to history, replacing any existing entries for the same dates // Adds entries to history, replacing any existing entries for the same dates
export function addHistoryEntries(state, entries) { export function addHistoryEntries(state, entries) {
if (!entries?.length) return;
const dates = new Set(entries.map(e => e.date)); const dates = new Set(entries.map(e => e.date));
state.history = state.history.filter(h => !dates.has(h.date)); state.history = state.history.filter(h => !dates.has(h.date));
state.history.push(...entries); state.history.push(...entries);