/* ===================================================================== GET /api/verwaltung/orders — liefert ALLE echten Bestellungen (+ Positionen) für die interne Verwaltungsseite (siehe src/pages/verwaltung/index.astro). Zusätzlich zur Middleware (functions/_middleware.js, schützt /api/verwaltung/* IMMER, unabhängig von SITE_PUBLIC) prüft diese Route die Sitzung noch einmal selbst — Verteidigung in der Tiefe, falls diese Datei mal unabhängig von der Middleware aufgerufen wird. ===================================================================== */ import { getGateRole, unauthorizedJson } from "../../_shared/auth.js"; import { json } from "../../_shared/http.js"; export async function onRequestGet(context) { const { request, env } = context; const role = await getGateRole(request, env); if (!role) return unauthorizedJson(); if (!env.DB) { return json(500, { ok: false, error: "Datenbank nicht verbunden." }); } try { const { results: orders } = await env.DB.prepare(`SELECT * FROM orders ORDER BY created_at DESC`).all(); if (orders.length === 0) { return json(200, { ok: true, orders: [] }); } const ids = orders.map((o) => o.id); const placeholders = ids.map(() => "?").join(","); const { results: items } = await env.DB .prepare(`SELECT * FROM order_items WHERE order_id IN (${placeholders}) ORDER BY id ASC`) .bind(...ids) .all(); const itemsByOrder = new Map(); items.forEach((item) => { const liste = itemsByOrder.get(item.order_id) ?? []; liste.push(item); itemsByOrder.set(item.order_id, liste); }); const result = orders.map((o) => ({ ...o, artikel: itemsByOrder.get(o.id) ?? [] })); return json(200, { ok: true, orders: result }); } catch (err) { return json(500, { ok: false, error: "Bestellungen konnten nicht geladen werden." }); } }