import { json, error } from '@sveltejs/kit'; import { getDb, newId, rows, row } from '$lib/server/db'; import { requireAuth } from '$lib/server/auth'; export async function GET({ request, url }) { const u = await requireAuth(request); const db = getDb(); const ort_id = url.searchParams.get('ort_id'); let items; if (ort_id) { items = db.prepare(` SELECT a.* FROM ort_ausfaelle a JOIN veranstaltungsorte o ON o.id = a.ort_id WHERE a.ort_id = ? AND o.verein_id = ? ORDER BY a.von `).all(ort_id, u.verein_id); } else { items = db.prepare(` SELECT a.* FROM ort_ausfaelle a JOIN veranstaltungsorte o ON o.id = a.ort_id WHERE o.verein_id = ? ORDER BY a.von `).all(u.verein_id); } return json(rows(items as Record[])); } export async function POST({ request }) { const u = await requireAuth(request); const db = getDb(); const body = await request.json(); if (!body.ort_id || !body.von || !body.bis) throw error(400, 'ort_id, von und bis sind Pflichtfelder'); const ort = db.prepare( 'SELECT id FROM veranstaltungsorte WHERE id = ? AND verein_id = ?' ).get(body.ort_id, u.verein_id); if (!ort) throw error(404, 'Ort nicht gefunden'); const id = newId(); db.prepare(` INSERT INTO ort_ausfaelle (id, ort_id, von, bis, grund) VALUES (?, ?, ?, ?, ?) `).run( id, body.ort_id, body.von, body.bis, body.grund ?? null ); const ausfall = db.prepare('SELECT * FROM ort_ausfaelle WHERE id = ?').get(id); return json(row(ausfall as Record), { status: 201 }); }