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) {
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 {
employees: parsed.employees ?? [],
calendar: parsed.calendar ?? { holidays: [], companyClosures: [] },
history: parsed.history ?? []
employees: Array.isArray(parsed.employees) ? parsed.employees : [],
calendar: (parsed.calendar && typeof parsed.calendar === 'object')
? {
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) {
const trimmed = (name ?? '').trim();
if (!trimmed) throw new Error('Mitarbeitername darf nicht leer sein');
return {
id: crypto.randomUUID(),
name: name.trim(),
name: trimmed,
constraints: {
neverDays: [],
lowPriorityDays: [],
@@ -48,6 +63,7 @@ export function toggleClosure(state, isoDate) {
// Adds entries to history, replacing any existing entries for the same dates
export function addHistoryEntries(state, entries) {
if (!entries?.length) return;
const dates = new Set(entries.map(e => e.date));
state.history = state.history.filter(h => !dates.has(h.date));
state.history.push(...entries);