Files
Speisekarte/components/SectionManager.tsx
T
florian.wilde a9a9cf7ba4 v1.5: Alle Manager-Komponenten auf eigene API-Routen umgestellt
Neue interne Route Handler unter app/api/ (dishes inkl. Bulk-Delete,
sections, allergens, additives, menu-entries, dish-suggestions,
settings, admin/branding) ersetzen den direkten Browser→Postgrest-
Zugriff der bisherigen Supabase-Anbindung. Jede Route prüft Autorisierung
selbst (lib/auth/session.ts requireRole) statt sich auf Postgres-RLS zu
verlassen – ersetzt 1:1 die bisherigen Policies (öffentlich lesbar /
staff+admin schreiben / nur admin für Einstellungen & Benutzer).

Rezeptvorschlag-Dublettencheck (SuggestionForm) läuft jetzt zwingend
serverseitig im POST-Handler, da es keinen Browser→Postgres-Pfad mehr
gibt. "Passkey annehmen" (SuggestionReview) läuft transaktional
(Gericht anlegen + Vorschlag löschen in einem Schritt).

Logo/Favicon: neuer lokaler Dateispeicher (lib/branding.ts, Docker-
Volume) statt Supabase-Storage-Bucket, ausgeliefert über
app/branding/[filename]. logoUrl()/faviconUrl() liefern jetzt einfache
relative Pfade statt einer fest verdrahteten Supabase-Storage-URL.

DeepL-Route (api/translate) und Benutzerverwaltung (api/admin/users)
laufen jetzt gegen die users-Tabelle statt Supabase Auth.

Alle "use client"-Manager-Komponenten (DishManager, WeekEditor,
SectionManager, CodeListManager, SuggestionForm/Review, UserManager,
DesignEditor) rufen ihre jeweiligen /api/-Routen per fetch() statt den
Supabase-Browser-Client zu nutzen.
2026-07-18 11:01:52 +02:00

296 lines
9.5 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"use client";
// Verwaltung der Essenszeiten (Brotzeit, Mittagessen, …):
// anlegen, umbenennen, Uhrzeit ändern, löschen, Reihenfolge anpassen.
import { useCallback, useEffect, useState } from "react";
import { formatMessage } from "@/lib/i18n/shared";
import { localized } from "@/lib/types";
import type { Section } from "@/lib/types";
import { useDict, useLocale } from "@/components/i18n/LocaleProvider";
interface SectionForm {
key: string | null; // null = neue Essenszeit
label: string;
labelEn: string;
labelPl: string;
timeFrom: string;
timeTo: string;
}
const EMPTY_FORM: SectionForm = {
key: null,
label: "",
labelEn: "",
labelPl: "",
timeFrom: "",
timeTo: "",
};
function splitTimeRange(range: string): { from: string; to: string } {
const [from, to] = range.split("-").map((s) => s.trim());
return { from: from ?? "", to: to ?? "" };
}
export default function SectionManager() {
const dict = useDict();
const locale = useLocale();
const [sections, setSections] = useState<Section[]>([]);
const [form, setForm] = useState<SectionForm | null>(null);
const [error, setError] = useState<string | null>(null);
const [loading, setLoading] = useState(true);
const [busy, setBusy] = useState(false);
const load = useCallback(async () => {
const res = await fetch("/api/sections");
if (!res.ok)
setError(formatMessage(dict.sectionManager.loadError, { message: String(res.status) }));
else setSections(await res.json());
setLoading(false);
}, [dict]);
useEffect(() => {
load();
}, [load]);
async function save(e: React.FormEvent) {
e.preventDefault();
if (!form) return;
setError(null);
const label = form.label.trim();
if (!label || !form.timeFrom || !form.timeTo) return;
const payload = {
label,
label_en: form.labelEn.trim() || null,
label_pl: form.labelPl.trim() || null,
time_range: `${form.timeFrom} - ${form.timeTo}`,
};
const res = form.key
? await fetch(`/api/sections/${form.key}`, {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(payload),
})
: await fetch("/api/sections", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(payload),
});
if (!res.ok) {
setError(formatMessage(dict.sectionManager.saveError, { message: String(res.status) }));
return;
}
setForm(null);
await load();
}
async function remove(section: Section) {
if (
!window.confirm(
formatMessage(dict.sectionManager.confirmDelete, { name: section.label })
)
)
return;
const res = await fetch(`/api/sections/${section.key}`, { method: "DELETE" });
if (!res.ok)
setError(formatMessage(dict.sectionManager.deleteError, { message: String(res.status) }));
await load();
}
async function move(section: Section, direction: -1 | 1) {
const idx = sections.findIndex((s) => s.key === section.key);
const neighbor = sections[idx + direction];
if (!neighbor) return;
setBusy(true);
setError(null);
const [r1, r2] = await Promise.all([
fetch(`/api/sections/${section.key}`, {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ sort: neighbor.sort }),
}),
fetch(`/api/sections/${neighbor.key}`, {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ sort: section.sort }),
}),
]);
if (!r1.ok || !r2.ok)
setError(formatMessage(dict.sectionManager.saveError, { message: "move failed" }));
setBusy(false);
await load();
}
return (
<div className="max-w-3xl">
<div className="flex items-center gap-3 mb-4">
<h1 className="text-xl font-bold text-[var(--c-primary)] mr-auto">
{dict.sectionManager.title}
</h1>
<button
type="button"
className="btn btn-add"
onClick={() => setForm(EMPTY_FORM)}
>
{dict.sectionManager.newSection}
</button>
</div>
{error && (
<p className="mb-3 text-sm text-[var(--c-del)]" role="alert">
{error}
</p>
)}
{form && (
<form onSubmit={save} className="card mb-4 space-y-4">
<h2 className="font-semibold">
{form.key ? dict.sectionManager.editSection : dict.sectionManager.newSection}
</h2>
<div>
<label className="label" htmlFor="section-label">
{dict.sectionManager.nameLabel}
</label>
<input
id="section-label"
className="input"
value={form.label}
onChange={(e) => setForm({ ...form, label: e.target.value })}
required
/>
</div>
<div className="grid gap-3 sm:grid-cols-2">
<div>
<label className="label" htmlFor="section-label-en">
{dict.sectionManager.nameEnLabel}
</label>
<input
id="section-label-en"
className="input"
value={form.labelEn}
onChange={(e) => setForm({ ...form, labelEn: e.target.value })}
/>
</div>
<div>
<label className="label" htmlFor="section-label-pl">
{dict.sectionManager.namePlLabel}
</label>
<input
id="section-label-pl"
className="input"
value={form.labelPl}
onChange={(e) => setForm({ ...form, labelPl: e.target.value })}
/>
</div>
</div>
<div className="flex gap-3">
<div className="max-w-32">
<label className="label" htmlFor="section-time-from">
{dict.sectionManager.timeFrom}
</label>
<input
id="section-time-from"
type="time"
className="input"
value={form.timeFrom}
onChange={(e) => setForm({ ...form, timeFrom: e.target.value })}
required
/>
</div>
<div className="max-w-32">
<label className="label" htmlFor="section-time-to">
{dict.sectionManager.timeTo}
</label>
<input
id="section-time-to"
type="time"
className="input"
value={form.timeTo}
onChange={(e) => setForm({ ...form, timeTo: e.target.value })}
required
/>
</div>
</div>
<div className="flex gap-2">
<button type="submit" className="btn btn-add">
{dict.common.save}
</button>
<button
type="button"
className="btn btn-neutral"
onClick={() => setForm(null)}
>
{dict.common.cancel}
</button>
</div>
</form>
)}
{loading ? (
<p className="text-gray-500">{dict.common.loading}</p>
) : (
<ul className="divide-y divide-gray-200 border border-gray-200 rounded-md bg-white">
{sections.map((section, idx) => (
<li key={section.key} className="flex items-center gap-3 px-4 py-2">
<div className="flex flex-col">
<button
type="button"
className="text-gray-400 hover:text-[var(--c-primary)] disabled:opacity-30"
onClick={() => move(section, -1)}
disabled={busy || idx === 0}
aria-label={dict.sectionManager.moveUp}
title={dict.sectionManager.moveUp}
>
▲
</button>
<button
type="button"
className="text-gray-400 hover:text-[var(--c-primary)] disabled:opacity-30"
onClick={() => move(section, 1)}
disabled={busy || idx === sections.length - 1}
aria-label={dict.sectionManager.moveDown}
title={dict.sectionManager.moveDown}
>
▼
</button>
</div>
<span className="mr-auto">
<span className="font-semibold">{localized(section, locale)}</span>{" "}
<span className="text-gray-500">– {section.time_range}</span>
</span>
<button
type="button"
className="btn btn-primary"
onClick={() => {
const { from, to } = splitTimeRange(section.time_range);
setForm({
key: section.key,
label: section.label,
labelEn: section.label_en ?? "",
labelPl: section.label_pl ?? "",
timeFrom: from,
timeTo: to,
});
}}
>
{dict.common.edit}
</button>
<button
type="button"
className="btn btn-del"
onClick={() => remove(section)}
>
{dict.common.delete}
</button>
</li>
))}
{sections.length === 0 && (
<li className="px-4 py-3 text-gray-500">{dict.sectionManager.empty}</li>
)}
</ul>
)}
</div>
);
}