Files
Speisekarte/components/CodeListManager.tsx
florian.wilde cd8b0fab9f feat: Speiseplan-Inhalte variabel mehrsprachig (Teil 2)
Gerichtnamen, Essenszeiten und Allergen-/Zusatzstoff-Bezeichnungen sind
jetzt genauso dynamisch mehrsprachig wie die Bedienoberfläche aus
v1.10.0, statt fest auf Englisch/Polnisch begrenzt zu sein. Neue
Übersetzungstabellen ersetzen die alten name_en/name_pl-Spalten,
DeepL-Auto-Übersetzung und CSV-Import/-Export unterstützen jetzt
beliebig viele aktive Sprachen.
2026-07-20 11:10:06 +02:00

332 lines
10 KiB
TypeScript
Raw Permalink 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";
// Pflege der globalen Allergen-/Zusatzstofflisten, die unterhalb
// der öffentlichen Speisekarte angezeigt werden.
import { useCallback, useEffect, useState } from "react";
import { formatMessage } from "@/lib/i18n/shared";
import { localized } from "@/lib/types";
import type { CodeItem } from "@/lib/types";
import { useDict, useLanguages, useLocale } from "@/components/i18n/LocaleProvider";
export default function CodeListManager({
table,
translateEnabled,
}: {
table: "allergens" | "additives";
translateEnabled: boolean;
}) {
const dict = useDict();
const locale = useLocale();
const languages = useLanguages().filter((l) => l.code !== "de");
const title =
table === "allergens" ? dict.codeList.allergensTitle : dict.codeList.additivesTitle;
const codeLabel =
table === "allergens"
? dict.codeList.allergenCodeLabel
: dict.codeList.additiveCodeLabel;
const [items, setItems] = useState<CodeItem[]>([]);
const [editing, setEditing] = useState<{
original: string | null; // code vor der Bearbeitung, null = neu
code: string;
name: string;
translations: Record<string, string>;
} | null>(null);
const [error, setError] = useState<string | null>(null);
const [notice, setNotice] = useState<string | null>(null);
const [ioBusy, setIoBusy] = useState(false);
const [translateState, setTranslateState] = useState<"idle" | "busy" | "done">(
"idle"
);
const load = useCallback(async () => {
const res = await fetch(`/api/${table}`);
if (!res.ok) setError(formatMessage(dict.codeList.loadError, { message: String(res.status) }));
else setItems(await res.json());
}, [table, dict]);
useEffect(() => {
load();
}, [load]);
async function save(e: React.FormEvent) {
e.preventDefault();
if (!editing) return;
setError(null);
const code = editing.code.trim();
const name = editing.name.trim();
if (!code || !name) return;
const payload = {
code,
name,
translations: editing.translations,
};
const res = editing.original
? await fetch(`/api/${table}/${editing.original}`, {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(payload),
})
: await fetch(`/api/${table}`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(payload),
});
if (!res.ok) {
const data = await res.json().catch(() => ({}));
setError(
data.error === "duplicate_code"
? formatMessage(dict.codeList.duplicateCode, { code })
: formatMessage(dict.codeList.saveError, { message: data.error ?? String(res.status) })
);
return;
}
setEditing(null);
await load();
}
async function remove(item: CodeItem) {
if (
!window.confirm(
formatMessage(dict.codeList.confirmDelete, { code: item.code, name: item.name })
)
)
return;
const res = await fetch(`/api/${table}/${item.code}`, { method: "DELETE" });
if (!res.ok)
setError(formatMessage(dict.codeList.deleteError, { message: String(res.status) }));
await load();
}
async function autoTranslate() {
if (!editing || !editing.name.trim()) return;
setTranslateState("busy");
setError(null);
try {
const res = await fetch("/api/translate", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
table,
id: editing.original,
text: editing.name.trim(),
}),
});
const data = await res.json();
if (!res.ok) throw new Error(data?.error ?? `Fehler (${res.status})`);
setEditing((prev) =>
prev
? { ...prev, translations: { ...prev.translations, ...(data.translations ?? {}) } }
: prev
);
setTranslateState("done");
} catch (err) {
setError(err instanceof Error ? err.message : String(err));
setTranslateState("idle");
}
}
async function exportItems() {
setError(null);
setNotice(null);
const res = await fetch(`/api/${table}/export`);
if (!res.ok) {
setError(formatMessage(dict.codeList.exportError, { message: String(res.status) }));
return;
}
const blob = await res.blob();
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = table === "allergens" ? "allergene.csv" : "zusatzstoffe.csv";
a.click();
URL.revokeObjectURL(url);
}
async function importItems(e: React.ChangeEvent<HTMLInputElement>) {
const file = e.target.files?.[0];
e.target.value = "";
if (!file) return;
setError(null);
setNotice(null);
setIoBusy(true);
const fd = new FormData();
fd.append("file", file);
const res = await fetch(`/api/${table}/import`, { method: "POST", body: fd });
setIoBusy(false);
if (!res.ok) {
setError(formatMessage(dict.codeList.importError, { message: String(res.status) }));
return;
}
const data = (await res.json()) as {
created: number;
updated: number;
skipped: { row: number; reason: string }[];
};
let msg = formatMessage(dict.codeList.importSuccess, {
created: data.created,
updated: data.updated,
});
if (data.skipped.length > 0) {
const reasons = data.skipped
.map((s) => formatMessage(dict.codeList.importSkippedRow, s))
.join("; ");
msg +=
" " + formatMessage(dict.codeList.importSkipped, { count: data.skipped.length, reasons });
}
setNotice(msg);
await load();
}
return (
<section className="card">
<div className="flex flex-wrap items-center gap-3 mb-3">
<h2 className="text-lg font-bold text-[var(--c-primary)] mr-auto">
{title}
</h2>
<button type="button" className="btn btn-neutral" onClick={exportItems}>
{dict.codeList.exportButton}
</button>
<label className="btn btn-neutral cursor-pointer">
{dict.codeList.importButton}
<input
type="file"
accept=".csv,text/csv"
className="hidden"
onChange={importItems}
disabled={ioBusy}
/>
</label>
<button
type="button"
className="btn btn-add"
onClick={() => {
setEditing({ original: null, code: "", name: "", translations: {} });
setTranslateState("idle");
}}
>
{dict.common.add}
</button>
</div>
{error && (
<p className="mb-2 text-sm text-[var(--c-del)]" role="alert">
{error}
</p>
)}
{notice && <p className="mb-2 text-sm text-green-700">{notice}</p>}
{editing && (
<form onSubmit={save} className="mb-3 space-y-2 border-b border-gray-200 pb-3">
<div className="max-w-36">
<label className="label">{codeLabel}</label>
<input
className="input"
value={editing.code}
onChange={(e) => setEditing({ ...editing, code: e.target.value })}
required
/>
</div>
<div>
<label className="label">{dict.codeList.nameLabel}</label>
<input
className="input"
value={editing.name}
onChange={(e) => setEditing({ ...editing, name: e.target.value })}
required
/>
</div>
{languages.length > 0 && (
<div className="grid gap-2 sm:grid-cols-2">
{languages.map((lang) => (
<div key={lang.code}>
<label className="label">{lang.label}</label>
<input
className="input"
value={editing.translations[lang.code] ?? ""}
onChange={(e) =>
setEditing({
...editing,
translations: { ...editing.translations, [lang.code]: e.target.value },
})
}
/>
</div>
))}
</div>
)}
{translateEnabled && languages.length > 0 && (
<div>
<button
type="button"
className="btn btn-neutral"
onClick={autoTranslate}
disabled={translateState === "busy" || !editing.name.trim()}
>
{translateState === "busy"
? dict.dishManager.translating
: dict.dishManager.autoTranslate}
</button>
{translateState === "done" && (
<span className="ml-2 text-sm text-green-700">
{dict.dishManager.translated}
</span>
)}
</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={() => setEditing(null)}
>
{dict.common.cancel}
</button>
</div>
</form>
)}
<ul className="divide-y divide-gray-100">
{items.map((item) => (
<li key={item.code} className="flex flex-wrap items-center gap-2 py-1.5 text-sm">
<span className="mr-auto">
<span className="font-semibold">{item.code}</span> –{" "}
{localized(item, locale)}
</span>
<button
type="button"
className="btn btn-primary"
onClick={() => {
setEditing({
original: item.code,
code: item.code,
name: item.name,
translations: { ...item.translations },
});
setTranslateState("idle");
}}
>
{dict.common.edit}
</button>
<button
type="button"
className="btn btn-del"
onClick={() => remove(item)}
>
{dict.common.delete}
</button>
</li>
))}
{items.length === 0 && (
<li className="py-2 text-gray-500 text-sm">{dict.codeList.empty}</li>
)}
</ul>
</section>
);
}