Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
92f852e335 | ||
|
|
cfb816b724 | ||
|
|
4e413fe600 | ||
|
|
68fd9dfc15 | ||
|
|
1d875fa02e | ||
|
|
2f56f3a479 | ||
|
|
c81d9c365a | ||
|
|
f4619d22ed | ||
|
|
4f4983f70e | ||
|
|
e9300278d4 |
No files matched your search
@@ -158,7 +158,7 @@ jobs:
|
||||
mkdir -p "$RUNNER_TEMP/lunchdaten"
|
||||
echo "LUNCH_DATA=$RUNNER_TEMP/lunchdaten" >> "$GITHUB_ENV"
|
||||
# HOSTNAME: Next bindet sich daran; im Container ist es die Kennung des Containers.
|
||||
(cd .next/standalone && HOSTNAME=0.0.0.0 PORT=3020 BACKUP_DISABLED=1 IMPORT_TEST_ORIGIN=http://127.0.0.1:3021 APP_DATA_DIR="$RUNNER_TEMP/lunchdaten" \
|
||||
(cd .next/standalone && HOSTNAME=0.0.0.0 PORT=3020 BACKUP_DISABLED=1 IMPORT_TEST_ORIGIN=http://127.0.0.1:3021 APP_DATA_DIR="$RUNNER_TEMP/lunchdaten" MAIL_TEST_DIR="$RUNNER_TEMP/lunchdaten/mails" \
|
||||
nohup node server.js > "$RUNNER_TEMP/server.log" 2>&1 &)
|
||||
for i in $(seq 30); do curl -sf localhost:3020/api/ready && exit 0; sleep 1; done
|
||||
cat "$RUNNER_TEMP/server.log"; exit 1
|
||||
|
||||
@@ -0,0 +1,175 @@
|
||||
{
|
||||
"projekt": "lunch",
|
||||
"lauf": "2026-11-07",
|
||||
"auth_typ": "passkey+magic-link",
|
||||
"asvs_level": 2,
|
||||
"gesamturteil": "solide",
|
||||
"live_geprueft": true,
|
||||
"abdeckung": {
|
||||
"geprueft": 14,
|
||||
"erfuellt": 13,
|
||||
"verletzt": 0,
|
||||
"nicht_anwendbar": 0,
|
||||
"nicht_angestrebt": 1
|
||||
},
|
||||
"befunde": [
|
||||
{
|
||||
"id": "passkey-ohne-user-verification",
|
||||
"titel": "Passkey ohne Prüfung der Person",
|
||||
"schweregrad": "mittel",
|
||||
"asvs": [
|
||||
"6.5.x"
|
||||
],
|
||||
"datei": "lib/auth/webauthn.ts",
|
||||
"angriff": "Ein Schlüssel ohne PIN genügt.",
|
||||
"fix": "userVerification required, requireUserVerification true",
|
||||
"belegt_durch": "live",
|
||||
"status": "behoben"
|
||||
},
|
||||
{
|
||||
"id": "geraet-person-nicht-entfernbar",
|
||||
"titel": "Verlorenes Gerät und Personen nicht entfernbar",
|
||||
"schweregrad": "mittel",
|
||||
"asvs": [
|
||||
"7.4.x",
|
||||
"7.5.x"
|
||||
],
|
||||
"datei": "app/(app)/mehr/page.tsx",
|
||||
"angriff": "Verlorenes Handy bleibt 180 Tage angemeldet.",
|
||||
"fix": "Passkey und Person entfernen, Sitzungen hängen am Passkey",
|
||||
"belegt_durch": "live",
|
||||
"status": "behoben"
|
||||
},
|
||||
{
|
||||
"id": "kein-rueckweg-letzter-passkey",
|
||||
"titel": "Kein Rückweg bei Verlust des letzten Passkeys",
|
||||
"schweregrad": "mittel",
|
||||
"asvs": [
|
||||
"6.4.x"
|
||||
],
|
||||
"datei": "lib/auth/codes.ts",
|
||||
"angriff": "Haushalt verloren, wenn das einzige Gerät weg ist.",
|
||||
"fix": "Wiederherstellungscode in /app/data",
|
||||
"belegt_durch": "live",
|
||||
"status": "behoben"
|
||||
},
|
||||
{
|
||||
"id": "bremse-xff-umgehbar",
|
||||
"titel": "Bremse über X-Forwarded-For umgehbar",
|
||||
"schweregrad": "niedrig",
|
||||
"asvs": [
|
||||
"6.3.1"
|
||||
],
|
||||
"datei": "lib/auth/request.ts",
|
||||
"angriff": "Je Versuch neue vorgetäuschte Adresse.",
|
||||
"fix": "gemeinsamer Topf je Bremse",
|
||||
"belegt_durch": "live",
|
||||
"status": "behoben"
|
||||
},
|
||||
{
|
||||
"id": "kein-anmeldeprotokoll",
|
||||
"titel": "Anmeldungen werden nicht protokolliert",
|
||||
"schweregrad": "niedrig",
|
||||
"asvs": [
|
||||
"16.x"
|
||||
],
|
||||
"datei": "lib/auth/",
|
||||
"angriff": "Missbrauch bleibt unbemerkt.",
|
||||
"fix": "Protokolltabelle mit Arbeitspaket 2",
|
||||
"belegt_durch": "live",
|
||||
"status": "offen"
|
||||
},
|
||||
{
|
||||
"id": "sitzung-ohne-hoechstdauer",
|
||||
"titel": "Sitzung ohne absolute Höchstdauer",
|
||||
"schweregrad": "info",
|
||||
"asvs": [
|
||||
"7.3.2"
|
||||
],
|
||||
"datei": "lib/auth/session.ts",
|
||||
"angriff": "Gestohlener Keks bleibt gültig, solange benutzt.",
|
||||
"fix": "feste Obergrenze erwägen",
|
||||
"belegt_durch": "live",
|
||||
"status": "offen"
|
||||
},
|
||||
{
|
||||
"id": "keine-csp-hsts",
|
||||
"titel": "Keine CSP, HSTS ungeklärt",
|
||||
"schweregrad": "niedrig",
|
||||
"asvs": [
|
||||
"3.4.x"
|
||||
],
|
||||
"datei": "next.config.ts",
|
||||
"angriff": "Härtung gegen XSS und Downgrade fehlt.",
|
||||
"fix": "CSP mit Nonces, HSTS auf der Box prüfen",
|
||||
"belegt_durch": "live",
|
||||
"status": "offen"
|
||||
},
|
||||
{
|
||||
"id": "mail-versand-flutbar",
|
||||
"titel": "Mail-Kontingent und Postfach ließen sich fluten",
|
||||
"schweregrad": "niedrig",
|
||||
"asvs": [
|
||||
"6.3.1",
|
||||
"6.6.3"
|
||||
],
|
||||
"datei": "app/api/auth/mail/request/route.ts",
|
||||
"angriff": "Mit wechselnden IPs viele Links an eine bekannte Adresse, Resend-Kontingent verbraucht.",
|
||||
"fix": "Je Adresse 3/15 min und 10/Tag, gemeinsamer Topf 30/h",
|
||||
"belegt_durch": "code",
|
||||
"status": "behoben"
|
||||
},
|
||||
{
|
||||
"id": "mail-adresse-aufzaehlbar",
|
||||
"titel": "Vergebene Adressen ließen sich beim Eintragen erkennen",
|
||||
"schweregrad": "niedrig",
|
||||
"asvs": [
|
||||
"6.3.7"
|
||||
],
|
||||
"datei": "app/api/me/email/route.ts",
|
||||
"angriff": "Angemeldete Person prüft fremde Adressen auf Konten, auch haushaltsübergreifend.",
|
||||
"fix": "Gleiche Antwort; Link greift bei vergebener Adresse nicht",
|
||||
"belegt_durch": "code",
|
||||
"status": "behoben"
|
||||
},
|
||||
{
|
||||
"id": "mail-sitzung-ueberlebt-adresse",
|
||||
"titel": "Mail-Sitzungen überlebten das Entfernen der Adresse",
|
||||
"schweregrad": "niedrig",
|
||||
"asvs": [
|
||||
"7.4.x"
|
||||
],
|
||||
"datei": "app/api/me/email/route.ts",
|
||||
"angriff": "Wer das Postfach mitliest, bleibt angemeldet, obwohl die Adresse entfernt wurde.",
|
||||
"fix": "Adresse entfernen/ändern beendet Sitzungen via mail",
|
||||
"belegt_durch": "test",
|
||||
"status": "behoben"
|
||||
},
|
||||
{
|
||||
"id": "mail-sitzung-zu-lang",
|
||||
"titel": "Mail-Sitzungen lebten 180 Tage",
|
||||
"schweregrad": "niedrig",
|
||||
"asvs": [
|
||||
"7.3.x"
|
||||
],
|
||||
"datei": "lib/auth/session.ts",
|
||||
"angriff": "Ein einmal geöffneter Link hält ein halbes Jahr.",
|
||||
"fix": "30 Tage gleitend für via mail",
|
||||
"belegt_durch": "code",
|
||||
"status": "behoben"
|
||||
},
|
||||
{
|
||||
"id": "mail-link-nicht-geraetegebunden",
|
||||
"titel": "Mail-Link nicht an das anfragende Gerät gebunden",
|
||||
"schweregrad": "info",
|
||||
"asvs": [
|
||||
"6.6.2"
|
||||
],
|
||||
"datei": "lib/auth/mail-login.ts",
|
||||
"angriff": "Wer den Link hat, meldet sich an — auch auf einem anderen Gerät.",
|
||||
"fix": "Bewusst: Link soll auch auf anderem Gerät gehen; 15 min, einmal, nur Anmelden",
|
||||
"belegt_durch": "code",
|
||||
"status": "akzeptiert"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -1,13 +1,13 @@
|
||||
# „Was gibt's?“ (lunch) — Projekt-Briefing für Claude Code
|
||||
# foodplanhero (lunch) — Projekt-Briefing für Claude Code
|
||||
|
||||
> **Produkt:** „Was gibt's?“ — die Familie entscheidet gemeinsam, was es warm
|
||||
> **Produkt:** foodplanhero („Plan. Cook. Smile.“, für Maike; bis 26.11.34 „Was gibt's?“) — die Familie entscheidet gemeinsam, was es warm
|
||||
> gibt, und aus dem Plan entsteht die Einkaufsliste. Konzept: `docs/konzept.md`.
|
||||
> **Technischer Name:** `lunch` (E-0003). **Maintainer:** Kai Böhm.
|
||||
> **Nutzerin, für die gebaut wird:** die Planerin (bei uns Maike).
|
||||
> **Plattform:** Olares One (Kubernetes), Repo und CI auf Gitea — kein Supabase,
|
||||
> kein Vercel (E-0001). Eigene Gestaltung, nicht AImighty (E-0002).
|
||||
> Verteilung über den Markt, Repo öffentlich (E-0005).
|
||||
> **Status:** 26.11.33 — alle neun Arbeitspakete aus `docs/PROJEKTSTART.md` sind gebaut:
|
||||
> **Status:** 26.11.43 — alle neun Arbeitspakete aus `docs/PROJEKTSTART.md` sind gebaut:
|
||||
> Anmeldung (Passkeys, Kinder mit Gerät + PIN), Gerichte (Link, Kochbuchfoto, AI über den
|
||||
> Olares Router), Wünschen, Plan, Einkaufsliste (Echtzeit, offline), Kochmodus mit
|
||||
> Bewertung, Web-App; Einzahl bei Stück-Mengen (26.11.15), Preise und Kosten mit Ampel
|
||||
@@ -16,8 +16,13 @@
|
||||
> Produkte je Gericht (26.11.21), Veto mit Gegenvorschlag (26.11.22),
|
||||
> bis zu 5 Fotos je Gericht (26.11.23), Gerichte einsprechen (26.11.24), Kassenbons (V2b, 26.11.25),
|
||||
> Führung (26.11.27), Präsentationsmodus und Küchendisplay (26.11.28),
|
||||
> lange Bons und Aldi (26.11.29), „Mein Gericht“ (26.11.30). Offen ist der
|
||||
> Magic Link (braucht SMTP).
|
||||
> lange Bons und Aldi (26.11.29), „Mein Gericht“ (26.11.30), Bons „nicht zum Kochen“
|
||||
> (26.11.33), foodplanhero für Maike (26.11.35), eine Schrift (26.11.37), Produktgruppen,
|
||||
> eigene Zutaten und Lieblingsprodukt je Haushalt (26.11.38, E-0015), Löffel und Gebinde
|
||||
> (26.11.39, E-0016), Anmelden per Mail-Link über Resend (26.11.40, E-0017; nur
|
||||
> anmelden, keine Geräte oder Passkeys aus einer Mail-Sitzung), Leiste bleibt nach der
|
||||
> Tastatur unten (26.11.41), Icon Kochmütze mit Herz (26.11.42), Fotos aus der Mediathek (26.11.43). Offen: Kai trägt
|
||||
> den Resend-Schlüssel unter Mehr › Mails verschicken ein.
|
||||
> **Letzte Aktualisierung:** 7. November 2026
|
||||
|
||||
Diese Datei ist das Gedächtnis jeder Sitzung. Entscheidungen stehen in
|
||||
@@ -85,8 +90,8 @@ Datenmodells (`households`, `dishes`, `rounds`, `slots`, …).
|
||||
Wiederholung der Vorrunde, Frisches zuerst; jeder Slot trägt einen Satz, warum.
|
||||
6. **Gestaltung (E-0002, E-0009):** Pastell Coral & Lavendel, nur als Token in
|
||||
`app/globals.css` (nie Farbwerte am Bauteil); Hauptaktion als Pille in Coral mit
|
||||
dunkler Schrift, Etiketten `.eyebrow` in tiefem Lavendel, Überschriften in Newsreader
|
||||
(lokal, `app/fonts/`), Abschnitte mit feinen Linien statt Kästen. Dunkler Modus von
|
||||
dunkler Schrift, Etiketten `.eyebrow` in tiefem Lavendel, eine Schrift: Poppins überall, Caveat nur
|
||||
für „by Maike“ (lokal, `app/fonts/`, E-0014), Abschnitte mit feinen Linien statt Kästen. Dunkler Modus von
|
||||
Anfang an; `tests/contrast.test.ts` verlangt 4,5:1. shadcn/ui, Icons aus Lucide,
|
||||
keine Emojis, nichts vom CDN. Leere Zustände sagen, was als Nächstes zu tun ist.
|
||||
Mobile zuerst. Ändert sich das Symbol: `docs/icon/lunch.svg`, dann
|
||||
@@ -412,6 +417,20 @@ Vorlagen ersetzt. `tests/seed.test.ts` prüft die Dateien. Ein Haushalt
|
||||
- In einer Karte (`bg-secondary`) kein `outline`-Knopf: Seitenfläche auf Kartenfläche wirkt
|
||||
im Dunkeln wie ein Loch. Zweite Wege als Textlink, Nebenknöpfe bündig (`px-0`), seit 26.11.31.
|
||||
|
||||
## foodplanhero für Maike (seit 26.11.35, E-0013)
|
||||
|
||||
- Name in der Oberfläche „foodplanhero“ (`app.name`), technisch bleibt alles `lunch`
|
||||
(appid, Chart, Datenbank). Slogan „Plan. Cook. Smile.“.
|
||||
- `components/brand/brand.tsx`: `Wordmark` (Poppins Bold, „hero“ in `--hero`), `Slogan`
|
||||
(`active` hebt plan/cook/smile hervor), `Portrait` (grüner Ring, „by Maike“ in Caveat,
|
||||
5,31° gedreht — nach Kais Figma). Schriften lokal: `app/fonts` (woff2) und
|
||||
`lib/brand-fonts` (woff fürs Startbild, `outputFileTracingIncludes` in next.config).
|
||||
- Widmung je Haushalt (`households.dedication_*`, Migration 0021): Foto unter
|
||||
`/app/data/fotos/<haushalt>/widmung-*.webp`, nie im Repo. `/api/widmung/foto` liefert es
|
||||
auch ohne Sitzung (Anmelden, Einladung, Startbild) — von Kai so gewollt.
|
||||
- Startbild: `/startbild/<w>x<h>` (`next/og`), Größen in `lib/startup-sizes.ts`, verlinkt
|
||||
über `appleWebApp.startupImage`. Nur solange die App lädt, keine künstliche Pause.
|
||||
|
||||
## Mein Gericht (seit 26.11.30, Kai und Mike, E-0012)
|
||||
|
||||
- `wishes.is_mine` (Migration 0019, eins je Person und Runde, nie an einem Veto oder
|
||||
|
||||
+7
-7
@@ -1,5 +1,5 @@
|
||||
# ============================================================================
|
||||
# OlaresManifest.yaml — Lunch („Was gibt's?“)
|
||||
# OlaresManifest.yaml — foodplanhero (lunch, bis 26.11.34 „Was gibt's?“)
|
||||
#
|
||||
# Linter-Regeln, die hier zwingend gelten (scripts/check-chart.sh):
|
||||
# - metadata.name, metadata.appid, Chart.yaml.name und der Ordnername
|
||||
@@ -18,10 +18,10 @@ workloadReplicas:
|
||||
metadata:
|
||||
name: lunch
|
||||
appid: lunch
|
||||
title: What's cooking?
|
||||
description: The family decides together what's for dinner — and the shopping list writes itself. Runs entirely on your own box.
|
||||
title: foodplanhero
|
||||
description: Plan. Cook. Smile. The family decides together what's for dinner — and the shopping list writes itself. Runs entirely on your own box.
|
||||
icon: https://git.aimighty.olares.de/aimighty/bilder/raw/branch/main/lunch/icon.png
|
||||
version: 26.11.33
|
||||
version: 26.11.43
|
||||
categories:
|
||||
- Applications
|
||||
|
||||
@@ -38,7 +38,7 @@ entrances:
|
||||
- name: lunch
|
||||
host: lunch
|
||||
port: 3000
|
||||
title: What's cooking?
|
||||
title: foodplanhero
|
||||
icon: https://git.aimighty.olares.de/aimighty/bilder/raw/branch/main/lunch/icon.png
|
||||
authLevel: public
|
||||
invisible: false
|
||||
@@ -61,14 +61,14 @@ permission:
|
||||
appData: true
|
||||
|
||||
spec:
|
||||
versionName: '26.11.33'
|
||||
versionName: '26.11.43'
|
||||
|
||||
featuredImage: https://git.aimighty.olares.de/aimighty/bilder/raw/branch/main/lunch/icon.png
|
||||
promoteImage:
|
||||
- https://git.aimighty.olares.de/aimighty/bilder/raw/branch/main/lunch/icon.png
|
||||
|
||||
fullDescription: |
|
||||
**What's cooking?** takes the daily "what are we eating?" off the
|
||||
**foodplanhero** — Plan. Cook. Smile. — takes the daily "what are we eating?" off the
|
||||
person who usually plans.
|
||||
|
||||
Everyone in the family wishes for dishes in ten seconds — children
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
# Was gibt's? (lunch)
|
||||
# foodplanhero (lunch)
|
||||
|
||||
Die Familie entscheidet gemeinsam, was es warm gibt, und aus dem Plan entsteht die Einkaufsliste — als PWA auf der eigenen Olares One. Konzept in [`docs/konzept.md`](docs/konzept.md), Weichen in [`docs/entscheidungen.md`](docs/entscheidungen.md), Regeln für jede Sitzung in [`CLAUDE.md`](CLAUDE.md), Daten und Arbeitspakete für den Start in [`docs/PROJEKTSTART.md`](docs/PROJEKTSTART.md).
|
||||
@@ -4,12 +4,18 @@ import { DishForm } from "@/components/dishes/dish-form";
|
||||
import { requireSession } from "@/lib/auth/session";
|
||||
import { withHousehold } from "@/lib/db";
|
||||
import { getDish } from "@/lib/dishes";
|
||||
import { fromBase, type BaseUnit, type KitchenUnit } from "@/lib/units";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
// Bearbeiten zeigt die Mengen für vier Portionen (oder was man dort einträgt).
|
||||
const PORTIONS = 4;
|
||||
|
||||
function amountIn(qty: number, unit: BaseUnit, display: KitchenUnit | null, packSize: number | null) {
|
||||
const n = display ? fromBase(qty, display, unit, packSize) : null;
|
||||
return n === null ? { qty, unit } : { qty: Math.round(n * 100) / 100, unit: display as string };
|
||||
}
|
||||
|
||||
export default async function EditDishPage({ params }: { params: Promise<{ id: string }> }) {
|
||||
const { id } = await params;
|
||||
if (!/^[0-9a-f-]{36}$/.test(id)) notFound();
|
||||
@@ -36,8 +42,9 @@ export default async function EditDishPage({ params }: { params: Promise<{ id: s
|
||||
isTrial: dish.isTrial,
|
||||
sourceUrl: dish.sourceUrl,
|
||||
ingredients: dish.ingredients.map((i) => ({
|
||||
ingredient: { id: i.ingredientId, name: i.name, unit: i.unit },
|
||||
qty: i.qtyPerPortion * PORTIONS,
|
||||
ingredient: { id: i.ingredientId, name: i.name, unit: i.unit, kitchenUnit: i.kitchenUnit, packKind: i.packKind, packSize: i.packSize },
|
||||
// Im Maß, in dem sie eingegeben wurde: „2 EL“, „1 Dose“ (26.11.39).
|
||||
...amountIn(i.qtyPerPortion * PORTIONS, i.unit, i.displayUnit, i.packSize),
|
||||
note: i.note,
|
||||
product: i.product,
|
||||
})),
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { ChevronLeft, MonitorPlay } from "lucide-react";
|
||||
import { TrialNote } from "@/components/dishes/trial-note";
|
||||
import Link from "next/link";
|
||||
import { notFound } from "next/navigation";
|
||||
import { getLocale, getTranslations } from "next-intl/server";
|
||||
@@ -54,7 +55,7 @@ export default async function DishPage({ params }: { params: Promise<{ id: strin
|
||||
<div className="relative aspect-[4/3] overflow-hidden sm:mx-4 sm:mt-4 sm:rounded-2xl">
|
||||
<DishPhoto dishId={dish.id} photo={dish.photo} />
|
||||
<Link
|
||||
href="/gerichte"
|
||||
href={dish.isTrial ? "/gerichte?ansicht=ausprobieren" : "/gerichte"}
|
||||
aria-label={t("title")}
|
||||
className="absolute left-3 top-3 flex size-11 items-center justify-center rounded-full bg-background/90 text-foreground"
|
||||
>
|
||||
@@ -75,6 +76,7 @@ export default async function DishPage({ params }: { params: Promise<{ id: strin
|
||||
) : null}
|
||||
</header>
|
||||
{photos.length ? <PhotoGallery dishId={dish.id} title={dish.title} photos={photos} canManage={canWrite} /> : null}
|
||||
{dish.isTrial ? <TrialNote id={dish.id} canWrite={canWrite} /> : null}
|
||||
{canWrite ? <DishActions id={dish.id} /> : null}
|
||||
{dish.steps.length || dish.ingredients.length ? (
|
||||
<Link
|
||||
|
||||
@@ -107,7 +107,7 @@ export default async function DishesPage({ searchParams }: { searchParams: Promi
|
||||
href="/gerichte/hinzufuegen"
|
||||
className={cn(
|
||||
buttonVariants({ size: "lg" }),
|
||||
"fixed bottom-[calc(4.5rem+env(safe-area-inset-bottom))] right-4 z-10 shadow-lg",
|
||||
"kb-shift fixed bottom-[calc(4.5rem+env(safe-area-inset-bottom))] right-4 z-10 shadow-lg",
|
||||
)}
|
||||
>
|
||||
<Plus aria-hidden />
|
||||
|
||||
@@ -5,6 +5,7 @@ import { CookingMode } from "@/components/cooking/cooking-mode";
|
||||
import { requireSession } from "@/lib/auth/session";
|
||||
import { cookingSlot } from "@/lib/cooking";
|
||||
import { withHousehold } from "@/lib/db";
|
||||
import { Slogan } from "@/components/brand/brand";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
@@ -22,6 +23,7 @@ export default async function CookingPage({ params }: { params: Promise<{ id: st
|
||||
<header className="flex flex-col gap-1">
|
||||
<p className="eyebrow">{slot.cookName ? t("eyebrowCook", { name: slot.cookName }) : t("eyebrow")}</p>
|
||||
<h1 className="text-4xl leading-tight">{slot.dish.title}</h1>
|
||||
<Slogan active="cook" />
|
||||
</header>
|
||||
{slot.cookedAt ? (
|
||||
<p className="rounded-2xl border border-border p-4">{t("alreadyCooked")}</p>
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
import { redirect } from "next/navigation";
|
||||
import { getTranslations } from "next-intl/server";
|
||||
import { MailSettings } from "@/components/more/mail-settings";
|
||||
import { requireSession } from "@/lib/auth/session";
|
||||
import { withHousehold } from "@/lib/db";
|
||||
import { loadMail, RESEND } from "@/lib/mail";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
// Mails verschicken (26.11.40), nur für Admins; per Mail-Link angemeldet nur lesen.
|
||||
export default async function MailSettingsPage() {
|
||||
const session = await requireSession();
|
||||
if (session.role !== "admin") redirect("/mehr");
|
||||
const t = await getTranslations("more.mailSettings");
|
||||
const { stored, me } = await withHousehold(session.householdId, async (c) => ({
|
||||
stored: await loadMail(c),
|
||||
me: (await c.query("select email from members where id = $1", [session.memberId])).rows[0]?.email as string | null,
|
||||
}));
|
||||
return (
|
||||
<main className="mx-auto flex max-w-md flex-col gap-5 px-4 py-6">
|
||||
<header className="flex flex-col gap-1">
|
||||
<p className="eyebrow">{session.householdName}</p>
|
||||
<h1 className="text-4xl leading-tight">{t("title")}</h1>
|
||||
<p className="text-muted-foreground">{t("intro")}</p>
|
||||
</header>
|
||||
{session.via === "mail" ? (
|
||||
<p className="rounded-xl border border-border px-4 py-3 text-sm">{(await getTranslations("auth.errors"))("mailSession")}</p>
|
||||
) : (
|
||||
<MailSettings
|
||||
me={me}
|
||||
current={
|
||||
stored
|
||||
? { host: stored.host, port: stored.port, secure: stored.secure, username: stored.username, fromAddress: stored.fromAddress, fromName: stored.fromName, hasPassword: !!stored.passwordEnc }
|
||||
: null
|
||||
}
|
||||
defaults={{ ...RESEND, fromAddress: "hallo@foodplanhero.de", fromName: "foodplanhero", hasPassword: false }}
|
||||
/>
|
||||
)}
|
||||
</main>
|
||||
);
|
||||
}
|
||||
+54
-4
@@ -6,9 +6,14 @@ import { LanguageSelect, SignOutButton } from "@/components/more/account-actions
|
||||
import { RemoveButton } from "@/components/more/remove-button";
|
||||
import { requireAdult } from "@/lib/auth/session";
|
||||
import { KidDevices, KidsAdmin } from "@/components/more/kids-admin";
|
||||
import { DedicationForm } from "@/components/more/dedication-form";
|
||||
import { Portrait, Slogan, Wordmark } from "@/components/brand/brand";
|
||||
import { getDedication, photoVersion } from "@/lib/dedication";
|
||||
import { aiFor } from "@/lib/ai-settings";
|
||||
import { InstallHint } from "@/components/install-hint";
|
||||
import { BudgetSettings } from "@/components/more/budget-settings";
|
||||
import { MailSignIn } from "@/components/more/mail-sign-in";
|
||||
import { can, WITH_PASSKEY } from "@/lib/auth/roles";
|
||||
import { withHousehold } from "@/lib/db";
|
||||
import { isLocale } from "@/lib/locale";
|
||||
|
||||
@@ -27,7 +32,7 @@ export default async function MorePage() {
|
||||
const t = await getTranslations("more");
|
||||
const tc = await getTranslations("costs.settings");
|
||||
const locale = await getLocale();
|
||||
const { members, passkeys, founder, kids, kidDevices, money } = await withHousehold(session.householdId, async (client) => {
|
||||
const { members, passkeys, founder, kids, kidDevices, money, mail, dedication } = await withHousehold(session.householdId, async (client) => {
|
||||
const members = (await client.query("select id, display_name, role from members order by created_at")).rows;
|
||||
const founder = (await client.query("select created_by from households")).rows[0]?.created_by as string | null;
|
||||
const passkeys = (
|
||||
@@ -43,7 +48,17 @@ export default async function MorePage() {
|
||||
)
|
||||
).rows;
|
||||
const money = (await client.query("select budget_per_round::float as budget, expensive_per_slots as per, currency from households")).rows[0];
|
||||
return { members, passkeys, founder, kids, kidDevices, money };
|
||||
// Anmelden per Mail (26.11.40): bestätigte Adresse, offene Bestätigung, eingerichteter Versand.
|
||||
const me = (await client.query("select email, email_verified_at is not null as verified from members where id = $1", [session.memberId])).rows[0];
|
||||
const pending = (
|
||||
await client.query(
|
||||
"select email from mail_tokens where member_id = $1 and purpose = 'verify' and used_at is null and expires_at > now() order by created_at desc limit 1",
|
||||
[session.memberId],
|
||||
)
|
||||
).rows[0]?.email as string | undefined;
|
||||
const sending = (await client.query("select from_address from household_mail where password_enc is not null")).rows[0]?.from_address as string | undefined;
|
||||
const mail = { verified: me?.verified ? (me.email as string) : null, pending: pending ?? null, sending: sending ?? null };
|
||||
return { members, passkeys, founder, kids, kidDevices, money, mail, dedication: await getDedication(client) };
|
||||
});
|
||||
const aiReady = !!(await aiFor(session.householdId));
|
||||
const date = new Intl.DateTimeFormat(locale, { dateStyle: "medium" });
|
||||
@@ -84,7 +99,7 @@ export default async function MorePage() {
|
||||
|
||||
{session.role === "admin" ? (
|
||||
<Section title={t("invitePerson")} id="einladen">
|
||||
<InvitePerson />
|
||||
{session.via === "mail" ? <p className="rounded-xl border border-border px-4 py-3 text-sm">{t("mail.locked")}</p> : <InvitePerson />}
|
||||
</Section>
|
||||
) : null}
|
||||
|
||||
@@ -102,9 +117,15 @@ export default async function MorePage() {
|
||||
</ul>
|
||||
{passkeys.length > 1 ? <p className="text-sm text-muted-foreground">{t("removeHint")}</p> : null}
|
||||
<h3 className="text-sm font-medium">{t("addDevice")}</h3>
|
||||
<AddDevice />
|
||||
{session.via === "mail" ? <p className="rounded-xl border border-border px-4 py-3 text-sm">{t("mail.locked")}</p> : <AddDevice />}
|
||||
</Section>
|
||||
|
||||
{can(WITH_PASSKEY, session.role) ? (
|
||||
<Section title={t("mail.title")} id="mail">
|
||||
<MailSignIn verified={mail.verified} pending={mail.pending} locked={session.via === "mail"} />
|
||||
</Section>
|
||||
) : null}
|
||||
|
||||
{session.role === "admin" ? (
|
||||
<>
|
||||
<Section title={t("kids.title")}>
|
||||
@@ -119,6 +140,21 @@ export default async function MorePage() {
|
||||
</>
|
||||
) : null}
|
||||
|
||||
{session.role === "admin" ? (
|
||||
<Section title={t("mail.sendingTitle")} id="mails">
|
||||
<Link
|
||||
href="/mehr/mail"
|
||||
className="flex min-h-11 items-center justify-between gap-2 rounded-2xl bg-muted px-4 py-3 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
|
||||
>
|
||||
<span className="flex flex-col">
|
||||
<span>{mail.sending ? t("mail.sendingReady", { from: mail.sending }) : t("mail.sendingNotReady")}</span>
|
||||
<span className="text-sm text-muted-foreground">{t("mail.sendingSummary")}</span>
|
||||
</span>
|
||||
<ChevronRight aria-hidden className="size-5 text-muted-foreground" />
|
||||
</Link>
|
||||
</Section>
|
||||
) : null}
|
||||
|
||||
{session.role === "admin" ? (
|
||||
<Section title={t("ai.title")}>
|
||||
<Link
|
||||
@@ -134,6 +170,20 @@ export default async function MorePage() {
|
||||
</Section>
|
||||
) : null}
|
||||
|
||||
{dedication.photo || dedication.text || session.role === "admin" ? (
|
||||
<Section title={t("dedication.title", { name: dedication.name ?? "Maike" })} id="widmung">
|
||||
{dedication.photo ? (
|
||||
<Portrait src={`/api/widmung/foto?v=${photoVersion(dedication.photo)}`} name={dedication.name ?? "Maike"} size={160} className="my-2" />
|
||||
) : null}
|
||||
{dedication.text ? <p className="whitespace-pre-line text-lg leading-relaxed">{dedication.text}</p> : null}
|
||||
<p className="flex flex-col items-center gap-2 py-2 text-center">
|
||||
<Wordmark className="text-2xl" />
|
||||
<Slogan />
|
||||
</p>
|
||||
{session.role === "admin" ? <DedicationForm name={dedication.name ?? ""} text={dedication.text ?? ""} hasPhoto={!!dedication.photo} /> : null}
|
||||
</Section>
|
||||
) : null}
|
||||
|
||||
<Section title={t("language")}>
|
||||
<LanguageSelect current={isLocale(locale) ? locale : "de"} />
|
||||
</Section>
|
||||
|
||||
@@ -9,6 +9,7 @@ import { listDishes } from "@/lib/dishes";
|
||||
import { planSlots } from "@/lib/plan";
|
||||
import { currentRound } from "@/lib/rounds";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { Slogan } from "@/components/brand/brand";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
@@ -42,6 +43,7 @@ export default async function PlanPage() {
|
||||
<header className="flex flex-col gap-1">
|
||||
<p className="eyebrow">{data.round ? t(`status.${data.round.status}`) : t("eyebrow")}</p>
|
||||
<h1 className="text-4xl leading-tight">{t("title")}</h1>
|
||||
{data.round && data.round.status !== "open" ? <Slogan active="plan" /> : null}
|
||||
{data.round ? (
|
||||
<p className="text-muted-foreground">
|
||||
{[day, t("meals", { n: data.round.slotsCount }), t("wishes", { n: "wishCount" in data ? data.wishCount ?? 0 : 0 })].filter(Boolean).join(" · ")}
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
import { Slogan, Wordmark } from "@/components/brand/brand";
|
||||
import { MailLink } from "@/components/auth/mail-link";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
// Ziel des Links aus der Mail (26.11.40). Wie AuthShell, nur dass Titel und Text
|
||||
// erst im Browser feststehen (der Token steht hinter #).
|
||||
export default function MailLinkPage() {
|
||||
return (
|
||||
<main className="mx-auto flex min-h-dvh w-full max-w-sm flex-col justify-center gap-6 px-4 py-10">
|
||||
<p className="flex flex-col items-center gap-2 text-center">
|
||||
<Wordmark className="text-4xl" />
|
||||
<Slogan />
|
||||
</p>
|
||||
<MailLink />
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -5,7 +5,9 @@ import { KIDS_COOKIE } from "@/lib/auth/kids";
|
||||
import { getTranslations } from "next-intl/server";
|
||||
import { AuthShell } from "@/components/auth/auth-shell";
|
||||
import { LoginButton } from "@/components/auth/login-button";
|
||||
import { MailLogin } from "@/components/auth/mail-login";
|
||||
import { getSession, isSetUp } from "@/lib/auth/session";
|
||||
import { photoVersion, publicDedication } from "@/lib/dedication";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
@@ -13,9 +15,12 @@ export default async function SignInPage() {
|
||||
if (!(await isSetUp())) redirect("/einrichten");
|
||||
if (await getSession()) redirect("/");
|
||||
const t = await getTranslations("auth.login");
|
||||
const d = await publicDedication();
|
||||
const portrait = d?.photo ? { src: `/api/widmung/foto?v=${photoVersion(d.photo)}`, name: d.name ?? "Maike" } : null;
|
||||
return (
|
||||
<AuthShell title={t("title")} intro={t("intro")}>
|
||||
<AuthShell title={t("title")} intro={t("intro")} portrait={portrait}>
|
||||
<LoginButton />
|
||||
<MailLogin />
|
||||
{(await cookies()).has(KIDS_COOKIE) ? (
|
||||
<Link href="/kinder" className="mx-auto inline-flex min-h-11 items-center text-sm font-semibold underline-offset-4 hover:underline">
|
||||
{t("kids")}
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
import { z } from "zod";
|
||||
import { withAuth } from "@/lib/db";
|
||||
import { fail, json, readJson, sameOrigin } from "@/lib/auth/http";
|
||||
import { createMailToken, findMailMember, linkMail, normalizeEmail, sendInBackground } from "@/lib/auth/mail-login";
|
||||
import { clientIp } from "@/lib/auth/request";
|
||||
import { tooManyAttempts } from "@/lib/auth/throttle";
|
||||
import { loadInstance } from "@/lib/auth/webauthn";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
const body = z.object({ email: z.string().trim().max(200).email() });
|
||||
|
||||
// Link per Mail anfordern (26.11.40). Die Antwort ist immer dieselbe — ob es die
|
||||
// Adresse gibt, verrät sie nicht, auch nicht durch ihre Dauer (Versand im Hintergrund).
|
||||
export async function POST(request: Request) {
|
||||
const parsed = body.safeParse(await readJson(request));
|
||||
const result = await withAuth(async (client) => {
|
||||
const instance = await loadInstance(client);
|
||||
if (!instance) return fail("notSetUp", 409);
|
||||
if (!sameOrigin(request, instance.origin)) return fail("origin", 403);
|
||||
if (!parsed.success) return fail("invalid", 400);
|
||||
const email = normalizeEmail(parsed.data.email);
|
||||
if (
|
||||
(await tooManyAttempts(client, `mail:${clientIp(request)}`, 10, 15)) ||
|
||||
(await tooManyAttempts(client, `mail-to:${email}`, 3, 15)) ||
|
||||
(await tooManyAttempts(client, `mail-to-day:${email}`, 10, 24 * 60)) ||
|
||||
// Gemeinsamer Topf: hält Resend-Kontingent und Absender-Ruf, auch wenn jemand Adressen variiert.
|
||||
(await tooManyAttempts(client, "mail:*", 30, 60))
|
||||
) {
|
||||
return fail("tooMany", 429);
|
||||
}
|
||||
const member = await findMailMember(client, email);
|
||||
if (!member) return null;
|
||||
const token = await createMailToken(client, { householdId: member.householdId, memberId: member.id, purpose: "login", email });
|
||||
return { member, token, email, origin: instance.origin };
|
||||
});
|
||||
if (result instanceof Response) return result;
|
||||
if (result) {
|
||||
sendInBackground(result.member.householdId, linkMail({ purpose: "login", to: result.email, token: result.token, origin: result.origin, locale: result.member.locale }));
|
||||
}
|
||||
return json({ ok: true });
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import { z } from "zod";
|
||||
import { withAuth } from "@/lib/db";
|
||||
import { fail, isSecure, json, readJson, sameOrigin } from "@/lib/auth/http";
|
||||
import { consumeMailToken } from "@/lib/auth/mail-login";
|
||||
import { clientIp } from "@/lib/auth/request";
|
||||
import { startSession } from "@/lib/auth/session";
|
||||
import { tooManyAttempts } from "@/lib/auth/throttle";
|
||||
import { loadInstance } from "@/lib/auth/webauthn";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
const body = z.object({ token: z.string().min(20).max(100) });
|
||||
|
||||
// Einen Link aus der Mail einlösen: „login“ beginnt eine Sitzung (via mail — nur
|
||||
// anmelden, E-0006), „verify“ bestätigt die eigene Adresse.
|
||||
export async function POST(request: Request) {
|
||||
const parsed = body.safeParse(await readJson(request));
|
||||
return withAuth(async (client) => {
|
||||
const instance = await loadInstance(client);
|
||||
if (!instance) return fail("notSetUp", 409);
|
||||
if (!sameOrigin(request, instance.origin)) return fail("origin", 403);
|
||||
if ((await tooManyAttempts(client, `mail-verify:${clientIp(request)}`, 20, 15)) || (await tooManyAttempts(client, "mail-verify:*", 200, 15))) {
|
||||
return fail("tooMany", 429);
|
||||
}
|
||||
if (!parsed.success) return fail("expired", 410);
|
||||
const hit = await consumeMailToken(client, parsed.data.token);
|
||||
if (!hit) return fail("expired", 410);
|
||||
if (hit.purpose === "login") {
|
||||
await startSession(client, { id: hit.memberId, householdId: hit.householdId, viaMail: true }, request, isSecure(instance.origin));
|
||||
}
|
||||
return json({ purpose: hit.purpose });
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import { guardWrite, isResponse } from "@/lib/auth/guard";
|
||||
import { fail } from "@/lib/auth/http";
|
||||
import { withHousehold } from "@/lib/db";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
// „In den Pool“ (26.11.41): ein Gericht aus „Ausprobieren“ zu den Stammgerichten.
|
||||
export async function POST(request: Request, { params }: { params: Promise<{ id: string }> }) {
|
||||
const { id } = await params;
|
||||
const session = await guardWrite(request);
|
||||
if (isResponse(session)) return session;
|
||||
if (!/^[0-9a-f-]{36}$/.test(id)) return fail("invalid", 400);
|
||||
const r = await withHousehold(session.householdId, (c) =>
|
||||
c.query("update dishes set is_trial = false, updated_at = now() where id = $1 and archived_at is null", [id]),
|
||||
);
|
||||
return r.rowCount === 1 ? new Response(null, { status: 204 }) : fail("notFound", 404);
|
||||
}
|
||||
@@ -42,5 +42,5 @@ export async function POST(request: Request) {
|
||||
byAi = true;
|
||||
}
|
||||
const imageUrl = recipe.image ? new URL(recipe.image, page.url).toString() : null;
|
||||
return json({ ...(await draftFromRecipe(recipe, await getLocale(), { sourceUrl: page.url, imageUrl, ai })), byAi });
|
||||
return json({ ...(await draftFromRecipe(recipe, await getLocale(), { sourceUrl: page.url, imageUrl, ai, householdId: session.householdId })), byAi });
|
||||
}
|
||||
@@ -40,5 +40,5 @@ export async function POST(request: Request) {
|
||||
throw error;
|
||||
}
|
||||
if (!recipe) return fail("noRecipe", 422);
|
||||
return json({ ...(await draftFromRecipe(recipe, await getLocale(), { ai })), byAi: true });
|
||||
return json({ ...(await draftFromRecipe(recipe, await getLocale(), { ai, householdId: session.householdId })), byAi: true });
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import { guardWrite, isResponse } from "@/lib/auth/guard";
|
||||
import { fail, json, readJson } from "@/lib/auth/http";
|
||||
import { stepIngredient } from "@/lib/dishes";
|
||||
import { allIngredients } from "@/lib/ingredients";
|
||||
import { withHousehold } from "@/lib/db";
|
||||
import { standardizeSteps } from "@/lib/recipe-standardize";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
@@ -24,7 +25,7 @@ export async function POST(request: Request) {
|
||||
const body = input.safeParse(await readJson(request));
|
||||
if (!body.success) return fail("invalid", 400);
|
||||
const locale = await getLocale();
|
||||
const all = new Map((await allIngredients()).map((e) => [e.id, e]));
|
||||
const all = new Map((await withHousehold(session.householdId, (c) => allIngredients(c))).map((e) => [e.id, e]));
|
||||
const own = body.data.ingredientIds.map((id) => all.get(id)).filter((e) => !!e);
|
||||
const styled = await standardizeSteps(
|
||||
await aiFor(session.householdId),
|
||||
|
||||
@@ -28,5 +28,5 @@ export async function POST(request: Request) {
|
||||
}
|
||||
if (!recipe) return fail("noRecipe", 422);
|
||||
recipe = { ...recipe, ingredients: guardAmounts(recipe.ingredients, body.data.text), steps: guardSteps(recipe.steps, body.data.text) };
|
||||
return json({ ...(await draftFromRecipe(recipe, await getLocale(), { ai })), byAi: true });
|
||||
return json({ ...(await draftFromRecipe(recipe, await getLocale(), { ai, householdId: session.householdId })), byAi: true });
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import { guardWrite, isResponse } from "@/lib/auth/guard";
|
||||
import { fail, json } from "@/lib/auth/http";
|
||||
import { withHousehold } from "@/lib/db";
|
||||
import { PhotoRejected, removePhoto, storePhoto } from "@/lib/photos";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
// Widmung pflegen (26.11.35): Name, ein paar Sätze, ein Foto — nur Admins.
|
||||
// Felder als Formular, damit das Foto in derselben Anfrage mitkommen kann.
|
||||
export async function PUT(request: Request) {
|
||||
const session = await guardWrite(request, ["admin"]);
|
||||
if (isResponse(session)) return session;
|
||||
const form = await request.formData().catch(() => null);
|
||||
if (!form) return fail("invalid", 400);
|
||||
const name = String(form.get("name") ?? "").trim();
|
||||
const text = String(form.get("text") ?? "").trim();
|
||||
if (name.length > 40 || text.length > 800) return fail("invalid", 400);
|
||||
const file = form.get("photo");
|
||||
const drop = form.get("removePhoto") === "1";
|
||||
try {
|
||||
const result = await withHousehold(session.householdId, async (c) => {
|
||||
const old = (await c.query("select dedication_photo as photo from households")).rows[0]?.photo as string | null;
|
||||
let photo = old;
|
||||
if (file instanceof File && file.size > 0) photo = await storePhoto(session.householdId, "widmung", file);
|
||||
else if (drop) photo = null;
|
||||
await c.query("update households set dedication_name = $1, dedication_text = $2, dedication_photo = $3", [name || null, text || null, photo]);
|
||||
return { old, photo };
|
||||
});
|
||||
if (result.old && result.old !== result.photo) await removePhoto(result.old);
|
||||
return json({ ok: true, photo: !!result.photo });
|
||||
} catch (error) {
|
||||
if (error instanceof PhotoRejected) return fail("photo", 400);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import { can, WITH_PASSKEY } from "@/lib/auth/roles";
|
||||
import { noMailSession } from "@/lib/auth/guard";
|
||||
import { withAuth, withHousehold } from "@/lib/db";
|
||||
import { fail, json, readJson, sameOrigin } from "@/lib/auth/http";
|
||||
import { createInvitationBody } from "@/lib/auth/schemas";
|
||||
@@ -16,6 +17,8 @@ const DAYS = { person: 7, device: 1 } as const;
|
||||
export async function POST(request: Request) {
|
||||
const session = await getSession();
|
||||
if (!session) return fail("signedOut", 401);
|
||||
const mail = noMailSession(session);
|
||||
if (mail) return mail;
|
||||
const instance = await withAuth(loadInstance);
|
||||
if (!instance || !sameOrigin(request, instance.origin)) return fail("origin", 403);
|
||||
const body = createInvitationBody.safeParse(await readJson(request));
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { z } from "zod";
|
||||
import { guardWrite, isResponse } from "@/lib/auth/guard";
|
||||
import { guardWrite, noMailSession, isResponse } from "@/lib/auth/guard";
|
||||
import { fail, json, readJson } from "@/lib/auth/http";
|
||||
import { createKidDeviceLink, LINK_HOURS } from "@/lib/auth/kids";
|
||||
import { loadInstance } from "@/lib/auth/webauthn";
|
||||
@@ -11,6 +11,8 @@ export const dynamic = "force-dynamic";
|
||||
export async function POST(request: Request) {
|
||||
const session = await guardWrite(request, ["admin"]);
|
||||
if (isResponse(session)) return session;
|
||||
const mail = noMailSession(session);
|
||||
if (mail) return mail;
|
||||
const body = z.object({ label: z.string().trim().min(1).max(60), kind: z.enum(["kids", "kitchen"]).default("kids") }).safeParse(await readJson(request));
|
||||
if (!body.success) return fail("invalid", 400);
|
||||
const instance = (await withAuth(loadInstance))!;
|
||||
@@ -22,6 +24,8 @@ export async function POST(request: Request) {
|
||||
export async function DELETE(request: Request) {
|
||||
const session = await guardWrite(request, ["admin"]);
|
||||
if (isResponse(session)) return session;
|
||||
const mail = noMailSession(session);
|
||||
if (mail) return mail;
|
||||
const body = z.object({ id: z.string().uuid() }).safeParse(await readJson(request));
|
||||
if (!body.success) return fail("invalid", 400);
|
||||
const removed = await withHousehold(session.householdId, (c) => c.query("delete from kid_devices where id = $1", [body.data.id]));
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
import { z } from "zod";
|
||||
import { guardWrite, isResponse, noMailSession } from "@/lib/auth/guard";
|
||||
import { fail, json, readJson } from "@/lib/auth/http";
|
||||
import { withHousehold } from "@/lib/db";
|
||||
import { seal } from "@/lib/vault";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
// Mailweg des Haushalts (26.11.40), nur für Admins. Das Passwort (bei Resend der
|
||||
// API-Schlüssel) geht nur hinein: verschlüsselt gespeichert, nie zurückgegeben.
|
||||
const input = z.object({
|
||||
host: z.string().trim().min(1).max(200).regex(/^[a-z0-9.-]+$/i),
|
||||
port: z.number().int().min(1).max(65535),
|
||||
secure: z.boolean(),
|
||||
username: z.string().trim().min(1).max(200),
|
||||
// undefined: bleibt; Text: neu; null: entfernen
|
||||
password: z.string().trim().min(1).max(500).nullable().optional(),
|
||||
fromAddress: z.string().trim().max(200).email(),
|
||||
fromName: z.string().trim().max(80).nullable().optional(),
|
||||
});
|
||||
|
||||
export async function PUT(request: Request) {
|
||||
const session = await guardWrite(request, ["admin"]);
|
||||
if (isResponse(session)) return session;
|
||||
const mail = noMailSession(session);
|
||||
if (mail) return mail;
|
||||
const body = input.safeParse(await readJson(request));
|
||||
if (!body.success) return fail("invalid", 400);
|
||||
const d = body.data;
|
||||
const sealed = d.password ? await seal(d.password) : null;
|
||||
await withHousehold(session.householdId, (c) =>
|
||||
c.query(
|
||||
`insert into household_mail (household_id, host, port, secure, username, password_enc, from_address, from_name, updated_by)
|
||||
values ($1, $2, $3, $4, $5, $6, $7, $8, $9)
|
||||
on conflict (household_id) do update set host = $2, port = $3, secure = $4, username = $5,
|
||||
password_enc = case when $10 then $6 else household_mail.password_enc end,
|
||||
from_address = $7, from_name = $8, updated_by = $9, updated_at = now()`,
|
||||
[session.householdId, d.host.toLowerCase(), d.port, d.secure, d.username, sealed, d.fromAddress.toLowerCase(), d.fromName || null, session.memberId, d.password !== undefined],
|
||||
),
|
||||
);
|
||||
return json({ ok: true });
|
||||
}
|
||||
|
||||
export async function DELETE(request: Request) {
|
||||
const session = await guardWrite(request, ["admin"]);
|
||||
if (isResponse(session)) return session;
|
||||
const mail = noMailSession(session);
|
||||
if (mail) return mail;
|
||||
await withHousehold(session.householdId, (c) => c.query("delete from household_mail"));
|
||||
return json({ ok: true });
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import { z } from "zod";
|
||||
import { getTranslations } from "next-intl/server";
|
||||
import { guardWrite, isResponse, noMailSession } from "@/lib/auth/guard";
|
||||
import { fail, json, readJson } from "@/lib/auth/http";
|
||||
import { tooManyAttempts } from "@/lib/auth/throttle";
|
||||
import { loadInstance } from "@/lib/auth/webauthn";
|
||||
import { withAuth } from "@/lib/db";
|
||||
import { buttonMail, MailNotConfigured, sendMail } from "@/lib/mail";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
const body = z.object({ to: z.string().trim().max(200).email() });
|
||||
|
||||
// „Testmail an mich“: prüft den Zugang mit einer echten Mail. Nur Admins, gebremst.
|
||||
export async function POST(request: Request) {
|
||||
const session = await guardWrite(request, ["admin"]);
|
||||
if (isResponse(session)) return session;
|
||||
const mail = noMailSession(session);
|
||||
if (mail) return mail;
|
||||
const parsed = body.safeParse(await readJson(request));
|
||||
if (!parsed.success) return fail("invalid", 400);
|
||||
const origin = await withAuth(async (client) => {
|
||||
if (await tooManyAttempts(client, `mail-test:${session.householdId}`, 5, 15)) return null;
|
||||
return (await loadInstance(client))!.origin;
|
||||
});
|
||||
if (!origin) return fail("tooMany", 429);
|
||||
const t = await getTranslations("mail.test");
|
||||
try {
|
||||
await sendMail(session.householdId, buttonMail({ to: parsed.data.to.toLowerCase(), subject: t("subject"), lead: t("lead"), button: t("button"), url: origin, note: t("note") }));
|
||||
} catch (error) {
|
||||
if (error instanceof MailNotConfigured) return fail("mailNotConfigured", 409);
|
||||
// Der Grund des Servers hilft beim Einrichten (falscher Schlüssel, Absender nicht bestätigt) — nur für Admins.
|
||||
return json({ error: "mailFailed", detail: String((error as Error).message).slice(0, 300) }, 502);
|
||||
}
|
||||
return json({ ok: true });
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import { z } from "zod";
|
||||
import { noMailSession } from "@/lib/auth/guard";
|
||||
import { withAuth, withHousehold } from "@/lib/db";
|
||||
import { fail, readJson, sameOrigin } from "@/lib/auth/http";
|
||||
import { getSession } from "@/lib/auth/session";
|
||||
@@ -11,6 +12,8 @@ export const dynamic = "force-dynamic";
|
||||
export async function POST(request: Request) {
|
||||
const session = await getSession();
|
||||
if (!session) return fail("signedOut", 401);
|
||||
const mail = noMailSession(session);
|
||||
if (mail) return mail;
|
||||
const instance = await withAuth(loadInstance);
|
||||
if (!instance || !sameOrigin(request, instance.origin)) return fail("origin", 403);
|
||||
if (session.role !== "admin") return fail("forbidden", 403);
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
import { z } from "zod";
|
||||
import { guardWrite, isResponse } from "@/lib/auth/guard";
|
||||
import { fail, json, readJson } from "@/lib/auth/http";
|
||||
import { PLANNERS } from "@/lib/auth/roles";
|
||||
import { withHousehold } from "@/lib/db";
|
||||
import { setPackSize } from "@/lib/ingredients";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
const body = z.object({ size: z.number().positive().max(100000) });
|
||||
|
||||
// Gebindegröße für den Haushalt (26.11.39): „bei uns hat die Dose 500 g“ — gilt für
|
||||
// alle Gerichte des Haushalts; ein Produkt mit Packung am Gericht geht vor.
|
||||
export async function PUT(request: Request, { params }: { params: Promise<{ id: string }> }) {
|
||||
const { id } = await params;
|
||||
const session = await guardWrite(request, [...PLANNERS]);
|
||||
if (isResponse(session)) return session;
|
||||
const parsed = body.safeParse(await readJson(request));
|
||||
if (!parsed.success || !/^[0-9a-f-]{36}$/.test(id)) return fail("invalid", 400);
|
||||
const size = Math.round(parsed.data.size * 1000) / 1000;
|
||||
const ok = await withHousehold(session.householdId, (c) => setPackSize(c, session.householdId, id, size));
|
||||
return ok ? json({ size }) : fail("noPack", 404);
|
||||
}
|
||||
@@ -1,17 +1,65 @@
|
||||
import { getLocale } from "next-intl/server";
|
||||
import { guardRead, isResponse } from "@/lib/auth/guard";
|
||||
import { json } from "@/lib/auth/http";
|
||||
import { searchIngredients } from "@/lib/ingredient-search";
|
||||
import { allIngredients } from "@/lib/ingredients";
|
||||
import { z } from "zod";
|
||||
import { guardRead, guardWrite, isResponse } from "@/lib/auth/guard";
|
||||
import { fail, json, readJson } from "@/lib/auth/http";
|
||||
import { PLANNERS } from "@/lib/auth/roles";
|
||||
import { CATEGORIES } from "@/lib/categories";
|
||||
import { withHousehold } from "@/lib/db";
|
||||
import { searchIngredients, type IngredientEntry } from "@/lib/ingredient-search";
|
||||
import { allIngredients, createOwnIngredient, OwnIngredientRefused } from "@/lib/ingredients";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
// Zutaten-Suche beim Tippen, in der Sprache der Person.
|
||||
const view = (i: IngredientEntry, locale: string, all: IngredientEntry[], products = new Map<string, string>()) => ({
|
||||
id: i.id,
|
||||
name: i.names[locale] ?? i.names.en,
|
||||
unit: i.unit,
|
||||
group: !!i.isGroup,
|
||||
kinds: i.isGroup ? all.filter((e) => e.parentId === i.id).length : 0,
|
||||
parentId: i.parentId ?? null,
|
||||
own: !!i.own,
|
||||
// Gemerktes Produkt des Haushalts — das Formular zeigt es gleich beim Wählen.
|
||||
product: products.get(i.id) ?? null,
|
||||
// Küchenmaß und Gebinde (26.11.39); die Größe mit der des Haushalts verrechnet.
|
||||
kitchenUnit: i.kitchenUnit ?? null,
|
||||
packKind: i.packKind ?? null,
|
||||
packSize: i.packSize ?? null,
|
||||
});
|
||||
|
||||
// Zutaten-Suche beim Tippen, in der Sprache der Person — mit den eigenen des
|
||||
// Haushalts und den Produktgruppen (26.11.38). Ohne q: nur die Gruppen (fürs Anlegen).
|
||||
export async function GET(request: Request) {
|
||||
const session = await guardRead();
|
||||
if (isResponse(session)) return session;
|
||||
const q = new URL(request.url).searchParams.get("q") ?? "";
|
||||
const locale = await getLocale();
|
||||
const hits = searchIngredients(await allIngredients(), q.slice(0, 60), locale);
|
||||
return json(hits.map((i) => ({ id: i.id, name: i.names[locale] ?? i.names.en, unit: i.unit })));
|
||||
const { all, products } = await withHousehold(session.householdId, async (c) => ({
|
||||
all: await allIngredients(c),
|
||||
products: new Map((await c.query("select ingredient_id, product from household_products")).rows.map((r) => [r.ingredient_id as string, r.product as string])),
|
||||
}));
|
||||
const hits = q.trim() ? searchIngredients(all, q.slice(0, 60), locale) : all.filter((i) => i.isGroup);
|
||||
return json(hits.map((i) => view(i, locale, all, products)));
|
||||
}
|
||||
|
||||
const create = z.object({
|
||||
name: z.string().trim().min(1).max(60),
|
||||
unit: z.enum(["g", "ml", "piece"]),
|
||||
parentId: z.string().uuid().nullable(),
|
||||
category: z.enum(CATEGORIES),
|
||||
});
|
||||
|
||||
// Eigene Zutat anlegen — wer Gerichte pflegt (Kai: „Ja, wer Gerichte pflegt“).
|
||||
export async function POST(request: Request) {
|
||||
const session = await guardWrite(request, [...PLANNERS]);
|
||||
if (isResponse(session)) return session;
|
||||
const body = create.safeParse(await readJson(request));
|
||||
if (!body.success) return fail("invalid", 400);
|
||||
const locale = await getLocale();
|
||||
try {
|
||||
const entry = await withHousehold(session.householdId, (c) => createOwnIngredient(c, session.householdId, body.data));
|
||||
return json(view(entry, locale, []), 201);
|
||||
} catch (error) {
|
||||
if (error instanceof OwnIngredientRefused) return fail(error.message, 409);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
import { z } from "zod";
|
||||
import { guardWrite, isResponse, noMailSession } from "@/lib/auth/guard";
|
||||
import { fail, json, readJson } from "@/lib/auth/http";
|
||||
import { createMailToken, linkMail, normalizeEmail } from "@/lib/auth/mail-login";
|
||||
import { WITH_PASSKEY } from "@/lib/auth/roles";
|
||||
import { tooManyAttempts } from "@/lib/auth/throttle";
|
||||
import { loadInstance } from "@/lib/auth/webauthn";
|
||||
import { withAuth } from "@/lib/db";
|
||||
import { MailNotConfigured, sendMail } from "@/lib/mail";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
const body = z.object({ email: z.string().trim().max(200).email() });
|
||||
|
||||
// Die eigene Adresse für den Mail-Link (26.11.40): eintragen schickt eine
|
||||
// Bestätigung; erst der Link darin schaltet die Anmeldung per Mail frei.
|
||||
export async function PUT(request: Request) {
|
||||
const session = await guardWrite(request, [...WITH_PASSKEY]);
|
||||
if (isResponse(session)) return session;
|
||||
const mail = noMailSession(session);
|
||||
if (mail) return mail;
|
||||
const parsed = body.safeParse(await readJson(request));
|
||||
if (!parsed.success) return fail("invalid", 400);
|
||||
const email = normalizeEmail(parsed.data.email);
|
||||
const prepared = await withAuth(async (client) => {
|
||||
if (await tooManyAttempts(client, `mail-confirm:${session.memberId}`, 5, 60)) return fail("tooMany", 429);
|
||||
// Ob die Adresse schon jemandem gehört, sagt diese Antwort nicht (auch nicht über Haushalte
|
||||
// hinweg): Die Mail geht raus, der Link darin greift dann nicht (consumeMailToken).
|
||||
const locale = (await client.query("select locale from members where id = $1", [session.memberId])).rows[0]?.locale ?? null;
|
||||
const token = await createMailToken(client, { householdId: session.householdId, memberId: session.memberId, purpose: "verify", email });
|
||||
return { token, locale, origin: (await loadInstance(client))!.origin };
|
||||
});
|
||||
if (prepared instanceof Response) return prepared;
|
||||
try {
|
||||
await sendMail(session.householdId, await linkMail({ purpose: "verify", to: email, ...prepared }));
|
||||
} catch (error) {
|
||||
return fail(error instanceof MailNotConfigured ? "mailNotConfigured" : "mailFailed", 502);
|
||||
}
|
||||
return json({ pending: email });
|
||||
}
|
||||
|
||||
export async function DELETE(request: Request) {
|
||||
const session = await guardWrite(request, [...WITH_PASSKEY]);
|
||||
if (isResponse(session)) return session;
|
||||
const mail = noMailSession(session);
|
||||
if (mail) return mail;
|
||||
await withAuth(async (client) => {
|
||||
await client.query("update members set email = null, email_verified_at = null where id = $1", [session.memberId]);
|
||||
await client.query("update mail_tokens set used_at = now() where member_id = $1 and used_at is null", [session.memberId]);
|
||||
// Wer die Adresse entfernt, beendet auch jede Sitzung, die über sie begann.
|
||||
await client.query("delete from sessions where member_id = $1 and via = 'mail'", [session.memberId]);
|
||||
});
|
||||
return json({ ok: true });
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import { z } from "zod";
|
||||
import { noMailSession } from "@/lib/auth/guard";
|
||||
import { withAuth, withHousehold } from "@/lib/db";
|
||||
import { fail, readJson, sameOrigin } from "@/lib/auth/http";
|
||||
import { getSession } from "@/lib/auth/session";
|
||||
@@ -12,6 +13,8 @@ export const dynamic = "force-dynamic";
|
||||
export async function POST(request: Request) {
|
||||
const session = await getSession();
|
||||
if (!session) return fail("signedOut", 401);
|
||||
const mail = noMailSession(session);
|
||||
if (mail) return mail;
|
||||
const instance = await withAuth(loadInstance);
|
||||
if (!instance || !sameOrigin(request, instance.origin)) return fail("origin", 403);
|
||||
const body = z.object({ id: z.string().min(1).max(1024) }).safeParse(await readJson(request));
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
import { fail } from "@/lib/auth/http";
|
||||
import { currentKitchenDisplay } from "@/lib/auth/kids";
|
||||
import { getSession } from "@/lib/auth/session";
|
||||
import { withHousehold } from "@/lib/db";
|
||||
import { publicDedication } from "@/lib/dedication";
|
||||
import { readPhoto } from "@/lib/photos";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
// Maikes Foto (26.11.35). Mit Sitzung oder Küchendisplay das des eigenen Haushalts;
|
||||
// ohne — Anmelden und Startbild — das des Haushalts dieser Box. Kai hat das so
|
||||
// gewollt („Anmelden und Einrichten“): Wer die Adresse kennt, sieht Maike.
|
||||
export async function GET() {
|
||||
const session = await getSession();
|
||||
const household = session?.householdId ?? (await currentKitchenDisplay())?.householdId;
|
||||
const photo = household
|
||||
? ((await withHousehold(household, async (c) => (await c.query("select dedication_photo as p from households")).rows[0]?.p)) as string | null)
|
||||
: ((await publicDedication())?.photo ?? null);
|
||||
if (!photo) return fail("notFound", 404);
|
||||
const body = await readPhoto(photo).catch(() => null);
|
||||
if (!body) return fail("notFound", 404);
|
||||
return new Response(new Uint8Array(body), { headers: { "content-type": "image/webp", "cache-control": "public, max-age=31536000, immutable" } });
|
||||
}
|
||||
@@ -3,6 +3,7 @@ import { AuthShell } from "@/components/auth/auth-shell";
|
||||
import { InviteForm } from "@/components/auth/invite-form";
|
||||
import { findInvitation } from "@/lib/auth/invitations";
|
||||
import { withAuth } from "@/lib/db";
|
||||
import { photoVersion, publicDedication } from "@/lib/dedication";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
// Der Link ist ein Geheimnis: nie als Referrer weitergeben.
|
||||
@@ -14,8 +15,12 @@ export default async function InvitationPage({ params }: { params: Promise<{ tok
|
||||
const invitation = token.length <= 100 ? await withAuth((client) => findInvitation(client, token)) : null;
|
||||
if (!invitation) return <AuthShell title={t("expiredTitle")} intro={t("expiredText")} />;
|
||||
const isDevice = Boolean(invitation.memberId);
|
||||
// Wer neu dazukommt, sieht zuerst, wem die App gewidmet ist (26.11.35).
|
||||
const d = await publicDedication();
|
||||
const portrait = d?.photo ? { src: `/api/widmung/foto?v=${photoVersion(d.photo)}`, name: d.name ?? "Maike" } : null;
|
||||
return (
|
||||
<AuthShell
|
||||
portrait={portrait}
|
||||
title={t("title", { household: invitation.householdName })}
|
||||
intro={isDevice ? t("introDevice", { name: invitation.memberName ?? "" }) : t("introPerson")}
|
||||
>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
Copyright 2020 The Newsreader Project Authors (http://github.com/productiontype/Newsreader) Newsreader-Italic[opsz,wght].ttf: Copyright 2020 The Newsreader Project Authors (http://github.com/productiontype/Newsreader)
|
||||
Copyright 2014 The Caveat Project Authors (https://github.com/googlefonts/caveat)
|
||||
|
||||
This Font Software is licensed under the SIL Open Font License, Version 1.1.
|
||||
This license is copied below, and is also available with a FAQ at:
|
||||
@@ -0,0 +1,93 @@
|
||||
Copyright 2020 The Poppins Project Authors (https://github.com/itfoundry/Poppins) Poppins-ThinItalic.ttf: Copyright 2020 The Poppins Project Authors (https://github.com/itfoundry/Poppins) Poppins-ExtraLight.ttf: Copyright 2020 The Poppins Project Authors (https://github.com/itfoundry/Poppins) Poppins-ExtraLightItalic.ttf: Copyright 2020 The Poppins Project Authors (https://github.com/itfoundry/Poppins) Poppins-Light.ttf: Copyright 2020 The Poppins Project Authors (https://github.com/itfoundry/Poppins) Poppins-LightItalic.ttf: Copyright 2020 The Poppins Project Authors (https://github.com/itfoundry/Poppins) Poppins-Regular.ttf: Copyright 2020 The Poppins Project Authors (https://github.com/itfoundry/Poppins) Poppins-Italic.ttf: Copyright 2020 The Poppins Project Authors (https://github.com/itfoundry/Poppins) Poppins-Medium.ttf: Copyright 2020 The Poppins Project Authors (https://github.com/itfoundry/Poppins) Poppins-MediumItalic.ttf: Copyright 2020 The Poppins Project Authors (https://github.com/itfoundry/Poppins) Poppins-SemiBold.ttf: Copyright 2020 The Poppins Project Authors (https://github.com/itfoundry/Poppins) Poppins-SemiBoldItalic.ttf: Copyright 2020 The Poppins Project Authors (https://github.com/itfoundry/Poppins) Poppins-Bold.ttf: Copyright 2020 The Poppins Project Authors (https://github.com/itfoundry/Poppins) Poppins-BoldItalic.ttf: Copyright 2020 The Poppins Project Authors (https://github.com/itfoundry/Poppins) Poppins-ExtraBold.ttf: Copyright 2020 The Poppins Project Authors (https://github.com/itfoundry/Poppins) Poppins-ExtraBoldItalic.ttf: Copyright 2020 The Poppins Project Authors (https://github.com/itfoundry/Poppins) Poppins-Black.ttf: Copyright 2020 The Poppins Project Authors (https://github.com/itfoundry/Poppins) Poppins-BlackItalic.ttf: Copyright 2020 The Poppins Project Authors (https://github.com/itfoundry/Poppins)
|
||||
|
||||
This Font Software is licensed under the SIL Open Font License, Version 1.1.
|
||||
This license is copied below, and is also available with a FAQ at:
|
||||
http://scripts.sil.org/OFL
|
||||
|
||||
|
||||
-----------------------------------------------------------
|
||||
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
|
||||
-----------------------------------------------------------
|
||||
|
||||
PREAMBLE
|
||||
The goals of the Open Font License (OFL) are to stimulate worldwide
|
||||
development of collaborative font projects, to support the font creation
|
||||
efforts of academic and linguistic communities, and to provide a free and
|
||||
open framework in which fonts may be shared and improved in partnership
|
||||
with others.
|
||||
|
||||
The OFL allows the licensed fonts to be used, studied, modified and
|
||||
redistributed freely as long as they are not sold by themselves. The
|
||||
fonts, including any derivative works, can be bundled, embedded,
|
||||
redistributed and/or sold with any software provided that any reserved
|
||||
names are not used by derivative works. The fonts and derivatives,
|
||||
however, cannot be released under any other type of license. The
|
||||
requirement for fonts to remain under this license does not apply
|
||||
to any document created using the fonts or their derivatives.
|
||||
|
||||
DEFINITIONS
|
||||
"Font Software" refers to the set of files released by the Copyright
|
||||
Holder(s) under this license and clearly marked as such. This may
|
||||
include source files, build scripts and documentation.
|
||||
|
||||
"Reserved Font Name" refers to any names specified as such after the
|
||||
copyright statement(s).
|
||||
|
||||
"Original Version" refers to the collection of Font Software components as
|
||||
distributed by the Copyright Holder(s).
|
||||
|
||||
"Modified Version" refers to any derivative made by adding to, deleting,
|
||||
or substituting -- in part or in whole -- any of the components of the
|
||||
Original Version, by changing formats or by porting the Font Software to a
|
||||
new environment.
|
||||
|
||||
"Author" refers to any designer, engineer, programmer, technical
|
||||
writer or other person who contributed to the Font Software.
|
||||
|
||||
PERMISSION & CONDITIONS
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of the Font Software, to use, study, copy, merge, embed, modify,
|
||||
redistribute, and sell modified and unmodified copies of the Font
|
||||
Software, subject to the following conditions:
|
||||
|
||||
1) Neither the Font Software nor any of its individual components,
|
||||
in Original or Modified Versions, may be sold by itself.
|
||||
|
||||
2) Original or Modified Versions of the Font Software may be bundled,
|
||||
redistributed and/or sold with any software, provided that each copy
|
||||
contains the above copyright notice and this license. These can be
|
||||
included either as stand-alone text files, human-readable headers or
|
||||
in the appropriate machine-readable metadata fields within text or
|
||||
binary files as long as those fields can be easily viewed by the user.
|
||||
|
||||
3) No Modified Version of the Font Software may use the Reserved Font
|
||||
Name(s) unless explicit written permission is granted by the corresponding
|
||||
Copyright Holder. This restriction only applies to the primary font name as
|
||||
presented to the users.
|
||||
|
||||
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
|
||||
Software shall not be used to promote, endorse or advertise any
|
||||
Modified Version, except to acknowledge the contribution(s) of the
|
||||
Copyright Holder(s) and the Author(s) or with their explicit written
|
||||
permission.
|
||||
|
||||
5) The Font Software, modified or unmodified, in part or in whole,
|
||||
must be distributed entirely under this license, and must not be
|
||||
distributed under any other license. The requirement for fonts to
|
||||
remain under this license does not apply to any document created
|
||||
using the Font Software.
|
||||
|
||||
TERMINATION
|
||||
This license becomes null and void if any of the above conditions are
|
||||
not met.
|
||||
|
||||
DISCLAIMER
|
||||
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
|
||||
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
|
||||
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
|
||||
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
|
||||
OTHER DEALINGS IN THE FONT SOFTWARE.
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+15
-6
@@ -23,6 +23,7 @@
|
||||
--ok: oklch(0.58 0.13 155); /* Ampel: im Rahmen */
|
||||
--warn: oklch(0.75 0.15 75); /* Ampel: knapp darüber */
|
||||
--over: oklch(0.58 0.19 25); /* Ampel: deutlich darüber */
|
||||
--hero: oklch(0.5 0.08 150); /* foodplanhero: „hero“ im Logo, Maikes Ring (26.11.35) */
|
||||
--radius: 1rem;
|
||||
}
|
||||
|
||||
@@ -40,6 +41,7 @@
|
||||
--secondary-foreground: var(--foreground);
|
||||
--accent: oklch(0.84 0.07 300);
|
||||
--ring: oklch(0.84 0.07 300);
|
||||
--hero: oklch(0.78 0.09 150);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -60,9 +62,11 @@
|
||||
--color-ok: var(--ok);
|
||||
--color-warn: var(--warn);
|
||||
--color-over: var(--over);
|
||||
--color-hero: var(--hero);
|
||||
--radius-xl: var(--radius);
|
||||
--font-sans: var(--font-geist-sans), ui-sans-serif, system-ui, sans-serif;
|
||||
--font-serif: var(--font-newsreader), ui-serif, Georgia, serif;
|
||||
--font-sans: var(--font-poppins), ui-sans-serif, system-ui, sans-serif;
|
||||
--font-brand: var(--font-sans);
|
||||
--font-hand: var(--font-caveat), cursive;
|
||||
}
|
||||
|
||||
/* Abstand fester Knopfleisten (Speichern, Übernehmen, Weiter) zur unteren Navigation.
|
||||
@@ -75,6 +79,12 @@
|
||||
--nav-space: 0px;
|
||||
}
|
||||
|
||||
/* Knopfleisten unten folgen der Korrektur der Navigation, wenn iOS nach der
|
||||
Tastatur zu kurz rechnet (lib/use-keyboard-nav.ts setzt --kb-shift, 26.11.41). */
|
||||
.kb-shift {
|
||||
translate: 0 var(--kb-shift, 0px);
|
||||
}
|
||||
|
||||
html {
|
||||
color-scheme: light dark;
|
||||
-webkit-text-size-adjust: 100%;
|
||||
@@ -89,12 +99,11 @@ body {
|
||||
}
|
||||
|
||||
@layer base {
|
||||
/* Überschriften in der Serifenschrift, etwas enger gesetzt. */
|
||||
/* Überschriften in Poppins SemiBold, etwas enger gesetzt (E-0014: eine Schrift). */
|
||||
h1,
|
||||
h2 {
|
||||
font-family: var(--font-newsreader), ui-serif, Georgia, serif;
|
||||
font-weight: 500;
|
||||
letter-spacing: -0.01em;
|
||||
font-weight: 600;
|
||||
letter-spacing: -0.02em;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+26
-10
@@ -1,18 +1,25 @@
|
||||
import { iconUrl } from "@/lib/icon-version";
|
||||
import type { Metadata, Viewport } from "next";
|
||||
import { GeistSans } from "geist/font/sans";
|
||||
import localFont from "next/font/local";
|
||||
import { NextIntlClientProvider } from "next-intl";
|
||||
import { getLocale, getTranslations } from "next-intl/server";
|
||||
import "./globals.css";
|
||||
import { STARTUP_SIZES } from "@/lib/startup-sizes";
|
||||
|
||||
// Überschriften in einer Serifenschrift (E-0009), lokal aus app/fonts —
|
||||
// nie vom CDN. Newsreader, SIL Open Font License (app/fonts/Newsreader-OFL.txt).
|
||||
const serif = localFont({
|
||||
src: "./fonts/newsreader-latin-opsz-normal.woff2",
|
||||
weight: "200 800",
|
||||
variable: "--font-newsreader",
|
||||
// Eine Schrift für alles (Kai, 7.11.2026, E-0014): Poppins — Logo, Überschriften,
|
||||
// Text —, dazu Caveat nur für Maikes Unterschrift „by Maike“. Beide SIL Open Font
|
||||
// License (app/fonts/Poppins-OFL.txt, Caveat-OFL.txt), lokal, nie vom CDN.
|
||||
const sans = localFont({
|
||||
src: [
|
||||
{ path: "./fonts/poppins-latin-400-normal.woff2", weight: "400" },
|
||||
{ path: "./fonts/poppins-latin-500-normal.woff2", weight: "500" },
|
||||
{ path: "./fonts/poppins-latin-600-normal.woff2", weight: "600" },
|
||||
{ path: "./fonts/poppins-latin-700-normal.woff2", weight: "700" },
|
||||
],
|
||||
variable: "--font-poppins",
|
||||
display: "swap",
|
||||
});
|
||||
const hand = localFont({ src: "./fonts/caveat-latin-400-normal.woff2", weight: "400", variable: "--font-caveat", display: "swap" });
|
||||
|
||||
export async function generateMetadata(): Promise<Metadata> {
|
||||
const t = await getTranslations("app");
|
||||
@@ -20,8 +27,17 @@ export async function generateMetadata(): Promise<Metadata> {
|
||||
title: t("name"),
|
||||
description: t("tagline"),
|
||||
applicationName: t("name"),
|
||||
appleWebApp: { capable: true, title: t("name"), statusBarStyle: "default" },
|
||||
icons: { icon: "/icon.svg", apple: "/apple-touch-icon.png" },
|
||||
appleWebApp: {
|
||||
capable: true,
|
||||
title: t("name"),
|
||||
statusBarStyle: "default",
|
||||
// Startbild mit Maike, solange die Web-App lädt (app/startbild, 26.11.35).
|
||||
startupImage: STARTUP_SIZES.map(([w, h, cw, ch, dpr]) => ({
|
||||
url: `/startbild/${w}x${h}`,
|
||||
media: `(device-width: ${cw}px) and (device-height: ${ch}px) and (-webkit-device-pixel-ratio: ${dpr}) and (orientation: portrait)`,
|
||||
})),
|
||||
},
|
||||
icons: { icon: iconUrl("/icon.svg"), apple: iconUrl("/apple-touch-icon.png") },
|
||||
};
|
||||
}
|
||||
|
||||
@@ -38,7 +54,7 @@ export const viewport: Viewport = {
|
||||
export default async function RootLayout({ children }: { children: React.ReactNode }) {
|
||||
const locale = await getLocale();
|
||||
return (
|
||||
<html lang={locale} className={`${GeistSans.variable} ${serif.variable}`}>
|
||||
<html lang={locale} className={`${sans.variable} ${hand.variable}`}>
|
||||
<body className="min-h-dvh antialiased">
|
||||
<NextIntlClientProvider>{children}</NextIntlClientProvider>
|
||||
</body>
|
||||
|
||||
+7
-6
@@ -1,3 +1,4 @@
|
||||
import { iconUrl } from "@/lib/icon-version";
|
||||
import type { MetadataRoute } from "next";
|
||||
import { getLocale, getTranslations } from "next-intl/server";
|
||||
|
||||
@@ -18,14 +19,14 @@ export default async function manifest(): Promise<MetadataRoute.Manifest> {
|
||||
theme_color: "#fdfcfe",
|
||||
// Lange auf das Symbol drücken: direkt zu Wünschen, Plan und Einkauf.
|
||||
shortcuts: [
|
||||
{ name: nav("wish"), url: "/wuenschen", icons: [{ src: "/icon-192.png", sizes: "192x192" }] },
|
||||
{ name: nav("plan"), url: "/plan", icons: [{ src: "/icon-192.png", sizes: "192x192" }] },
|
||||
{ name: nav("shopping"), url: "/einkauf", icons: [{ src: "/icon-192.png", sizes: "192x192" }] },
|
||||
{ name: nav("wish"), url: "/wuenschen", icons: [{ src: iconUrl("/icon-192.png"), sizes: "192x192" }] },
|
||||
{ name: nav("plan"), url: "/plan", icons: [{ src: iconUrl("/icon-192.png"), sizes: "192x192" }] },
|
||||
{ name: nav("shopping"), url: "/einkauf", icons: [{ src: iconUrl("/icon-192.png"), sizes: "192x192" }] },
|
||||
],
|
||||
icons: [
|
||||
{ src: "/icon-192.png", sizes: "192x192", type: "image/png" },
|
||||
{ src: "/icon-512.png", sizes: "512x512", type: "image/png" },
|
||||
{ src: "/icon-512-maskable.png", sizes: "512x512", type: "image/png", purpose: "maskable" },
|
||||
{ src: iconUrl("/icon-192.png"), sizes: "192x192", type: "image/png" },
|
||||
{ src: iconUrl("/icon-512.png"), sizes: "512x512", type: "image/png" },
|
||||
{ src: iconUrl("/icon-512-maskable.png"), sizes: "512x512", type: "image/png", purpose: "maskable" },
|
||||
],
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
import { readFile } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { ImageResponse } from "next/og";
|
||||
import sharp from "sharp";
|
||||
import { publicDedication } from "@/lib/dedication";
|
||||
import { readPhoto } from "@/lib/photos";
|
||||
import { STARTUP_SIZES } from "@/lib/startup-sizes";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
// Startbild der Web-App (26.11.35): iOS zeigt es, solange die App vom
|
||||
// Home-Bildschirm lädt — keine künstliche Pause. foodplanhero, „PLAN. COOK.
|
||||
// SMILE.“ und, wenn hochgeladen, Maike im grünen Ring mit „by Maike“.
|
||||
//
|
||||
// Farben als Hex, weil der Bildbauer kein OKLCH kennt — umgerechnet aus den
|
||||
// Token in app/globals.css (--background, --foreground, --hero).
|
||||
const BG = "#fefdff";
|
||||
const FG = "#1d1c23";
|
||||
const HERO = "#3f704b";
|
||||
|
||||
const fonts = (async () => {
|
||||
const dir = path.join(process.cwd(), "lib", "brand-fonts");
|
||||
const [bold, medium, hand] = await Promise.all(
|
||||
["poppins-latin-700-normal.woff", "poppins-latin-500-normal.woff", "caveat-latin-400-normal.woff"].map((f) => readFile(path.join(dir, f))),
|
||||
);
|
||||
return [
|
||||
{ name: "Poppins", data: bold!, weight: 700 as const, style: "normal" as const },
|
||||
{ name: "Poppins", data: medium!, weight: 500 as const, style: "normal" as const },
|
||||
{ name: "Caveat", data: hand!, weight: 400 as const, style: "normal" as const },
|
||||
];
|
||||
})();
|
||||
|
||||
export async function GET(_: Request, { params }: { params: Promise<{ size: string }> }) {
|
||||
const { size } = await params;
|
||||
const match = STARTUP_SIZES.find(([w, h]) => size === `${w}x${h}`);
|
||||
if (!match) return new Response("not found", { status: 404 });
|
||||
const [width, height, , , dpr] = match;
|
||||
const unit = dpr; // CSS-Pixel → Bildpixel
|
||||
const d = await publicDedication().catch(() => null);
|
||||
let photo: string | null = null;
|
||||
if (d?.photo) {
|
||||
const raw = await readPhoto(d.photo).catch(() => null);
|
||||
if (raw) photo = `data:image/png;base64,${(await sharp(raw).resize(240 * unit, 240 * unit, { fit: "cover" }).png().toBuffer()).toString("base64")}`;
|
||||
}
|
||||
const name = d?.name ?? "Maike";
|
||||
return new ImageResponse(
|
||||
(
|
||||
<div style={{ width, height, background: BG, display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", gap: 18 * unit }}>
|
||||
<div style={{ display: "flex", fontFamily: "Poppins", fontWeight: 700, fontSize: 44 * unit, color: FG, letterSpacing: -0.5 * unit }}>
|
||||
foodplan<span style={{ color: HERO }}>hero</span>
|
||||
</div>
|
||||
<div style={{ display: "flex", fontFamily: "Poppins", fontWeight: 500, fontSize: 14 * unit, color: FG, letterSpacing: 3.5 * unit }}>PLAN. COOK. SMILE.</div>
|
||||
{photo ? (
|
||||
<div style={{ display: "flex", flexDirection: "column", alignItems: "center", marginTop: 28 * unit }}>
|
||||
{/* eslint-disable-next-line @next/next/no-img-element -- Bildbauer, kein DOM */}
|
||||
<img src={photo} width={180 * unit} height={180 * unit} style={{ borderRadius: 9999, border: `${6 * unit}px solid ${HERO}`, objectFit: "cover" }} alt="" />
|
||||
<div style={{ display: "flex", fontFamily: "Caveat", fontSize: 40 * unit, color: FG, marginTop: -10 * unit, transform: "rotate(5.31deg)" }}>by {name}</div>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
),
|
||||
{ width, height, fonts: await fonts, headers: { "cache-control": "public, max-age=3600" } },
|
||||
);
|
||||
}
|
||||
@@ -1,13 +1,29 @@
|
||||
import Image from "next/image";
|
||||
import { Portrait, Slogan, Wordmark } from "@/components/brand/brand";
|
||||
|
||||
// Rahmen für Einrichten, Anmelden und Einladung: Symbol, Titel, Text, Inhalt.
|
||||
export function AuthShell({ title, intro, children }: { title: string; intro?: string; children?: React.ReactNode }) {
|
||||
// Rahmen für Einrichten, Anmelden und Einladung — alles mittig, Zeilen ausgeglichen
|
||||
// (text-balance, Kai 7.11.2026: kein „an.“ allein in der Zeile): foodplanhero mit Slogan (seit
|
||||
// 26.11.35 statt des Symbols), wo es eins gibt Maikes Porträt, dann Titel, Text, Inhalt.
|
||||
export function AuthShell({
|
||||
title,
|
||||
intro,
|
||||
portrait,
|
||||
children,
|
||||
}: {
|
||||
title: string;
|
||||
intro?: string;
|
||||
portrait?: { src: string; name: string } | null;
|
||||
children?: React.ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<main className="mx-auto flex min-h-dvh w-full max-w-sm flex-col justify-center gap-6 px-4 py-10">
|
||||
<div className="flex flex-col items-center gap-4 text-center">
|
||||
<Image src="/icon.svg" alt="" width={56} height={56} priority />
|
||||
<h1 className="text-4xl leading-tight">{title}</h1>
|
||||
{intro ? <p className="text-muted-foreground">{intro}</p> : null}
|
||||
<p className="flex flex-col items-center gap-2">
|
||||
<Wordmark className="text-4xl" />
|
||||
<Slogan />
|
||||
</p>
|
||||
{portrait ? <Portrait src={portrait.src} name={portrait.name} size={120} className="my-2" /> : null}
|
||||
<h1 className="text-balance text-4xl leading-tight">{title}</h1>
|
||||
{intro ? <p className="mx-auto max-w-[34ch] text-balance text-muted-foreground">{intro}</p> : null}
|
||||
</div>
|
||||
{children}
|
||||
</main>
|
||||
|
||||
@@ -42,7 +42,7 @@ export function InviteForm({ token, suggestedName, askName }: { token: string; s
|
||||
<Button type="submit" size="lg" disabled={busy}>
|
||||
{busy ? t("working") : t("invite.submit")}
|
||||
</Button>
|
||||
<p className="text-sm text-muted-foreground">{t("setup.passkeyHint")}</p>
|
||||
<p className="mx-auto max-w-[36ch] text-balance text-center text-sm text-muted-foreground">{t("setup.passkeyHint")}</p>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -31,7 +31,7 @@ export function LoginButton() {
|
||||
<KeyRound aria-hidden />
|
||||
{busy ? t("working") : t("login.submit")}
|
||||
</Button>
|
||||
<p className="text-sm text-muted-foreground">{t("login.noPasskey")}</p>
|
||||
<p className="mx-auto max-w-[36ch] text-balance text-center text-sm text-muted-foreground">{t("login.noPasskey")}</p>
|
||||
<Link href="/wiederherstellen" className="inline-flex min-h-11 items-center self-center text-sm underline underline-offset-4">
|
||||
{t("login.lost")}
|
||||
</Link>
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
"use client";
|
||||
|
||||
import Link from "next/link";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { useEffect, useState } from "react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { ErrorNotice } from "@/components/ui/notice";
|
||||
|
||||
type State = { kind: "ready"; purpose: "login" | "verify"; token: string } | { kind: "expired" } | { kind: "verified" } | { kind: "loading" };
|
||||
|
||||
// Der Link aus der Mail (26.11.40): Der Token steht hinter # und geht nie an den
|
||||
// Server, bis die Person tippt — ein Mail-Scanner, der nur abruft, verbraucht ihn nicht.
|
||||
export function MailLink() {
|
||||
const t = useTranslations("auth");
|
||||
const router = useRouter();
|
||||
const [state, setState] = useState<State>({ kind: "loading" });
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const m = window.location.hash.match(/^#(login|verify)=([A-Za-z0-9_-]{20,100})$/);
|
||||
// Aus der Adresszeile nehmen: kein Token im Verlauf, kein zweites Einlösen beim Neuladen.
|
||||
history.replaceState(null, "", window.location.pathname);
|
||||
setState(m ? { kind: "ready", purpose: m[1] as "login" | "verify", token: m[2]! } : { kind: "expired" });
|
||||
}, []);
|
||||
|
||||
async function go() {
|
||||
if (state.kind !== "ready") return;
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
const res = await fetch("/api/auth/mail/verify", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ token: state.token }),
|
||||
}).catch(() => null);
|
||||
setBusy(false);
|
||||
if (res?.ok) {
|
||||
const { purpose } = await res.json();
|
||||
if (purpose === "login") router.replace("/");
|
||||
else setState({ kind: "verified" });
|
||||
return;
|
||||
}
|
||||
if (res?.status === 410) return setState({ kind: "expired" });
|
||||
setError(res?.status === 429 ? "tooMany" : "unknown");
|
||||
}
|
||||
|
||||
if (state.kind === "loading") return null;
|
||||
if (state.kind === "expired") {
|
||||
return (
|
||||
<div className="flex flex-col items-center gap-4 text-center">
|
||||
<h1 className="text-balance text-4xl leading-tight">{t("mailLink.expiredTitle")}</h1>
|
||||
<p className="mx-auto max-w-[34ch] text-balance text-muted-foreground">{t("mailLink.expiredIntro")}</p>
|
||||
<Button asChild size="lg" className="self-stretch">
|
||||
<Link href="/anmelden">{t("mailLink.back")}</Link>
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
if (state.kind === "verified") {
|
||||
return (
|
||||
<div className="flex flex-col items-center gap-4 text-center">
|
||||
<h1 className="text-balance text-4xl leading-tight">{t("mailLink.verified")}</h1>
|
||||
<Button asChild size="lg" className="self-stretch">
|
||||
<Link href="/mehr">{t("mailLink.toMore")}</Link>
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
const login = state.purpose === "login";
|
||||
return (
|
||||
<div className="flex flex-col items-center gap-4 text-center">
|
||||
<h1 className="text-balance text-4xl leading-tight">{t(login ? "mailLink.loginTitle" : "mailLink.verifyTitle")}</h1>
|
||||
<p className="mx-auto max-w-[34ch] text-balance text-muted-foreground">{t(login ? "mailLink.loginIntro" : "mailLink.verifyIntro")}</p>
|
||||
{error ? <ErrorNotice className="self-stretch">{t(`errors.${error}`)}</ErrorNotice> : null}
|
||||
<Button size="lg" className="self-stretch" onClick={go} disabled={busy}>
|
||||
{busy ? t("working") : t(login ? "mailLink.loginSubmit" : "mailLink.verifySubmit")}
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
"use client";
|
||||
|
||||
import { Mail } from "lucide-react";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { useId, useState } from "react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { ErrorNotice } from "@/components/ui/notice";
|
||||
|
||||
// Link per Mail anfordern (26.11.40). Die Antwort sagt immer dasselbe — ob es die
|
||||
// Adresse gibt, verrät sie nicht.
|
||||
export function MailLogin() {
|
||||
const t = useTranslations("auth");
|
||||
const id = useId();
|
||||
const [open, setOpen] = useState(false);
|
||||
const [email, setEmail] = useState("");
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [sent, setSent] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
async function submit(event: React.FormEvent) {
|
||||
event.preventDefault();
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
const res = await fetch("/api/auth/mail/request", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ email }),
|
||||
}).catch(() => null);
|
||||
setBusy(false);
|
||||
if (res?.ok) return setSent(true);
|
||||
const key = res ? ((await res.json().catch(() => ({}))).error as string | undefined) : undefined;
|
||||
setError(key === "tooMany" || key === "invalid" ? key : "unknown");
|
||||
}
|
||||
|
||||
if (!open) {
|
||||
return (
|
||||
<Button type="button" variant="outline" size="lg" onClick={() => setOpen(true)}>
|
||||
<Mail aria-hidden />
|
||||
{t("login.mailToggle")}
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
if (sent) {
|
||||
return (
|
||||
<p role="status" className="mx-auto max-w-[34ch] text-balance rounded-xl border border-border px-4 py-3 text-center text-sm">
|
||||
{t("login.mailSent")}
|
||||
</p>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<form onSubmit={submit} className="flex flex-col gap-3">
|
||||
<Label htmlFor={id}>{t("login.mailLabel")}</Label>
|
||||
<Input id={id} type="email" autoComplete="email" inputMode="email" required value={email} onChange={(e) => setEmail(e.target.value)} />
|
||||
{error ? <ErrorNotice>{t(`errors.${error}`)}</ErrorNotice> : null}
|
||||
<Button type="submit" size="lg" disabled={busy || !email.trim()}>
|
||||
<Mail aria-hidden />
|
||||
{busy ? t("working") : t("login.mailSubmit")}
|
||||
</Button>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -50,7 +50,7 @@ export function RecoveryForm() {
|
||||
{busy ? t("working") : t("recovery.submit")}
|
||||
</Button>
|
||||
</form>
|
||||
<p className="text-sm text-muted-foreground">{t("recovery.others")}</p>
|
||||
<p className="mx-auto max-w-[36ch] text-balance text-center text-sm text-muted-foreground">{t("recovery.others")}</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -48,7 +48,7 @@ export function SetupForm() {
|
||||
<Button type="submit" size="lg" disabled={busy}>
|
||||
{busy ? t("working") : t("setup.submit")}
|
||||
</Button>
|
||||
<p className="text-sm text-muted-foreground">{t("setup.passkeyHint")}</p>
|
||||
<p className="mx-auto max-w-[36ch] text-balance text-center text-sm text-muted-foreground">{t("setup.passkeyHint")}</p>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
// foodplanhero (Kai für Maike, 26.11.35): Wortmarke, Slogan und Maikes Porträt —
|
||||
// wie in Kais Figma-Entwurf: Poppins Bold, „hero“ in Grün; „PLAN. COOK. SMILE.“ in
|
||||
// Poppins Medium mit 25 % Abstand; „by Maike“ in Caveat, leicht gedreht.
|
||||
|
||||
export function Wordmark({ className }: { className?: string }) {
|
||||
return (
|
||||
<span className={cn("font-brand font-bold leading-none tracking-tight", className)}>
|
||||
foodplan<span className="text-hero">hero</span>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
export type SloganStep = "plan" | "cook" | "smile";
|
||||
const WORDS: SloganStep[] = ["plan", "cook", "smile"];
|
||||
|
||||
/** „PLAN. COOK. SMILE.“ — mit active ist das Wort hervorgehoben, das gerade passiert. */
|
||||
export function Slogan({ active, className }: { active?: SloganStep; className?: string }) {
|
||||
return (
|
||||
<span className={cn("font-brand text-xs font-medium uppercase tracking-[0.25em]", className)}>
|
||||
{WORDS.map((w, i) => (
|
||||
<span key={w} className={cn(active && w !== active && "text-muted-foreground", active === w && "text-hero")}>
|
||||
{w}.{i < WORDS.length - 1 ? " " : ""}
|
||||
</span>
|
||||
))}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
/** Maike im Kreis mit grünem Ring, darunter „by Maike“ in Schreibschrift. */
|
||||
export function Portrait({ src, name, size = 128, className }: { src: string; name: string; size?: number; className?: string }) {
|
||||
return (
|
||||
<figure className={cn("relative mx-auto flex flex-col items-center", className)} style={{ width: size }}>
|
||||
{/* eslint-disable-next-line @next/next/no-img-element -- eigenes Foto von der Box */}
|
||||
<img src={src} alt={name} width={size} height={size} className="aspect-square w-full rounded-full border-4 border-hero object-cover" />
|
||||
<figcaption className="-mt-3 rotate-[5.31deg] font-hand text-3xl leading-none text-foreground">by {name}</figcaption>
|
||||
</figure>
|
||||
);
|
||||
}
|
||||
@@ -158,7 +158,7 @@ export function CookingMode({
|
||||
|
||||
{error ? <ErrorNotice>{t("error")}</ErrorNotice> : null}
|
||||
|
||||
<div className="sticky bottom-[var(--nav-space)] z-10 flex gap-2 bg-background py-2">
|
||||
<div className="kb-shift sticky bottom-[var(--nav-space)] z-10 flex gap-2 bg-background py-2">
|
||||
<Button type="button" variant="outline" size="lg" disabled={index < 0} onClick={() => go(-1)} aria-label={t("back")}>
|
||||
<ChevronLeft aria-hidden />
|
||||
</Button>
|
||||
|
||||
@@ -1,19 +1,29 @@
|
||||
"use client";
|
||||
|
||||
import { Pause, Play, Timer as TimerIcon } from "lucide-react";
|
||||
import { useLocale, useTranslations } from "next-intl";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { useEffect, useState } from "react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { labelFor } from "@/lib/ingredient-name";
|
||||
import type { Section } from "@/lib/recipe-style";
|
||||
import { timerFromText } from "@/lib/timer";
|
||||
import { formatQuantity, type BaseUnit } from "@/lib/units";
|
||||
import { type BaseUnit, type KitchenUnit } from "@/lib/units";
|
||||
import { useKitchenAmount } from "@/lib/use-kitchen-amount";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
// Gemeinsames von Kochmodus und Präsentation (26.11.28): Display an lassen,
|
||||
// Timer gegen die Uhr, Mengen in der Portionszahl.
|
||||
|
||||
export type Ingredient = { ingredientId: string; name: string; forms: { one: string; other: string } | null; qtyPerPortion: number; unit: BaseUnit; note: string | null };
|
||||
export type Ingredient = {
|
||||
ingredientId: string;
|
||||
name: string;
|
||||
forms: { one: string; other: string } | null;
|
||||
qtyPerPortion: number;
|
||||
unit: BaseUnit;
|
||||
note: string | null;
|
||||
displayUnit?: KitchenUnit | null;
|
||||
packSize?: number | null;
|
||||
};
|
||||
export type Step = { section: Section; text: string; timerSeconds: number | null; ingredientIds: string[]; timerFrom?: string };
|
||||
export type Running = { step: number; endsAt: number | null; left: number; done: boolean };
|
||||
|
||||
@@ -98,12 +108,10 @@ export const withTextTimer = (s: Step): Step => ({ ...s, timerSeconds: s.timerSe
|
||||
|
||||
/** „250 g“ in der Portionszahl, und der passende Name (Einzahl/Mehrzahl). */
|
||||
export function useAmount(portions: number) {
|
||||
const locale = useLocale();
|
||||
const kitchen = useKitchenAmount();
|
||||
return {
|
||||
amount: (i: Ingredient) => {
|
||||
const f = formatQuantity(i.qtyPerPortion * portions, i.unit, locale);
|
||||
return `${f.amount}${f.unit ? ` ${f.unit}` : ""}`;
|
||||
},
|
||||
// „2 EL (30 ml)“, „400 g (1 Dose)“ — lib/units.ts formatKitchen (26.11.39).
|
||||
amount: (i: Ingredient) => kitchen.text(i, i.qtyPerPortion * portions),
|
||||
label: (i: Ingredient) => labelFor(i, i.qtyPerPortion * portions),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ import { useRef, useState } from "react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { Slogan } from "@/components/brand/brand";
|
||||
|
||||
type ToRate = { slotId: string; dishId: string; title: string; cookName: string | null; isCook: boolean; thanked: boolean };
|
||||
|
||||
@@ -43,7 +44,10 @@ export function RateCard({ item }: { item: ToRate }) {
|
||||
|
||||
return (
|
||||
<article className="flex flex-col gap-3 rounded-2xl bg-muted p-5" aria-labelledby={`rate-${item.slotId}`}>
|
||||
<p className="eyebrow">{t("eyebrow")}</p>
|
||||
<p className="flex flex-wrap items-baseline justify-between gap-x-3 gap-y-1">
|
||||
<span className="eyebrow">{t("eyebrow")}</span>
|
||||
<Slogan active="smile" />
|
||||
</p>
|
||||
<h2 id={`rate-${item.slotId}`} className="text-2xl leading-snug">
|
||||
{t("question", { title: item.title })}
|
||||
</h2>
|
||||
@@ -81,7 +85,6 @@ export function RateCard({ item }: { item: ToRate }) {
|
||||
ref={file}
|
||||
type="file"
|
||||
accept="image/*"
|
||||
capture="environment"
|
||||
className="sr-only"
|
||||
tabIndex={-1}
|
||||
aria-hidden
|
||||
|
||||
@@ -24,19 +24,24 @@ export function PhotoButton({
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<"photo" | "full" | null>(null);
|
||||
|
||||
async function upload(file: File) {
|
||||
// Mehrere aus der Mediathek (26.11.43): nacheinander, bis fünf erreicht sind.
|
||||
async function upload(files: File[]) {
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
const form = new FormData();
|
||||
form.append("photo", file);
|
||||
const res = await fetch(`/api/dishes/${id}/photos`, {
|
||||
method: "POST",
|
||||
body: form,
|
||||
});
|
||||
let failed: "photo" | "full" | null = null;
|
||||
for (const file of files.slice(0, Math.max(0, 5 - count))) {
|
||||
const form = new FormData();
|
||||
form.append("photo", file);
|
||||
const res = await fetch(`/api/dishes/${id}/photos`, { method: "POST", body: form }).catch(() => null);
|
||||
if (!res?.ok) {
|
||||
failed = res && (await res.json().catch(() => ({}))).error === "full" ? "full" : "photo";
|
||||
break;
|
||||
}
|
||||
}
|
||||
setBusy(false);
|
||||
if (input.current) input.current.value = "";
|
||||
if (res.ok) router.refresh();
|
||||
else setError((await res.json().catch(() => ({}))).error === "full" ? "full" : "photo");
|
||||
setError(failed);
|
||||
router.refresh();
|
||||
}
|
||||
|
||||
return (
|
||||
@@ -45,11 +50,12 @@ export function PhotoButton({
|
||||
ref={input}
|
||||
type="file"
|
||||
accept="image/*"
|
||||
capture="environment"
|
||||
// Ohne capture: Das iPhone bietet Fotomediathek, Kamera und Dateien an (Kai, 26.11.43).
|
||||
multiple
|
||||
className="sr-only"
|
||||
tabIndex={-1}
|
||||
aria-hidden
|
||||
onChange={(e) => e.target.files?.[0] && upload(e.target.files[0])}
|
||||
onChange={(e) => e.target.files?.length && upload(Array.from(e.target.files))}
|
||||
/>
|
||||
<Button
|
||||
variant="secondary"
|
||||
|
||||
@@ -2,20 +2,23 @@
|
||||
|
||||
import { ArrowDown, ArrowUp, Plus, Sparkles, X, Package, Wand2 } from "lucide-react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { useLocale, useTranslations } from "next-intl";
|
||||
import { useEffect, useId, useRef, useState } from "react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { ErrorNotice } from "@/components/ui/notice";
|
||||
import { BASES, TAGS } from "@/lib/categories";
|
||||
import { parseNumber, type BaseUnit } from "@/lib/units";
|
||||
import { formatQuantity, isPackKind, parseNumber, type BaseUnit } from "@/lib/units";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { SECTIONS, type Section } from "@/lib/recipe-style";
|
||||
|
||||
export type Picked = { id: string; name: string; unit: BaseUnit };
|
||||
import { IngredientPicker, type Picked } from "./ingredient-picker";
|
||||
import { PackSize } from "./pack-size";
|
||||
export { IngredientPicker, type Picked };
|
||||
// Produkt (optional): Name, Packung in der Einheit der Zeile, Kochzeit laut Packung.
|
||||
type Row = { key: number; ingredient: Picked | null; qty: string; unit: string; note: string; product: string; pack: string; cook: string; open: boolean };
|
||||
// inherited: Lieblingsprodukt des Haushalts für diese Zutat (26.11.38); remember: dieses Produkt für alle Gerichte merken.
|
||||
type Row = { key: number; ingredient: Picked | null; qty: string; unit: string; note: string; product: string; pack: string; cook: string; open: boolean; remember?: boolean; inherited?: string | null };
|
||||
type StepRow = { key: number; text: string; timer: string; section: Section | "" };
|
||||
|
||||
export type DishFormValue = {
|
||||
@@ -32,7 +35,7 @@ export type DishFormValue = {
|
||||
qty: number | null;
|
||||
unit?: string | null;
|
||||
note: string | null;
|
||||
product?: { name: string; pack: number | null; cookMinutes: number | null } | null;
|
||||
product?: { name: string; pack: number | null; cookMinutes: number | null; fromHousehold?: boolean } | null;
|
||||
}[];
|
||||
steps: { text: string; timerMinutes: number | null; section?: Section | null }[];
|
||||
sourceUrl?: string | null;
|
||||
@@ -51,6 +54,19 @@ const UNITS_FOR: Record<BaseUnit, string[]> = {
|
||||
piece: ["piece"],
|
||||
};
|
||||
|
||||
/** Maße für eine Zutat: die ihrer Basiseinheit und, wenn sie eins hat, ihr Gebinde (26.11.39). */
|
||||
const unitsFor = (p: Picked | null) => {
|
||||
const list = UNITS_FOR[p?.unit ?? "g"];
|
||||
return p?.packKind && p.packSize ? [...list, p.packKind] : list;
|
||||
};
|
||||
|
||||
/**
|
||||
* Vorgewählte Einheit beim Wählen einer Zutat: ihr Löffelmaß (Olivenöl in EL), sonst
|
||||
* die Basiseinheit. Ein Gebinde wird angeboten, aber nie vorgewählt — wer nach
|
||||
* „Kokosmilch“ gleich „400“ tippt, meint Milliliter, nicht 400 Dosen.
|
||||
*/
|
||||
const preferredUnit = (p: Picked) => (p.kitchenUnit && unitsFor(p).includes(p.kitchenUnit) ? p.kitchenUnit : p.unit);
|
||||
|
||||
let counter = 0;
|
||||
const next = () => ++counter;
|
||||
|
||||
@@ -61,6 +77,11 @@ const formatQty = (n: number) => String(Math.round(n * 100) / 100).replace(".",
|
||||
// Portion um (lib/dishes.ts).
|
||||
export function DishForm({ initial }: { initial?: DishFormValue }) {
|
||||
const t = useTranslations("dishes");
|
||||
const locale = useLocale();
|
||||
const sizeText = (size: number, unit: BaseUnit) => {
|
||||
const f = formatQuantity(size, unit, locale);
|
||||
return `${f.amount}${f.unit ? ` ${f.unit}` : ""}`;
|
||||
};
|
||||
const router = useRouter();
|
||||
const [title, setTitle] = useState(initial?.title ?? "");
|
||||
const [portions, setPortions] = useState(String(initial?.portions ?? 4));
|
||||
@@ -74,12 +95,14 @@ export function DishForm({ initial }: { initial?: DishFormValue }) {
|
||||
key: next(),
|
||||
ingredient: i.ingredient,
|
||||
qty: i.qty !== null ? formatQty(i.qty) : "",
|
||||
unit: i.unit && UNITS_FOR[i.ingredient.unit].includes(i.unit) ? i.unit : i.ingredient.unit,
|
||||
unit: i.unit && unitsFor(i.ingredient).includes(i.unit) ? i.unit : i.ingredient.unit,
|
||||
note: i.note ?? "",
|
||||
product: i.product?.name ?? "",
|
||||
pack: i.product?.pack ? formatQty(i.product.pack) : "",
|
||||
cook: i.product?.cookMinutes ? String(i.product.cookMinutes) : "",
|
||||
open: !!i.product,
|
||||
// Ein geerbtes Lieblingsprodukt füllt die Felder nicht — leer heißt: es gilt weiter.
|
||||
product: i.product && !i.product.fromHousehold ? i.product.name : "",
|
||||
pack: i.product?.pack && !i.product.fromHousehold ? formatQty(i.product.pack) : "",
|
||||
cook: i.product?.cookMinutes && !i.product.fromHousehold ? String(i.product.cookMinutes) : "",
|
||||
open: !!i.product && !i.product.fromHousehold,
|
||||
inherited: i.product?.fromHousehold ? i.product.name : null,
|
||||
}))
|
||||
: [{ key: next(), ingredient: null, qty: "", unit: "g", note: "", product: "", pack: "", cook: "", open: false }],
|
||||
);
|
||||
@@ -152,6 +175,7 @@ export function DishForm({ initial }: { initial?: DishFormValue }) {
|
||||
name: r.product.trim(),
|
||||
pack: r.pack.trim() ? (parseNumber(r.pack) ?? null) : null,
|
||||
cookMinutes: r.cook.trim() ? Math.round(parseNumber(r.cook) ?? 0) || null : null,
|
||||
remember: !!r.remember,
|
||||
}
|
||||
: null,
|
||||
}));
|
||||
@@ -277,7 +301,7 @@ export function DishForm({ initial }: { initial?: DishFormValue }) {
|
||||
{rows.map((row) => (
|
||||
<li key={row.key} className="flex flex-col gap-2 rounded-2xl bg-muted p-3">
|
||||
<div className="flex items-start gap-2">
|
||||
<IngredientPicker value={row.ingredient} onPick={(p) => update(row.key, { ingredient: p, unit: p.unit })} />
|
||||
<IngredientPicker canCreate value={row.ingredient} onPick={(p) => update(row.key, { ingredient: p, unit: preferredUnit(p), inherited: row.product ? row.inherited : (p.product ?? null) })} />
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
@@ -303,13 +327,26 @@ export function DishForm({ initial }: { initial?: DishFormValue }) {
|
||||
onChange={(e) => update(row.key, { unit: e.target.value })}
|
||||
className="min-h-11 rounded-xl border border-border bg-background px-3 text-base"
|
||||
>
|
||||
{UNITS_FOR[row.ingredient?.unit ?? "g"].map((u) => (
|
||||
{unitsFor(row.ingredient).map((u) => (
|
||||
<option key={u} value={u}>
|
||||
{t(`form.units.${u}`)}
|
||||
{/* Ein Gebinde nennt seine Größe gleich mit: „Dose (400 g)“. */}
|
||||
{isPackKind(u) && row.ingredient?.packSize
|
||||
? t("form.unitWithSize", { unit: t(`form.units.${u}`), size: sizeText(row.ingredient.packSize, row.ingredient.unit) })
|
||||
: t(`form.units.${u}`)}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
{row.ingredient && isPackKind(row.unit) && row.ingredient.packSize ? (
|
||||
<PackSize
|
||||
ingredient={row.ingredient}
|
||||
kind={row.unit}
|
||||
sizeText={sizeText}
|
||||
onSaved={(size) =>
|
||||
setRows((rs) => rs.map((r) => (r.ingredient?.id === row.ingredient!.id ? { ...r, ingredient: { ...r.ingredient!, packSize: size } } : r)))
|
||||
}
|
||||
/>
|
||||
) : null}
|
||||
<Input
|
||||
aria-label={t("form.note")}
|
||||
placeholder={t("form.notePlaceholder")}
|
||||
@@ -333,7 +370,7 @@ export function DishForm({ initial }: { initial?: DishFormValue }) {
|
||||
<div className="grid grid-cols-2 gap-2">
|
||||
<div className="flex flex-col gap-1">
|
||||
<Label htmlFor={`pack-${row.key}`} className="text-sm">
|
||||
{t("form.productPack", { unit: t(`form.units.${row.unit}`) })}
|
||||
{t("form.productPack", { unit: t(`form.units.${isPackKind(row.unit) ? (row.ingredient?.unit ?? "g") : row.unit}`) })}
|
||||
</Label>
|
||||
<Input id={`pack-${row.key}`} inputMode="decimal" value={row.pack} onChange={(e) => update(row.key, { pack: e.target.value })} />
|
||||
</div>
|
||||
@@ -345,12 +382,19 @@ export function DishForm({ initial }: { initial?: DishFormValue }) {
|
||||
</div>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">{t("form.productHint")}</p>
|
||||
<label className="flex min-h-11 items-center gap-3 text-sm">
|
||||
<input type="checkbox" checked={!!row.remember} onChange={(e) => update(row.key, { remember: e.target.checked })} className="size-5 accent-primary" />
|
||||
{t("form.rememberProduct", { name: row.ingredient?.name ?? "" })}
|
||||
</label>
|
||||
</fieldset>
|
||||
) : (
|
||||
<Button type="button" variant="ghost" className="self-start" disabled={!row.ingredient} onClick={() => update(row.key, { open: true })}>
|
||||
<Package aria-hidden />
|
||||
{t("form.addProduct")}
|
||||
</Button>
|
||||
<div className="flex flex-col gap-1">
|
||||
{row.inherited ? <p className="text-sm text-muted-foreground">{t("form.inheritedProduct", { product: row.inherited })}</p> : null}
|
||||
<Button type="button" variant="ghost" className="self-start" disabled={!row.ingredient} onClick={() => update(row.key, { open: true })}>
|
||||
<Package aria-hidden />
|
||||
{row.inherited ? t("form.otherProduct") : t("form.addProduct")}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</li>
|
||||
))}
|
||||
@@ -447,7 +491,7 @@ export function DishForm({ initial }: { initial?: DishFormValue }) {
|
||||
</section>
|
||||
|
||||
{error ? <ErrorNotice>{t(`form.errors.${error}`)}</ErrorNotice> : null}
|
||||
<div className="sticky bottom-[var(--nav-space)] z-10 flex gap-2 bg-background py-2">
|
||||
<div className="kb-shift sticky bottom-[var(--nav-space)] z-10 flex gap-2 bg-background py-2">
|
||||
<Button type="button" variant="outline" onClick={() => router.back()}>
|
||||
{t("form.cancel")}
|
||||
</Button>
|
||||
@@ -461,67 +505,3 @@ export function DishForm({ initial }: { initial?: DishFormValue }) {
|
||||
|
||||
// Zutat suchen und wählen. Tippen sucht in der Sprache der Person, auch über
|
||||
// Synonyme (lib/ingredient-search.ts); ein Tipp auf einen Treffer wählt ihn.
|
||||
export function IngredientPicker({ value, onPick }: { value: Picked | null; onPick: (p: Picked) => void }) {
|
||||
const t = useTranslations("dishes.form");
|
||||
const id = useId();
|
||||
const [query, setQuery] = useState(value?.name ?? "");
|
||||
const [hits, setHits] = useState<Picked[]>([]);
|
||||
const [open, setOpen] = useState(false);
|
||||
const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open || !query.trim() || query === value?.name) {
|
||||
setHits([]);
|
||||
return;
|
||||
}
|
||||
if (timer.current) clearTimeout(timer.current);
|
||||
timer.current = setTimeout(async () => {
|
||||
const res = await fetch(`/api/ingredients?q=${encodeURIComponent(query)}`);
|
||||
if (res.ok) setHits(await res.json());
|
||||
}, 150);
|
||||
}, [query, open, value?.name]);
|
||||
|
||||
return (
|
||||
<div className="relative flex-1">
|
||||
<Input
|
||||
id={id}
|
||||
role="combobox"
|
||||
aria-expanded={open && hits.length > 0}
|
||||
aria-controls={`${id}-list`}
|
||||
aria-autocomplete="list"
|
||||
aria-label={t("searchIngredient")}
|
||||
placeholder={t("searchIngredient")}
|
||||
value={query}
|
||||
autoComplete="off"
|
||||
onFocus={() => setOpen(true)}
|
||||
onChange={(e) => {
|
||||
setQuery(e.target.value);
|
||||
setOpen(true);
|
||||
}}
|
||||
/>
|
||||
{open && query.trim() && query !== value?.name ? (
|
||||
<ul id={`${id}-list`} role="listbox" className="absolute inset-x-0 top-full z-20 mt-1 overflow-hidden rounded-xl border border-border bg-card shadow-lg">
|
||||
{hits.length ? (
|
||||
hits.map((h) => (
|
||||
<li key={h.id} role="option" aria-selected={value?.id === h.id}>
|
||||
<button
|
||||
type="button"
|
||||
className="flex min-h-11 w-full items-center px-4 text-left hover:bg-muted"
|
||||
onClick={() => {
|
||||
onPick(h);
|
||||
setQuery(h.name);
|
||||
setOpen(false);
|
||||
}}
|
||||
>
|
||||
{h.name}
|
||||
</button>
|
||||
</li>
|
||||
))
|
||||
) : (
|
||||
<li className="px-4 py-3 text-sm text-muted-foreground">{t("noHits")}</li>
|
||||
)}
|
||||
</ul>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,208 @@
|
||||
"use client";
|
||||
|
||||
import { Plus } from "lucide-react";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { useEffect, useId, useRef, useState } from "react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { ErrorNotice } from "@/components/ui/notice";
|
||||
import { CATEGORIES } from "@/lib/categories";
|
||||
import { normalize } from "@/lib/ingredient-search";
|
||||
import type { BaseUnit, KitchenUnit, PackKind } from "@/lib/units";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
export type Picked = {
|
||||
id: string;
|
||||
name: string;
|
||||
unit: BaseUnit;
|
||||
group?: boolean;
|
||||
product?: string | null;
|
||||
kitchenUnit?: KitchenUnit | null;
|
||||
packKind?: PackKind | null;
|
||||
packSize?: number | null;
|
||||
};
|
||||
type Hit = Picked & { kinds: number; parentId: string | null; own: boolean };
|
||||
|
||||
// Zutat suchen und wählen (26.11.38): Ein Oberbegriff („Pasta“) steht oben als
|
||||
// „beliebige Sorte“, seine Sorten eingerückt darunter. Findet die Suche nichts
|
||||
// Passendes, legt, wer Gerichte pflegt, eine eigene Zutat für den Haushalt an.
|
||||
export function IngredientPicker({ value, onPick, canCreate = false }: { value: Picked | null; onPick: (p: Picked) => void; canCreate?: boolean }) {
|
||||
const t = useTranslations("dishes.form");
|
||||
const ti = useTranslations("ingredients");
|
||||
const id = useId();
|
||||
const [query, setQuery] = useState(value?.name ?? "");
|
||||
const [hits, setHits] = useState<Hit[]>([]);
|
||||
const [open, setOpen] = useState(false);
|
||||
const [creating, setCreating] = useState(false);
|
||||
// Für welche Eingabe die Treffer gelten — „anlegen“ erst, wenn die Suche geantwortet hat.
|
||||
const [answered, setAnswered] = useState("");
|
||||
const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open || !query.trim() || query === value?.name) {
|
||||
setHits([]);
|
||||
return;
|
||||
}
|
||||
if (timer.current) clearTimeout(timer.current);
|
||||
timer.current = setTimeout(async () => {
|
||||
const res = await fetch(`/api/ingredients?q=${encodeURIComponent(query)}`);
|
||||
if (res.ok) {
|
||||
setHits(await res.json());
|
||||
setAnswered(query);
|
||||
}
|
||||
}, 150);
|
||||
}, [query, open, value?.name]);
|
||||
|
||||
const pick = (h: Picked) => {
|
||||
onPick({ id: h.id, name: h.name, unit: h.unit, group: h.group, product: h.product ?? null, kitchenUnit: h.kitchenUnit, packKind: h.packKind, packSize: h.packSize });
|
||||
setQuery(h.name);
|
||||
setOpen(false);
|
||||
setCreating(false);
|
||||
};
|
||||
const groupIds = new Set(hits.filter((h) => h.group).map((h) => h.id));
|
||||
const exact = hits.some((h) => normalize(h.name) === normalize(query));
|
||||
const offerCreate = canCreate && query.trim().length >= 2 && !exact && answered === query;
|
||||
|
||||
return (
|
||||
<div className="relative flex-1">
|
||||
<Input
|
||||
id={id}
|
||||
role="combobox"
|
||||
aria-expanded={open && hits.length > 0}
|
||||
aria-controls={`${id}-list`}
|
||||
aria-autocomplete="list"
|
||||
aria-label={t("searchIngredient")}
|
||||
placeholder={t("searchIngredient")}
|
||||
value={query}
|
||||
autoComplete="off"
|
||||
onFocus={() => setOpen(true)}
|
||||
onChange={(e) => {
|
||||
setQuery(e.target.value);
|
||||
setOpen(true);
|
||||
setCreating(false);
|
||||
}}
|
||||
/>
|
||||
{open && query.trim() && query !== value?.name && !creating ? (
|
||||
<ul id={`${id}-list`} role="listbox" className="absolute inset-x-0 top-full z-20 mt-1 max-h-96 overflow-y-auto rounded-xl border border-border bg-card shadow-lg">
|
||||
{hits.map((h) => {
|
||||
const member = !!h.parentId && groupIds.has(h.parentId);
|
||||
return (
|
||||
<li key={h.id} role="option" aria-selected={value?.id === h.id}>
|
||||
<button
|
||||
type="button"
|
||||
className={cn("flex min-h-11 w-full items-center justify-between gap-2 px-4 text-left hover:bg-muted", member && "pl-8", h.group && "font-semibold")}
|
||||
onClick={() => pick(h)}
|
||||
>
|
||||
<span>
|
||||
{h.name}
|
||||
{h.group ? <span className="font-normal text-muted-foreground"> · {ti("anyKind")}</span> : null}
|
||||
</span>
|
||||
{h.group ? (
|
||||
<span className="text-xs font-normal text-muted-foreground">{ti("kinds", { n: h.kinds })}</span>
|
||||
) : h.own ? (
|
||||
<span className="text-xs text-muted-foreground">{ti("ownBadge")}</span>
|
||||
) : null}
|
||||
</button>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
{!hits.length && !offerCreate ? <li className="px-4 py-3 text-sm text-muted-foreground">{t("noHits")}</li> : null}
|
||||
{offerCreate ? (
|
||||
<li role="option" aria-selected={false} className="border-t border-border">
|
||||
<button type="button" className="flex min-h-11 w-full items-center gap-2 px-4 text-left font-semibold text-accent hover:bg-muted" onClick={() => setCreating(true)}>
|
||||
<Plus aria-hidden className="size-4" />
|
||||
{ti("create", { name: query.trim() })}
|
||||
</button>
|
||||
</li>
|
||||
) : null}
|
||||
</ul>
|
||||
) : null}
|
||||
{creating ? <CreateIngredient name={query.trim()} onCancel={() => setCreating(false)} onCreated={pick} /> : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function CreateIngredient({ name: initial, onCancel, onCreated }: { name: string; onCancel: () => void; onCreated: (p: Picked) => void }) {
|
||||
const t = useTranslations("ingredients");
|
||||
const id = useId();
|
||||
const [name, setName] = useState(initial);
|
||||
const [unit, setUnit] = useState<BaseUnit>("g");
|
||||
const [groups, setGroups] = useState<Hit[]>([]);
|
||||
const [parentId, setParentId] = useState("");
|
||||
const [category, setCategory] = useState<string>("pasta_rice");
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
void fetch("/api/ingredients")
|
||||
.then((r) => (r.ok ? r.json() : []))
|
||||
.then(setGroups)
|
||||
.catch(() => undefined);
|
||||
}, []);
|
||||
|
||||
async function save() {
|
||||
setBusy(true);
|
||||
setError(false);
|
||||
const res = await fetch("/api/ingredients", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ name, unit, parentId: parentId || null, category }),
|
||||
}).catch(() => null);
|
||||
setBusy(false);
|
||||
if (!res?.ok) return setError(true);
|
||||
onCreated(await res.json());
|
||||
}
|
||||
|
||||
return (
|
||||
<div role="group" aria-label={t("title")} className="mt-2 flex flex-col gap-3 rounded-2xl border border-border bg-card p-4">
|
||||
<p className="font-semibold">{t("title")}</p>
|
||||
<div className="flex flex-col gap-1">
|
||||
<Label htmlFor={`${id}-name`}>{t("name")}</Label>
|
||||
<Input id={`${id}-name`} value={name} maxLength={60} onChange={(e) => setName(e.target.value)} />
|
||||
</div>
|
||||
<div className="grid grid-cols-[6.5rem_minmax(0,1fr)] gap-3">
|
||||
<div className="flex flex-col gap-1">
|
||||
<Label htmlFor={`${id}-unit`}>{t("unit")}</Label>
|
||||
<select id={`${id}-unit`} value={unit} onChange={(e) => setUnit(e.target.value as BaseUnit)} className="min-h-11 rounded-xl border border-border bg-background px-3">
|
||||
<option value="g">g</option>
|
||||
<option value="ml">ml</option>
|
||||
<option value="piece">Stück</option>
|
||||
</select>
|
||||
</div>
|
||||
<div className="flex flex-col gap-1">
|
||||
<Label htmlFor={`${id}-group`}>{t("group")}</Label>
|
||||
<select id={`${id}-group`} value={parentId} onChange={(e) => setParentId(e.target.value)} className="min-h-11 rounded-xl border border-border bg-background px-3">
|
||||
<option value="">{t("noGroup")}</option>
|
||||
{groups.map((g) => (
|
||||
<option key={g.id} value={g.id}>
|
||||
{g.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
{!parentId ? (
|
||||
<div className="flex flex-col gap-1">
|
||||
<Label htmlFor={`${id}-category`}>{t("category")}</Label>
|
||||
<select id={`${id}-category`} value={category} onChange={(e) => setCategory(e.target.value)} className="min-h-11 rounded-xl border border-border bg-background px-3">
|
||||
{CATEGORIES.map((c) => (
|
||||
<option key={c} value={c}>
|
||||
{t(`categories.${c}`)}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
) : null}
|
||||
{error ? <ErrorNotice>{t("error")}</ErrorNotice> : null}
|
||||
<div className="flex gap-2">
|
||||
<Button type="button" disabled={busy || !name.trim()} onClick={save}>
|
||||
{t("save")}
|
||||
</Button>
|
||||
<Button type="button" variant="ghost" onClick={onCancel}>
|
||||
{t("cancel")}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
"use client";
|
||||
|
||||
import { useTranslations } from "next-intl";
|
||||
import { useId, useState } from "react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { ErrorNotice } from "@/components/ui/notice";
|
||||
import { parseNumber, type BaseUnit, type PackKind } from "@/lib/units";
|
||||
|
||||
// Größe eines Gebindes (26.11.39): „1 Dose = 400 g“ — wer Gerichte pflegt, kann sie
|
||||
// für den Haushalt ändern („unsere Dose hat 500 g“). Gilt für alle Gerichte.
|
||||
export function PackSize({
|
||||
ingredient,
|
||||
kind,
|
||||
sizeText,
|
||||
onSaved,
|
||||
}: {
|
||||
ingredient: { id: string; unit: BaseUnit; packSize?: number | null };
|
||||
kind: PackKind;
|
||||
sizeText: (size: number, unit: BaseUnit) => string;
|
||||
onSaved: (size: number) => void;
|
||||
}) {
|
||||
const t = useTranslations("dishes.form");
|
||||
const id = useId();
|
||||
const [open, setOpen] = useState(false);
|
||||
const [value, setValue] = useState(String(ingredient.packSize ?? ""));
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState(false);
|
||||
const unit = t(`units.${kind}`);
|
||||
|
||||
async function save() {
|
||||
const size = parseNumber(value);
|
||||
if (!size || size <= 0) return setError(true);
|
||||
setBusy(true);
|
||||
setError(false);
|
||||
const res = await fetch(`/api/ingredients/${ingredient.id}/pack`, {
|
||||
method: "PUT",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ size }),
|
||||
}).catch(() => null);
|
||||
setBusy(false);
|
||||
if (!res?.ok) return setError(true);
|
||||
onSaved((await res.json()).size);
|
||||
setOpen(false);
|
||||
}
|
||||
|
||||
if (!open) {
|
||||
return (
|
||||
<div className="flex flex-wrap items-center gap-x-3 text-sm text-muted-foreground">
|
||||
<span>{t("packSize", { unit, size: sizeText(ingredient.packSize ?? 0, ingredient.unit) })}</span>
|
||||
<Button type="button" variant="ghost" className="min-h-11" onClick={() => setOpen(true)}>
|
||||
{t("packChange")}
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<div className="flex flex-col gap-2 rounded-xl border border-border p-3">
|
||||
<Label htmlFor={id} className="text-sm">
|
||||
{t("packSizeLabel", { unit, base: t(`units.${ingredient.unit}`) })}
|
||||
</Label>
|
||||
<div className="flex gap-2">
|
||||
<Input id={id} inputMode="decimal" value={value} onChange={(e) => setValue(e.target.value)} className="flex-1" />
|
||||
<Button type="button" disabled={busy} onClick={save}>
|
||||
{t("packSave")}
|
||||
</Button>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">{t("packHint")}</p>
|
||||
{error ? <ErrorNotice>{t("packError")}</ErrorNotice> : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -43,7 +43,6 @@ export function PhotoImport() {
|
||||
<input
|
||||
type="file"
|
||||
accept="image/*"
|
||||
capture="environment"
|
||||
multiple
|
||||
className="sr-only"
|
||||
aria-label={t("choose")}
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
"use client";
|
||||
|
||||
import { Minus, Plus, Timer } from "lucide-react";
|
||||
import { useLocale, useTranslations } from "next-intl";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { useState } from "react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { labelFor } from "@/lib/ingredient-name";
|
||||
import { SECTIONS, type Section } from "@/lib/recipe-style";
|
||||
import { formatQuantity, scale, type BaseUnit } from "@/lib/units";
|
||||
import { scale, type BaseUnit, type KitchenUnit } from "@/lib/units";
|
||||
import { useKitchenAmount } from "@/lib/use-kitchen-amount";
|
||||
|
||||
type Ingredient = {
|
||||
ingredientId: string;
|
||||
@@ -17,6 +18,8 @@ type Ingredient = {
|
||||
note: string | null;
|
||||
isStaple: boolean;
|
||||
product?: { name: string } | null;
|
||||
displayUnit?: KitchenUnit | null;
|
||||
packSize?: number | null;
|
||||
};
|
||||
type Step = { section: Section; text: string; timerSeconds: number | null; ingredientIds: string[]; timerFrom?: string };
|
||||
|
||||
@@ -24,14 +27,11 @@ type Step = { section: Section; text: string; timerSeconds: number | null; ingre
|
||||
// rechnet lib/units.ts — gespeichert ist immer „pro Portion“.
|
||||
export function PortionScaler({ ingredients, steps, initialPortions }: { ingredients: Ingredient[]; steps: Step[]; initialPortions: number }) {
|
||||
const t = useTranslations("dishes.detail");
|
||||
const locale = useLocale();
|
||||
const kitchen = useKitchenAmount();
|
||||
const [portions, setPortions] = useState(initialPortions);
|
||||
const ts = useTranslations("dishes.sections");
|
||||
const byId = new Map(ingredients.map((i) => [i.ingredientId, i]));
|
||||
const amountOf = (i: Ingredient) => {
|
||||
const f = formatQuantity(scale(i.qtyPerPortion, portions), i.unit, locale);
|
||||
return `${f.amount}${f.unit ? ` ${f.unit}` : ""} ${labelFor(i, scale(i.qtyPerPortion, portions))}`;
|
||||
};
|
||||
const amountOf = (i: Ingredient) => `${kitchen.text(i, scale(i.qtyPerPortion, portions))} ${labelFor(i, scale(i.qtyPerPortion, portions))}`;
|
||||
// Durchgehend nummeriert, gegliedert nach Abschnitten (lib/recipe-style.ts).
|
||||
const numbered = steps.map((s, n) => ({ ...s, n: n + 1 }));
|
||||
|
||||
@@ -54,14 +54,12 @@ export function PortionScaler({ ingredients, steps, initialPortions }: { ingredi
|
||||
</div>
|
||||
<ul className="flex flex-col divide-y divide-border">
|
||||
{ingredients.map((i) => {
|
||||
const f = formatQuantity(scale(i.qtyPerPortion, portions), i.unit, locale);
|
||||
const f = kitchen.parts(i, scale(i.qtyPerPortion, portions));
|
||||
return (
|
||||
<li key={i.ingredientId} className="flex min-h-11 items-baseline gap-3 py-2">
|
||||
<span className="w-20 shrink-0 text-right font-semibold tabular-nums">
|
||||
{f.amount}
|
||||
{f.unit ? ` ${f.unit}` : ""}
|
||||
</span>
|
||||
<span className="w-20 shrink-0 text-right font-semibold tabular-nums">{f.main}</span>
|
||||
<span className="flex-1">
|
||||
{f.extra ? <span className="text-muted-foreground tabular-nums">({f.extra}) </span> : null}
|
||||
{labelFor(i, scale(i.qtyPerPortion, portions))}
|
||||
{i.note ? <span className="text-muted-foreground">, {i.note}</span> : null}
|
||||
{i.product ? <span className="block text-sm text-muted-foreground">{i.product.name}</span> : null}
|
||||
@@ -80,11 +78,11 @@ export function PortionScaler({ ingredients, steps, initialPortions }: { ingredi
|
||||
if (!list.length) return null;
|
||||
return (
|
||||
<div key={section} className="flex flex-col gap-3">
|
||||
<h3 className="font-serif text-xl">{ts(section)}</h3>
|
||||
<h3 className="font-semibold text-xl">{ts(section)}</h3>
|
||||
<ol className="flex flex-col gap-4">
|
||||
{list.map((s) => (
|
||||
<li key={s.n} className="flex gap-3">
|
||||
<span aria-hidden className="flex size-8 shrink-0 items-center justify-center rounded-full bg-secondary font-serif text-lg">
|
||||
<span aria-hidden className="flex size-8 shrink-0 items-center justify-center rounded-full bg-secondary font-semibold text-lg">
|
||||
{s.n}
|
||||
</span>
|
||||
<div className="flex min-w-0 flex-col gap-1 pt-1">
|
||||
|
||||
@@ -52,7 +52,7 @@ export function StarterPicker({ starters }: { starters: Starter[] }) {
|
||||
{on || s.inPool ? <Check className="size-4" strokeWidth={2.5} /> : null}
|
||||
</span>
|
||||
<span className="flex flex-1 flex-col">
|
||||
<span className="font-serif text-lg leading-snug">{s.title}</span>
|
||||
<span className="font-semibold text-lg leading-snug">{s.title}</span>
|
||||
<span className="text-xs text-muted-foreground">{s.inPool ? t("starters.inPool") : s.meta}</span>
|
||||
</span>
|
||||
</button>
|
||||
@@ -61,7 +61,7 @@ export function StarterPicker({ starters }: { starters: Starter[] }) {
|
||||
})}
|
||||
</ul>
|
||||
{error ? <ErrorNotice>{t("form.errors.unknown")}</ErrorNotice> : null}
|
||||
<div className="sticky bottom-[var(--nav-space)] z-10 bg-background/0 pb-2">
|
||||
<div className="kb-shift sticky bottom-[var(--nav-space)] z-10 bg-background/0 pb-2">
|
||||
<Button
|
||||
size="lg"
|
||||
className="w-full shadow-lg"
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
"use client";
|
||||
|
||||
import Link from "next/link";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { useState } from "react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
|
||||
// Ein Gericht unter „Ausprobieren“ sagt das selbst (26.11.41, Kai: „neue Gerichte werden
|
||||
// nicht gespeichert“ — sie standen nur nicht im Pool). Mit einem Tipp in den Pool.
|
||||
export function TrialNote({ id, canWrite }: { id: string; canWrite: boolean }) {
|
||||
const t = useTranslations("dishes.detail");
|
||||
const router = useRouter();
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
async function toPool() {
|
||||
setBusy(true);
|
||||
const res = await fetch(`/api/dishes/${id}/pool`, { method: "POST" }).catch(() => null);
|
||||
setBusy(false);
|
||||
if (res?.ok) router.refresh();
|
||||
}
|
||||
|
||||
return (
|
||||
<div role="note" className="flex flex-col gap-3 rounded-xl border border-border px-4 py-3">
|
||||
<p className="text-sm">
|
||||
{t("inTrial")}{" "}
|
||||
<Link href="/gerichte?ansicht=ausprobieren" className="font-semibold underline underline-offset-4">
|
||||
{t("inTrialLink")}
|
||||
</Link>
|
||||
</p>
|
||||
{canWrite ? (
|
||||
<Button type="button" variant="outline" className="self-start" disabled={busy} onClick={toPool}>
|
||||
{t("toPool")}
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
"use client";
|
||||
|
||||
import { ImagePlus } from "lucide-react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { useState } from "react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { ErrorNotice } from "@/components/ui/notice";
|
||||
|
||||
// Widmung pflegen (nur Admin): Name, ein paar Sätze, ein Foto. Das Foto bleibt auf
|
||||
// der Box (/app/data), nicht im Code (Kai, 7.11.2026).
|
||||
export function DedicationForm({ name, text, hasPhoto }: { name: string; text: string; hasPhoto: boolean }) {
|
||||
const t = useTranslations("more.dedication");
|
||||
const router = useRouter();
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState(false);
|
||||
const [saved, setSaved] = useState(false);
|
||||
const [file, setFile] = useState<string | null>(null);
|
||||
|
||||
async function send(form: FormData) {
|
||||
setBusy(true);
|
||||
setError(false);
|
||||
setSaved(false);
|
||||
const res = await fetch("/api/household/dedication", { method: "PUT", body: form }).catch(() => null);
|
||||
setBusy(false);
|
||||
if (!res?.ok) return setError(true);
|
||||
setSaved(true);
|
||||
setFile(null);
|
||||
router.refresh();
|
||||
}
|
||||
|
||||
return (
|
||||
<form
|
||||
className="flex flex-col gap-3 rounded-2xl border border-border p-4"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
void send(new FormData(e.currentTarget));
|
||||
}}
|
||||
>
|
||||
<h3 className="font-semibold">{t("edit")}</h3>
|
||||
<div className="flex flex-col gap-2">
|
||||
<Label htmlFor="dedication-name">{t("name")}</Label>
|
||||
<Input id="dedication-name" name="name" maxLength={40} defaultValue={name} placeholder="Maike" />
|
||||
</div>
|
||||
<div className="flex flex-col gap-2">
|
||||
<Label htmlFor="dedication-text">{t("text")}</Label>
|
||||
<textarea
|
||||
id="dedication-text"
|
||||
name="text"
|
||||
maxLength={800}
|
||||
rows={4}
|
||||
defaultValue={text}
|
||||
placeholder={t("textPlaceholder")}
|
||||
className="rounded-xl border border-border bg-background px-3 py-2 text-base"
|
||||
/>
|
||||
</div>
|
||||
<div className="flex flex-col gap-2">
|
||||
{/* Eigener Knopf statt des Dateifelds: das zeigte die Beschriftung des Browsers („Choose File“). */}
|
||||
<input
|
||||
id="dedication-photo"
|
||||
name="photo"
|
||||
type="file"
|
||||
accept="image/jpeg,image/png,image/webp,image/heic,image/heif"
|
||||
className="peer sr-only"
|
||||
onChange={(e) => setFile(e.target.files?.[0]?.name ?? null)}
|
||||
/>
|
||||
<Label
|
||||
htmlFor="dedication-photo"
|
||||
className="inline-flex min-h-11 cursor-pointer items-center gap-2 self-start rounded-full border border-border px-5 font-semibold peer-focus-visible:ring-2 peer-focus-visible:ring-ring"
|
||||
>
|
||||
<ImagePlus aria-hidden className="size-5" />
|
||||
{hasPhoto ? t("newPhoto") : t("photo")}
|
||||
</Label>
|
||||
{file ? <p className="text-sm">{t("chosen", { name: file })}</p> : null}
|
||||
<p className="text-sm text-muted-foreground">{t("photoHint")}</p>
|
||||
</div>
|
||||
{error ? <ErrorNotice>{t("error")}</ErrorNotice> : null}
|
||||
{saved ? (
|
||||
<p role="status" className="text-sm">
|
||||
{t("saved")}
|
||||
</p>
|
||||
) : null}
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<Button type="submit" disabled={busy}>
|
||||
{t("save")}
|
||||
</Button>
|
||||
{hasPhoto ? (
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
disabled={busy}
|
||||
onClick={() => {
|
||||
const form = new FormData();
|
||||
form.set("name", name);
|
||||
form.set("text", text);
|
||||
form.set("removePhoto", "1");
|
||||
void send(form);
|
||||
}}
|
||||
>
|
||||
{t("removePhoto")}
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
"use client";
|
||||
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { useState } from "react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { ErrorNotice } from "@/components/ui/notice";
|
||||
|
||||
export type MailCurrent = {
|
||||
host: string;
|
||||
port: number;
|
||||
secure: boolean;
|
||||
username: string;
|
||||
fromAddress: string;
|
||||
fromName: string | null;
|
||||
hasPassword: boolean;
|
||||
} | null;
|
||||
|
||||
// Mails verschicken (nur Admin, 26.11.40). Voreinstellung Resend; der Schlüssel
|
||||
// geht nur hinein und wird nie angezeigt.
|
||||
export function MailSettings({ current, defaults, me }: { current: MailCurrent; defaults: NonNullable<MailCurrent>; me: string | null }) {
|
||||
const t = useTranslations("more.mailSettings");
|
||||
const te = useTranslations("auth.errors");
|
||||
const router = useRouter();
|
||||
const start = current ?? defaults;
|
||||
const [host, setHost] = useState(start.host);
|
||||
const [port, setPort] = useState(String(start.port));
|
||||
const [secure, setSecure] = useState(start.secure);
|
||||
const [username, setUsername] = useState(start.username);
|
||||
const [password, setPassword] = useState("");
|
||||
const [fromAddress, setFromAddress] = useState(start.fromAddress);
|
||||
const [fromName, setFromName] = useState(start.fromName ?? "");
|
||||
const [testTo, setTestTo] = useState(me ?? "");
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [note, setNote] = useState<string | null>(null);
|
||||
|
||||
async function save(event: React.FormEvent) {
|
||||
event.preventDefault();
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
setNote(null);
|
||||
const res = await fetch("/api/household/mail", {
|
||||
method: "PUT",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
host: host.trim(),
|
||||
port: Number(port),
|
||||
secure,
|
||||
username: username.trim(),
|
||||
password: password.trim() ? password.trim() : undefined,
|
||||
fromAddress: fromAddress.trim(),
|
||||
fromName: fromName.trim() || null,
|
||||
}),
|
||||
}).catch(() => null);
|
||||
setBusy(false);
|
||||
if (!res?.ok) return setError(te("invalid"));
|
||||
setPassword("");
|
||||
setNote(t("saved"));
|
||||
router.refresh();
|
||||
}
|
||||
|
||||
async function test() {
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
setNote(null);
|
||||
const res = await fetch("/api/household/mail/test", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ to: testTo }) }).catch(() => null);
|
||||
setBusy(false);
|
||||
if (res?.ok) return setNote(t("testSent"));
|
||||
const data = res ? await res.json().catch(() => ({})) : {};
|
||||
if (data.error === "mailFailed") return setError(t("testFailed", { detail: data.detail ?? "" }));
|
||||
setError(te(["mailNotConfigured", "tooMany", "invalid"].includes(data.error) ? data.error : "unknown"));
|
||||
}
|
||||
|
||||
async function remove() {
|
||||
setBusy(true);
|
||||
await fetch("/api/household/mail", { method: "DELETE" }).catch(() => null);
|
||||
setBusy(false);
|
||||
router.refresh();
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-5">
|
||||
<form onSubmit={save} className="flex flex-col gap-3">
|
||||
<div className="flex flex-col gap-1">
|
||||
<Label htmlFor="mail-host">{t("host")}</Label>
|
||||
<Input id="mail-host" value={host} onChange={(e) => setHost(e.target.value)} autoComplete="off" />
|
||||
</div>
|
||||
<div className="flex flex-col gap-1">
|
||||
<Label htmlFor="mail-port">{t("port")}</Label>
|
||||
<Input id="mail-port" inputMode="numeric" value={port} onChange={(e) => setPort(e.target.value)} />
|
||||
</div>
|
||||
<label className="flex min-h-11 items-center gap-3 text-sm">
|
||||
<input type="checkbox" checked={secure} onChange={(e) => setSecure(e.target.checked)} className="size-5 accent-primary" />
|
||||
{t("secure")}
|
||||
</label>
|
||||
<div className="flex flex-col gap-1">
|
||||
<Label htmlFor="mail-user">{t("username")}</Label>
|
||||
<Input id="mail-user" value={username} onChange={(e) => setUsername(e.target.value)} autoComplete="off" />
|
||||
</div>
|
||||
<div className="flex flex-col gap-1">
|
||||
<Label htmlFor="mail-password">{t("password")}</Label>
|
||||
<Input id="mail-password" type="password" value={password} onChange={(e) => setPassword(e.target.value)} autoComplete="new-password" placeholder="re_…" />
|
||||
{current?.hasPassword ? <p className="text-sm text-muted-foreground">{t("passwordSaved")}</p> : null}
|
||||
</div>
|
||||
<div className="flex flex-col gap-1">
|
||||
<Label htmlFor="mail-from">{t("fromAddress")}</Label>
|
||||
<Input id="mail-from" type="email" value={fromAddress} onChange={(e) => setFromAddress(e.target.value)} />
|
||||
</div>
|
||||
<div className="flex flex-col gap-1">
|
||||
<Label htmlFor="mail-from-name">{t("fromName")}</Label>
|
||||
<Input id="mail-from-name" value={fromName} onChange={(e) => setFromName(e.target.value)} maxLength={80} />
|
||||
</div>
|
||||
<Button type="submit" disabled={busy || (!current?.hasPassword && !password.trim())}>
|
||||
{t("save")}
|
||||
</Button>
|
||||
</form>
|
||||
|
||||
{current?.hasPassword ? (
|
||||
<div className="flex flex-col gap-2 border-t border-border pt-4">
|
||||
<Label htmlFor="mail-test-to">{t("testTo")}</Label>
|
||||
<Input id="mail-test-to" type="email" value={testTo} onChange={(e) => setTestTo(e.target.value)} />
|
||||
<Button type="button" variant="outline" disabled={busy || !testTo.trim()} onClick={test}>
|
||||
{t("test")}
|
||||
</Button>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{error ? <ErrorNotice>{error}</ErrorNotice> : null}
|
||||
{note ? (
|
||||
<p role="status" className="rounded-xl border border-border px-4 py-3 text-sm">
|
||||
{note}
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
<section className="flex flex-col gap-2 border-t border-border pt-4">
|
||||
<h2 className="eyebrow">{t("stepsTitle")}</h2>
|
||||
<ol className="flex list-decimal flex-col gap-1 pl-5 text-sm text-muted-foreground">
|
||||
<li>{t("step1")}</li>
|
||||
<li>{t("step2")}</li>
|
||||
<li>{t("step3")}</li>
|
||||
<li>{t("step4")}</li>
|
||||
</ol>
|
||||
</section>
|
||||
|
||||
{current ? (
|
||||
<Button type="button" variant="ghost" className="self-start" disabled={busy} onClick={remove}>
|
||||
{t("remove")}
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
"use client";
|
||||
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { useId, useState } from "react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { ErrorNotice } from "@/components/ui/notice";
|
||||
|
||||
// Mehr › Anmelden per Mail (26.11.40): eigene Adresse eintragen, über den Link
|
||||
// bestätigen. Wer per Mail-Link angemeldet ist, ändert hier nichts (E-0006).
|
||||
export function MailSignIn({ verified, pending, locked }: { verified: string | null; pending: string | null; locked: boolean }) {
|
||||
const t = useTranslations("more.mail");
|
||||
const te = useTranslations("auth.errors");
|
||||
const router = useRouter();
|
||||
const id = useId();
|
||||
const [email, setEmail] = useState("");
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [sentTo, setSentTo] = useState<string | null>(pending);
|
||||
|
||||
async function save(event: React.FormEvent) {
|
||||
event.preventDefault();
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
const res = await fetch("/api/me/email", { method: "PUT", headers: { "content-type": "application/json" }, body: JSON.stringify({ email }) }).catch(() => null);
|
||||
setBusy(false);
|
||||
if (res?.ok) {
|
||||
setSentTo((await res.json()).pending);
|
||||
setEmail("");
|
||||
return;
|
||||
}
|
||||
const key = res ? ((await res.json().catch(() => ({}))).error as string | undefined) : undefined;
|
||||
setError(key && ["mailNotConfigured", "mailFailed", "tooMany", "mailSession"].includes(key) ? key : "unknown");
|
||||
}
|
||||
|
||||
async function remove() {
|
||||
setBusy(true);
|
||||
await fetch("/api/me/email", { method: "DELETE" }).catch(() => null);
|
||||
setBusy(false);
|
||||
setSentTo(null);
|
||||
router.refresh();
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-3">
|
||||
<p className="text-sm text-muted-foreground">{t("intro")}</p>
|
||||
{verified ? <p className="font-medium">{t("verified", { email: verified })}</p> : null}
|
||||
{sentTo && sentTo !== verified ? (
|
||||
<p role="status" className="rounded-xl border border-border px-4 py-3 text-sm">
|
||||
{t("pending", { email: sentTo })}
|
||||
</p>
|
||||
) : null}
|
||||
{locked ? (
|
||||
<p className="rounded-xl border border-border px-4 py-3 text-sm">{t("locked")}</p>
|
||||
) : (
|
||||
<>
|
||||
<form onSubmit={save} className="flex flex-col gap-2">
|
||||
<Label htmlFor={id}>{t("label")}</Label>
|
||||
<Input id={id} type="email" autoComplete="email" inputMode="email" required value={email} onChange={(e) => setEmail(e.target.value)} />
|
||||
{error ? <ErrorNotice>{te(error)}</ErrorNotice> : null}
|
||||
<Button type="submit" disabled={busy || !email.trim()}>
|
||||
{t("save")}
|
||||
</Button>
|
||||
</form>
|
||||
{verified || sentTo ? (
|
||||
<Button type="button" variant="ghost" className="self-start" disabled={busy} onClick={remove}>
|
||||
{t("remove")}
|
||||
</Button>
|
||||
) : null}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -186,7 +186,7 @@ export function PlanBoard({
|
||||
) : null}
|
||||
|
||||
{status === "open" && slots.length ? (
|
||||
<div className="sticky bottom-[var(--nav-space)] z-10 bg-background py-2">
|
||||
<div className="kb-shift sticky bottom-[var(--nav-space)] z-10 bg-background py-2">
|
||||
<Button type="button" size="lg" className="w-full" disabled={busy} onClick={() => act("POST", "/api/plan/approve")}>
|
||||
{t("approve")}
|
||||
</Button>
|
||||
@@ -269,7 +269,7 @@ function SlotCard({
|
||||
</div>
|
||||
<div className="flex min-w-0 flex-1 flex-col gap-0.5">
|
||||
<p className="text-xs text-muted-foreground">{t("slot", { n: index + 1 })}</p>
|
||||
<h2 className="font-serif text-xl leading-snug">{slot.title ?? t("empty")}</h2>
|
||||
<h2 className="font-semibold text-xl leading-snug">{slot.title ?? t("empty")}</h2>
|
||||
{reason ? <p className="text-sm text-muted-foreground">{reason}</p> : null}
|
||||
{cost ? (
|
||||
<p className="flex flex-wrap items-center gap-2 text-sm text-muted-foreground">
|
||||
|
||||
@@ -281,7 +281,7 @@ export function ReceiptReview({ receipt }: { receipt: Receipt }) {
|
||||
{done ? (
|
||||
<p className="text-sm text-muted-foreground">{t("doneText")}</p>
|
||||
) : (
|
||||
<div className="sticky bottom-[var(--nav-space)] z-10 flex gap-2 bg-background py-2">
|
||||
<div className="kb-shift sticky bottom-[var(--nav-space)] z-10 flex gap-2 bg-background py-2">
|
||||
<Button type="button" variant="outline" disabled={busy} onClick={remove} aria-label={t("delete")}>
|
||||
<Trash2 aria-hidden />
|
||||
</Button>
|
||||
|
||||
@@ -5,7 +5,7 @@ import { useLocale, useTranslations } from "next-intl";
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { formatQuantity } from "@/lib/units";
|
||||
import { formatQuantity, type PackKind } from "@/lib/units";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
export type Item = {
|
||||
@@ -16,6 +16,8 @@ export type Item = {
|
||||
unit: "g" | "ml" | "piece" | null;
|
||||
packCount: number | null;
|
||||
packSize: number | null;
|
||||
/** Gebinde („2 Dosen à 400 g“), seit 26.11.39. */
|
||||
packKind?: PackKind | null;
|
||||
dishes: string[];
|
||||
aislePosition: number | null;
|
||||
manual: boolean;
|
||||
@@ -46,6 +48,7 @@ function writeQueue(ops: Op[]) {
|
||||
// Warteschlange im Browser und gehen raus, sobald wieder Netz da ist.
|
||||
export function ShoppingList({ initial, aisles, me }: { initial: Item[]; aisles: Aisle[]; me: string }) {
|
||||
const t = useTranslations("shopping");
|
||||
const tm = useTranslations("measure");
|
||||
const locale = useLocale();
|
||||
const [items, setItems] = useState(initial);
|
||||
const [queue, setQueue] = useState<Op[]>([]);
|
||||
@@ -135,6 +138,7 @@ export function ShoppingList({ initial, aisles, me }: { initial: Item[]; aisles:
|
||||
if (i.unit === "piece") return t("pieces", { n: i.qty });
|
||||
if (i.packCount && i.packSize) {
|
||||
const f = formatQuantity(i.packSize, i.unit, locale);
|
||||
if (i.packKind) return t("packOf", { count: i.packCount, word: tm(i.packKind, { n: i.packCount }), size: `${f.amount} ${f.unit}` });
|
||||
return i.packCount > 1 ? `${i.packCount} × ${f.amount} ${f.unit}` : `${f.amount} ${f.unit}`;
|
||||
}
|
||||
const f = formatQuantity(i.qty, i.unit, locale);
|
||||
|
||||
@@ -2,10 +2,13 @@ import { cn } from "@/lib/utils";
|
||||
|
||||
// TokenJar (Konzept, „Bausteine“): Jetons als Münzen. Volle Münze = noch frei.
|
||||
// Die Zahl steht immer daneben im Text — Farbe allein trägt nichts.
|
||||
// Mehr als fünf Münzen passen am Handy nicht in eine Zeile; dann trägt die Zahl allein.
|
||||
const MAX_COINS = 5;
|
||||
|
||||
export function TokenJar({ total, left, label, className }: { total: number; left: number; label: string; className?: string }) {
|
||||
return (
|
||||
<span className={cn("inline-flex items-center gap-2", className)}>
|
||||
<span aria-hidden className="flex gap-1">
|
||||
<span aria-hidden className={cn("flex gap-1", total > MAX_COINS && "hidden")}>
|
||||
{Array.from({ length: total }, (_, i) => (
|
||||
<span
|
||||
key={i}
|
||||
@@ -16,7 +19,7 @@ export function TokenJar({ total, left, label, className }: { total: number; lef
|
||||
/>
|
||||
))}
|
||||
</span>
|
||||
<span className="text-sm font-semibold">{label}</span>
|
||||
{label ? <span className="text-sm font-semibold">{label}</span> : null}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
@@ -85,7 +85,13 @@ export function WishBoard({
|
||||
for (const e of entries) map.set(e.dishId, [...(map.get(e.dishId) ?? []), e]);
|
||||
return map;
|
||||
}, [entries]);
|
||||
const mine = (id: string) => byDish.get(id)?.find((e) => e.memberId === me);
|
||||
// Gerade Gespeichertes (Grund, „Ich koche das“) gilt sofort — auch wenn das Blatt
|
||||
// wieder aufgeht, bevor die Seite neu geladen ist.
|
||||
const [edits, setEdits] = useState<Record<string, { note: string | null; wantsToCook: boolean }>>({});
|
||||
const mine = (id: string) => {
|
||||
const own = byDish.get(id)?.find((e) => e.memberId === me);
|
||||
return own && edits[id] ? { ...own, ...edits[id] } : own;
|
||||
};
|
||||
const wishers = (id: string) => (byDish.get(id) ?? []).filter((e) => !e.isVeto);
|
||||
const vetoes = (id: string) => (byDish.get(id) ?? []).filter((e) => e.isVeto);
|
||||
const mineOf = (id: string) => (byDish.get(id) ?? []).filter((e) => e.isMine);
|
||||
@@ -105,6 +111,7 @@ export function WishBoard({
|
||||
setError(["noTokens", "noVetos", "noRound", "noTrial", "dish", "alternative", "protected", "repeat", "notWished"].includes(data.error) ? data.error : "unknown");
|
||||
return null;
|
||||
}
|
||||
if (method !== "PATCH") setEdits(({ [key]: _, ...rest }) => rest); // neuer oder zurückgenommener Wunsch: Server gilt
|
||||
if (method === "POST" && "vibrate" in navigator) navigator.vibrate?.(15);
|
||||
router.refresh();
|
||||
return data;
|
||||
@@ -129,12 +136,19 @@ export function WishBoard({
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-4">
|
||||
<div className="sticky top-0 z-10 -mx-4 flex flex-wrap items-center gap-x-4 gap-y-2 border-b border-border bg-background px-4 py-3">
|
||||
<TokenJar total={budget.tokens} left={budget.tokensLeft} label={t("tokensLeft", { n: budget.tokensLeft })} />
|
||||
{canVeto && budget.vetos > 0 ? <span className="text-sm text-muted-foreground">{t("vetosLeft", { n: budget.vetosLeft })}</span> : null}
|
||||
<Button type="button" variant="outline" className="ml-auto" disabled={!!busy || budget.tokensLeft < 1} onClick={joker}>
|
||||
{/* Eine Zeile, auch am kleinen iPhone (Kai, 7.11.2026): Jetons, darunter klein das Veto,
|
||||
rechts der Joker kompakt — Zeichen und Wort, damit er ohne Raten verständlich bleibt. */}
|
||||
<div className="sticky top-0 z-10 -mx-4 flex items-center gap-3 border-b border-border bg-background px-4 py-3">
|
||||
<div className="flex min-w-0 flex-1 items-center gap-2">
|
||||
<TokenJar total={budget.tokens} left={budget.tokensLeft} label="" className="shrink-0" />
|
||||
<span className="flex min-w-0 flex-col leading-tight">
|
||||
<span className="text-sm font-semibold">{t("tokensLeft", { n: budget.tokensLeft })}</span>
|
||||
{canVeto && budget.vetos > 0 ? <span className="text-xs text-muted-foreground">{t("vetosLeft", { n: budget.vetosLeft })}</span> : null}
|
||||
</span>
|
||||
</div>
|
||||
<Button type="button" variant="outline" className="shrink-0 px-4" aria-label={t("joker")} disabled={!!busy || budget.tokensLeft < 1} onClick={joker}>
|
||||
<Shuffle aria-hidden />
|
||||
{t("joker")}
|
||||
{t("jokerShort")}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
@@ -218,7 +232,7 @@ export function WishBoard({
|
||||
) : null}
|
||||
</span>
|
||||
<span className="flex min-h-11 flex-col gap-0.5 p-3 pr-12">
|
||||
<span className="font-serif text-lg leading-snug">{tile.title}</span>
|
||||
<span className="font-semibold text-lg leading-snug">{tile.title}</span>
|
||||
{favorite ? <span className="sr-only">{t("favorite")}</span> : null}
|
||||
{mineNames.length ? <span className="sr-only">{isMyDish ? t("mine") : t("mineOf", { names: mineNames.join(", ") })}</span> : null}
|
||||
{names.length ? <span className="text-xs text-muted-foreground">{t("wishedBy", { names: names.join(", ") })}</span> : null}
|
||||
@@ -271,6 +285,10 @@ export function WishBoard({
|
||||
busy={!!busy}
|
||||
onCall={async (method, body) => {
|
||||
const ok = await call(method, "/api/wishes", body, open.id);
|
||||
if (ok && method === "PATCH") {
|
||||
const b = body as { note: string | null; wantsToCook: boolean };
|
||||
setEdits((e) => ({ ...e, [open.id]: { note: b.note, wantsToCook: b.wantsToCook } }));
|
||||
}
|
||||
if (ok) dialog.current?.close();
|
||||
}}
|
||||
onClose={() => dialog.current?.close()}
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
-- foodplanhero by Maike (Kai, 7.11.2026, 26.11.35): Die App ist Maike gewidmet.
|
||||
-- Je Haushalt ein Name, ein Foto (unter /app/data/fotos, nicht im Code) und ein
|
||||
-- paar Sätze. Das Foto erscheint auf dem Startbild, beim Anmelden und unter
|
||||
-- „Mehr“ › „Für Maike“. Ohne Foto bleibt alles wie vorher.
|
||||
|
||||
alter table households add column dedication_name text check (dedication_name is null or length(trim(dedication_name)) between 1 and 40);
|
||||
alter table households add column dedication_text text check (dedication_text is null or length(dedication_text) <= 800);
|
||||
alter table households add column dedication_photo text;
|
||||
@@ -0,0 +1,39 @@
|
||||
-- Produktgruppen und eigene Zutaten (Kai, 7.11.2026, 26.11.38).
|
||||
--
|
||||
-- Gruppen: Eine Zutat kann ein Oberbegriff sein (Pasta, Reis, Käse, Hülsenfrüchte)
|
||||
-- und selbst gewählt werden („Pasta, beliebige Sorte“); die Sorten zeigen mit
|
||||
-- parent_id auf ihn. Kommen aus db/seed wie alle globalen Zutaten.
|
||||
--
|
||||
-- Eigene Zutaten: Fehlt etwas im Katalog („Gnocchi“), legen Erwachsene es für
|
||||
-- ihren Haushalt an (household_id). Global bleibt household_id leer.
|
||||
--
|
||||
-- Lieblingsprodukt je Zutat oder Gruppe für den ganzen Haushalt („unsere Pasta
|
||||
-- ist Barilla Nr. 5“): household_products; ein Produkt am Gericht geht vor.
|
||||
|
||||
alter table ingredients add column is_group boolean not null default false;
|
||||
alter table ingredients add column parent_id uuid references ingredients (id);
|
||||
alter table ingredients add column household_id uuid references households (id) on delete cascade;
|
||||
create index ingredients_parent_idx on ingredients (parent_id) where parent_id is not null;
|
||||
create index ingredients_household_idx on ingredients (household_id) where household_id is not null;
|
||||
|
||||
drop policy ingredients_read on ingredients;
|
||||
create policy ingredients_read on ingredients for select
|
||||
using (household_id is null or household_id = app_household_id() or app_maintenance());
|
||||
create policy ingredients_own on ingredients for all
|
||||
using (household_id = app_household_id())
|
||||
with check (household_id = app_household_id() and not is_group);
|
||||
|
||||
create table household_products (
|
||||
household_id uuid not null references households (id) on delete cascade,
|
||||
ingredient_id uuid not null references ingredients (id) on delete cascade,
|
||||
product text not null check (length(trim(product)) between 1 and 80),
|
||||
product_pack numeric(12, 3) check (product_pack is null or product_pack > 0),
|
||||
cook_minutes integer check (cook_minutes is null or cook_minutes between 1 and 240),
|
||||
updated_at timestamptz not null default now(),
|
||||
primary key (household_id, ingredient_id)
|
||||
);
|
||||
alter table household_products enable row level security;
|
||||
alter table household_products force row level security;
|
||||
create policy household_products_household on household_products
|
||||
using (household_id = app_household_id())
|
||||
with check (household_id = app_household_id());
|
||||
@@ -0,0 +1,33 @@
|
||||
-- Löffel und Gebinde (Kai, 7.11.2026, 26.11.39).
|
||||
--
|
||||
-- Mengen bleiben in der Basiseinheit pro Portion gespeichert (CLAUDE.md, Regel 2).
|
||||
-- Dazu kommt, in welchem Küchenmaß sie eingegeben wurden (display_unit), damit
|
||||
-- das Rezept „2 EL (30 ml)“ zeigt statt nur „30 ml“, und „400 g (1 Dose)“.
|
||||
--
|
||||
-- An der Zutat: das übliche Küchenmaß (kitchen_unit, vorgewählt im Formular)
|
||||
-- und das übliche Gebinde mit Größe in der Basiseinheit (pack_kind, pack_size).
|
||||
-- Ein Haushalt kann die Größe ändern (household_pack_sizes); ein Produkt mit
|
||||
-- Packungsgröße am Gericht geht vor.
|
||||
|
||||
alter table ingredients add column kitchen_unit text
|
||||
check (kitchen_unit in ('tbsp', 'tsp', 'pinch', 'can', 'jar', 'pack', 'bunch'));
|
||||
alter table ingredients add column pack_kind text check (pack_kind in ('can', 'jar', 'pack', 'bunch'));
|
||||
alter table ingredients add column pack_size numeric(12, 3) check (pack_size is null or pack_size > 0);
|
||||
|
||||
alter table dish_ingredients add column display_unit text
|
||||
check (display_unit in ('tbsp', 'tsp', 'pinch', 'can', 'jar', 'pack', 'bunch'));
|
||||
|
||||
alter table shopping_items add column pack_kind text check (pack_kind in ('can', 'jar', 'pack', 'bunch'));
|
||||
|
||||
create table household_pack_sizes (
|
||||
household_id uuid not null references households (id) on delete cascade,
|
||||
ingredient_id uuid not null references ingredients (id) on delete cascade,
|
||||
pack_size numeric(12, 3) not null check (pack_size > 0),
|
||||
updated_at timestamptz not null default now(),
|
||||
primary key (household_id, ingredient_id)
|
||||
);
|
||||
alter table household_pack_sizes enable row level security;
|
||||
alter table household_pack_sizes force row level security;
|
||||
create policy household_pack_sizes_household on household_pack_sizes
|
||||
using (household_id = app_household_id())
|
||||
with check (household_id = app_household_id());
|
||||
@@ -0,0 +1,54 @@
|
||||
-- Anmelden per Link aus der Mail (Kai, 7.11.2026, 26.11.40; E-0006, E-0017).
|
||||
--
|
||||
-- Mailweg je Haushalt (Resend über SMTP): Das Passwort (API-Schlüssel) liegt
|
||||
-- nur verschlüsselt hier (lib/vault.ts, tresor.key), wie bei household_ai.
|
||||
--
|
||||
-- Wer sich per Mail anmelden will, trägt seine Adresse selbst ein und bestätigt
|
||||
-- sie über einen ersten Link (email_verified_at). Ohne Bestätigung keine Mail.
|
||||
--
|
||||
-- mail_tokens: Einmal-Links zum Anmelden (15 Minuten) und zum Bestätigen
|
||||
-- (24 Stunden); gespeichert nur der Hash. Eine Sitzung merkt sich, womit sie
|
||||
-- begann (via): Wer per Mail kam, darf nur anmelden — keine Geräte, keine
|
||||
-- Passkeys, keine Einladungen (E-0006).
|
||||
|
||||
create table household_mail (
|
||||
household_id uuid primary key references households (id) on delete cascade,
|
||||
host text not null check (length(host) between 1 and 200),
|
||||
port integer not null check (port between 1 and 65535),
|
||||
secure boolean not null default true,
|
||||
username text not null check (length(username) between 1 and 200),
|
||||
password_enc bytea,
|
||||
from_address text not null check (from_address = lower(from_address) and from_address like '%@%'),
|
||||
from_name text check (length(from_name) <= 80),
|
||||
updated_by uuid references members (id) on delete set null,
|
||||
updated_at timestamptz not null default now()
|
||||
);
|
||||
alter table household_mail enable row level security;
|
||||
alter table household_mail force row level security;
|
||||
create policy household_mail_household on household_mail
|
||||
using (household_id = app_household_id())
|
||||
with check (household_id = app_household_id());
|
||||
|
||||
alter table members add column email_verified_at timestamptz;
|
||||
|
||||
create table mail_tokens (
|
||||
id uuid primary key default gen_random_uuid(),
|
||||
household_id uuid not null references households (id) on delete cascade,
|
||||
member_id uuid not null references members (id) on delete cascade,
|
||||
purpose text not null check (purpose in ('login', 'verify')),
|
||||
email text not null check (email = lower(email)),
|
||||
token_hash bytea not null unique,
|
||||
created_at timestamptz not null default now(),
|
||||
expires_at timestamptz not null,
|
||||
used_at timestamptz
|
||||
);
|
||||
create index mail_tokens_member_idx on mail_tokens (member_id);
|
||||
alter table mail_tokens enable row level security;
|
||||
alter table mail_tokens force row level security;
|
||||
-- Wie invitations: im Haushalt und für die Anmeldung, die den Haushalt erst findet.
|
||||
create policy mail_tokens_household on mail_tokens
|
||||
using (household_id = app_household_id() or app_auth())
|
||||
with check (household_id = app_household_id() or app_auth());
|
||||
|
||||
alter table sessions add column via text not null default 'passkey' check (via in ('passkey', 'mail', 'kid'));
|
||||
update sessions set via = 'kid' where kid_device_id is not null;
|
||||
+637
-138
File diff suppressed because it is too large.
Load diff
+109
-3
@@ -174,10 +174,10 @@ acht Paletten Variante H gewählt). Löst die Palette aus E-0002 ab; der Rest vo
|
||||
Hauptaktion je Ansicht.
|
||||
- **Etiketten und Links:** kleine Versalien in tiefem Lavendel (`.eyebrow`), etwa
|
||||
„HEUTE“, „ZUTATEN“. Pastell nie als Schriftfarbe auf heller Fläche.
|
||||
- **Schrift:** Überschriften `h1`/`h2` in Newsreader (Serifen, SIL OFL, lokal unter
|
||||
`app/fonts/`), Text in Geist.
|
||||
- **Schrift:** ~~Überschriften in Newsreader, Text in Geist~~ — seit 26.11.37 Poppins
|
||||
überall (E-0014).
|
||||
- **Abschnitte** ohne Kasten, getrennt durch feine Linien.
|
||||
- **Symbol:** Teller mit Dampf auf Coral, Blatt in Lavendel (`docs/icon/lunch.svg`).
|
||||
- **Symbol:** Kochmütze mit Herz auf Coral (seit 26.11.42, Kai: Entwurf a; vorher Teller mit Dampf und Lavendel-Blatt), `docs/icon/lunch.svg`.
|
||||
- **Kontrast** jeder Schrift auf ihrer Fläche mindestens 4,5:1, hell und dunkel —
|
||||
`tests/contrast.test.ts` rechnet ihn aus den Token.
|
||||
|
||||
@@ -229,3 +229,109 @@ und wer sich verzockt, steht leer da. Entschieden:
|
||||
kommen. Ein Veto ohne Publikum lohnt sich zum Ärgern nicht.
|
||||
|
||||
Jetons und Veto bleiben für alles andere.
|
||||
|
||||
## E-0013 · foodplanhero, Maike gewidmet
|
||||
|
||||
*7.11.2026 · Kai*
|
||||
|
||||
Die App ist eine Danksagung an Maike. Sie heißt in der Oberfläche **foodplanhero** mit dem
|
||||
Slogan **„Plan. Cook. Smile.“** (Kais früherer Entwurf); technisch bleibt sie `lunch`.
|
||||
|
||||
- **Startbild ja, Wartezeit nein:** Maike erscheint auf dem iOS-Startbild, solange die
|
||||
Web-App lädt. Eine künstliche Pause wie bei Airbnb gibt es nicht — die App öffnet man
|
||||
vor dem Herd und im Laden mehrmals am Tag.
|
||||
- **Maike** zusätzlich beim Anmelden, bei der Einladung und unter „Mehr“ › „Für Maike“
|
||||
mit Kais Worten. Das Foto lädt ein Admin auf der Box hoch; es liegt nie im Repo.
|
||||
- **Slogan im Ablauf:** leise, mit dem Wort, das gerade passiert (Plan, Kochen, Bewerten).
|
||||
- **Gestaltung bleibt** (E-0009): Coral und Lavendel; neu ist nur das Grün von „hero“ als
|
||||
Token `--hero`, das auch Maikes Ring trägt.
|
||||
|
||||
## E-0014 · Eine Schrift: Poppins (löst die Serifen aus E-0009 ab)
|
||||
|
||||
*7.11.2026 · Kai („zu viele Schriftarten“)*
|
||||
|
||||
Mit foodplanhero standen vier Schriften auf der Startseite: Poppins (Logo), Caveat
|
||||
(„by Maike“), Newsreader (Überschriften) und Geist (Text). Entschieden: **Poppins für
|
||||
alles** — Logo, Überschriften (SemiBold), Text, Knöpfe —, wie in Kais Figma-Entwurf.
|
||||
**Caveat** bleibt, aber nur als Maikes Unterschrift „by Maike“, nirgends sonst.
|
||||
Newsreader und Geist sind entfernt. Farben, Flächen und Abstände aus E-0009 bleiben.
|
||||
|
||||
## E-0015 · Produktgruppen, eigene Zutaten, Lieblingsprodukt je Haushalt
|
||||
|
||||
*7.11.2026 · Kai („den Oberbegriff Pasta eigentlich besser … Oder Produktgruppen?“)*
|
||||
|
||||
**Gruppen.** Es gibt vier Oberbegriffe: Pasta, Reis, Käse sowie Linsen und Hülsenfrüchte.
|
||||
Jede Gruppe ist selbst eine Zutat (`is_group`) und lässt sich als „beliebige Sorte“ wählen.
|
||||
Die Sorten hängen über `parent_id` an ihrer Gruppe. Trifft die Suche eine Gruppe, auch über
|
||||
ein Synonym („Nudeln“), steht die Gruppe oben und alle ihre Sorten folgen. Gibt es keinen
|
||||
eigenen Bon-Preis für die Gruppe, ist ihr Preis der Durchschnitt der besten Preise ihrer
|
||||
Sorten.
|
||||
|
||||
**Eigene Zutaten.** Zutaten anlegen darf, wer Gerichte pflegt (Admin und Mitglied). Eine
|
||||
eigene Zutat gehört dem Haushalt (`household_id`). Die Zeilensicherheit zeigt sie nur
|
||||
diesem Haushalt, und Gruppen anlegen kann ein Haushalt nicht. Doppelte Namen werden
|
||||
abgewiesen. Eigene Zutaten gehen in die Sicherung.
|
||||
|
||||
**Lieblingsprodukt.** Es gilt je Zutat für den ganzen Haushalt (`household_products`) und
|
||||
wird mit dem Haken „Für alle Gerichte mit … merken“ gesetzt. Ein Produkt, das am Gericht
|
||||
selbst steht, geht immer vor.
|
||||
|
||||
## E-0016 · Löffel und Gebinde als Mengeneinheiten
|
||||
|
||||
*7.11.2026 · Kai („Teelöffel, Esslöffel … eine Dose als Einheit … natürlich muss auch die Grammzahl dort stehen“)*
|
||||
|
||||
**Gespeichert** wird weiter in der Basiseinheit pro Portion (Regel 2). Dazu hält
|
||||
`dish_ingredients.display_unit` fest, in welchem Maß die Menge eingegeben wurde:
|
||||
EL, TL, Prise, Dose, Glas, Packung oder Bund. Hochrechnen, Einkaufsliste und
|
||||
Preise rechnen also unverändert.
|
||||
|
||||
**Anzeige** (Kais Wahl):
|
||||
- Löffel stehen vorn, die Gramm in Klammern: „2 EL (30 ml)“. Die Prise hat keine Klammer.
|
||||
- Gebinde zeigen die Gramm zuerst: „400 g (1 Dose)“, hochgerechnet in Küchenbrüchen.
|
||||
- Weniger als eine Viertel Packung zeigt nur Gramm.
|
||||
- Ältere Gerichte und Vorlagen ohne Maß bekommen Löffel, wenn es ½ bis 8 sind, und
|
||||
ein Gebinde ab einer Viertel Packung. Prisen bekommen sie nie von selbst.
|
||||
|
||||
**An der Zutat:**
|
||||
- Das übliche Löffelmaß wird im Formular vorgewählt (Olivenöl in EL, Kreuzkümmel in TL, Salz in Prisen).
|
||||
- Das übliche Gebinde und seine Größe (gehackte Tomaten: Dose, 400 g) werden angeboten, mit der Größe in der Auswahl.
|
||||
- Ein Gebinde wird **nie vorgewählt**: Wer nach „Kokosmilch“ gleich „400“ tippt, meint Milliliter.
|
||||
|
||||
**Größe eines Gebindes:** Es gilt zuerst das Produkt am Gericht, dann das Lieblingsprodukt
|
||||
des Haushalts, dann die Haushaltsgröße (`household_pack_sizes`, ändern darf, wer Gerichte
|
||||
pflegt), zuletzt die Vorgabe. Beim Einlesen von Rezepten kommt die Größe aus der Zutat,
|
||||
nie aus dem Text oder einem Modell.
|
||||
|
||||
## E-0017 · Mail-Link über Resend: nur anmelden
|
||||
|
||||
*7.11.2026 · Kai („Dann lieber resend“). Folgt E-0006.*
|
||||
|
||||
**Mailweg:** Resend über SMTP, Server `smtp.resend.com`, Port 465 mit TLS von
|
||||
Anfang an, Benutzer `resend`, Passwort ist ein API-Schlüssel. Der Absender ist
|
||||
`hallo@foodplanhero.de`.
|
||||
- Je Haushalt in `household_mail`. Der Schlüssel liegt nur verschlüsselt dort
|
||||
(`lib/vault.ts`) und kommt mit `tresor.key` in die Sicherung.
|
||||
- Die Felder bleiben änderbar, falls Resend etwas ändert.
|
||||
- Cloudflare Email Sending wäre möglich gewesen, braucht aber den bezahlten
|
||||
Workers-Tarif. Brevo war für die Domain schon vorbereitet. Kai hat Resend
|
||||
gewählt.
|
||||
|
||||
**Wer:** Nur wer es selbst einschaltet. Die Person trägt ihre Adresse unter Mehr
|
||||
ein und bestätigt sie über einen ersten Link (24 Stunden). Erwachsene und
|
||||
Jugendliche dürfen das, Kinder und Gäste nicht.
|
||||
|
||||
**Der Link:** Er gilt 15 Minuten und einmal; gespeichert ist nur der Hash.
|
||||
- Er steht hinter `#` auf `/anmelden/mail`. Eingelöst wird er erst per POST nach
|
||||
einem Tipp, so verbrauchen Mail-Scanner ihn nicht.
|
||||
- Die Antwort auf eine Anfrage ist immer gleich; der Versand läuft im Hintergrund.
|
||||
|
||||
**Nur anmelden** (Kai): Eine Sitzung mit `via = 'mail'` darf Folgendes nicht:
|
||||
- Passkeys oder Geräte hinzufügen oder entfernen
|
||||
- Einladungen und Kindergeräte erstellen
|
||||
- Personen entfernen
|
||||
- Adresse oder Mailweg ändern
|
||||
|
||||
Das prüft `noMailSession` in `lib/auth/guard.ts`. Mail-Sitzungen gelten 30 Tage
|
||||
statt 180. Adresse entfernen oder ändern beendet sie.
|
||||
|
||||
Sicherheitsprüfung: `docs/sicherheit/login-2026-11-07.md`.
|
||||
+7
-14
@@ -1,15 +1,8 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512">
|
||||
<rect width="512" height="512" rx="112" fill="#f39380"/>
|
||||
<!-- Teller -->
|
||||
<circle cx="256" cy="292" r="142" fill="#fefdff"/>
|
||||
<circle cx="256" cy="292" r="98" fill="none" stroke="#e7e1f6" stroke-width="14"/>
|
||||
<!-- Dampf -->
|
||||
<g fill="none" stroke="#fefdff" stroke-width="18" stroke-linecap="round">
|
||||
<path d="M206 78c-16 18 16 30 0 48"/>
|
||||
<path d="M256 64c-16 20 16 34 0 54"/>
|
||||
<path d="M306 78c-16 18 16 30 0 48"/>
|
||||
</g>
|
||||
<!-- Salbeiblatt -->
|
||||
<path d="M206 316c20-62 86-82 116-72-6 52-58 98-116 72z" fill="#7761b0"/>
|
||||
<path d="M214 312c30-24 58-42 96-62" stroke="#fefdff" stroke-width="7" stroke-linecap="round" fill="none"/>
|
||||
</svg>
|
||||
<!-- foodplanhero (Kai, 7.11.2026, 26.11.42): Kochmütze mit Herz, für Maike. Koralle wie bisher. --><rect width="512" height="512" rx="112" fill="#f39380"/><g>
|
||||
<circle cx="178" cy="214" r="70" fill="#fefdff"/>
|
||||
<circle cx="256" cy="176" r="86" fill="#fefdff"/>
|
||||
<circle cx="334" cy="214" r="70" fill="#fefdff"/>
|
||||
<rect x="158" y="210" width="196" height="132" fill="#fefdff"/>
|
||||
<rect x="150" y="350" width="212" height="56" rx="20" fill="#fefdff"/>
|
||||
</g><path d="M256 318 C230 298 202 276 202 250 C202 230 217 218 234 218 C245 218 252 224 256 233 C260 224 267 218 278 218 C295 218 310 230 310 250 C310 276 282 298 256 318 Z" fill="#f39380"/></svg>
|
||||
|
Before Width: | Height: | Size: 719 B After Width: | Height: | Size: 720 B |
@@ -0,0 +1,148 @@
|
||||
# Login-Sicherheit: Lunch (foodplanhero) — Mail-Link
|
||||
|
||||
**Gesamturteil:** 🟢 solide. Der neue Weg „Anmelden per Mail“ hat nach den
|
||||
Korrekturen in diesem PR keine offenen Befunde über „niedrig“.
|
||||
|
||||
**Geprüft am 7.11.2026, vor der Auslieferung von 26.11.40.**
|
||||
- **Auth-Typ:** Passkeys bleiben der Hauptweg. Neu ist ein **Mail-Link als
|
||||
zweiter Weg zum Anmelden**, nur für Personen, die ihre Adresse selbst
|
||||
eingetragen und bestätigt haben.
|
||||
- **Versand:** Resend über SMTP. Der Schlüssel liegt verschlüsselt im Tresor.
|
||||
- **ASVS-Ziel:** L2 (personenbezogene Daten, Kinder).
|
||||
- **Live geprüft** gegen localhost mit dem Mail-Ordner statt echtem Versand
|
||||
(`MAIL_TEST_DIR`, `e2e/mail.spec.ts`):
|
||||
- einrichten und Testmail schicken
|
||||
- Adresse bestätigen
|
||||
- unbekannte Adresse anfragen
|
||||
- per Link anmelden
|
||||
- Rechte der Mail-Sitzung
|
||||
- denselben Link ein zweites Mal öffnen
|
||||
- **Ohne echten Versand:** Gegen Resend wurde nichts geschickt; jeder Versuch
|
||||
kostet Kontingent.
|
||||
- **Geprüfte Dateien:**
|
||||
- `lib/auth/mail-login.ts`
|
||||
- `lib/mail.ts`
|
||||
- `app/api/auth/mail/{request,verify}`
|
||||
- `app/api/me/email`
|
||||
- `app/api/household/mail{,/test}`
|
||||
- `components/auth/mail-link.tsx`
|
||||
- `lib/auth/guard.ts` (`noMailSession`)
|
||||
- `lib/auth/session.ts` (`via`)
|
||||
- `db/migrations/0024_mail_sign_in.sql`
|
||||
|
||||
**Grundannahme, ausgesprochen.** Wer das Postfach hat, kommt in Lunch hinein. Das
|
||||
gilt nur für Personen, die die Anmeldung per Mail selbst einschalten.
|
||||
|
||||
Der Link öffnet nur die Anmeldung. Er schafft keinen Zugang über das hinaus, was
|
||||
eine Sitzung ohnehin kann (Kai, E-0006/E-0017). Aus einer Mail-Sitzung geht
|
||||
Folgendes nicht:
|
||||
- Passkeys oder Geräte hinzufügen oder entfernen
|
||||
- Einladungen und Kindergeräte erstellen
|
||||
- Personen entfernen
|
||||
- die eigene Adresse oder den Mailweg ändern
|
||||
|
||||
Wer sein Postfach verliert, verliert also nicht dauerhaft das Konto. Ein Angreifer
|
||||
mit dem Postfach hat höchstens 30 Tage Zugriff und kann keinen bleibenden
|
||||
Zugang anlegen.
|
||||
|
||||
**Vertrauensgrenzen.**
|
||||
1. **Der Token läuft nur im Browser.** Er steht hinter `#`, geht also nie in
|
||||
Server-Logs, Proxy-Logs oder den `Referer`. Der Server sieht ihn erst im
|
||||
POST nach einem Tipp, und dieser POST muss vom eigenen Ursprung kommen
|
||||
(`sameOrigin`).
|
||||
2. **Datenzugriff vor der Anmeldung:** `withAuth()` darf die Haushaltsgrenze nun
|
||||
auch auf `mail_tokens` überspringen. Das ist bewusst so; der Wachtest
|
||||
`tests/rls.test.ts` hält die Liste fest. `household_mail` gehört nur dem
|
||||
Haushalt.
|
||||
3. **Fehlende Konfiguration:** Ohne Mailweg gibt es keinen Versand. Die Anfrage
|
||||
antwortet trotzdem gleich, es gibt keinen Rückfall auf einen anderen Weg.
|
||||
`MAIL_TEST_DIR` setzt nur die CI. Das Chart setzt es nicht.
|
||||
4. **Wege an der Anmeldung vorbei:** keine neuen.
|
||||
|
||||
**Abdeckung** (Abschnitt 3 „Magic Link“, dazu Bremse, Sitzung und CSRF für den
|
||||
neuen Weg): 14 Anforderungen geprüft.
|
||||
- 13 erfüllt, 0 verletzt. Vorher waren es 4, sie sind in diesem PR behoben.
|
||||
- 1 nicht angestrebt (6.6.2, Bindung des Links an das anfragende Gerät): Der
|
||||
Link soll auch auf einem anderen Gerät gehen.
|
||||
|
||||
## Sofort beheben
|
||||
|
||||
Keine.
|
||||
|
||||
## In diesem PR behoben
|
||||
|
||||
### 1. Mail-Kontingent und Postfach ließen sich fluten — niedrig (ASVS 6.3.1, 6.6.3)
|
||||
**Wo:** `app/api/auth/mail/request/route.ts`
|
||||
**Was passierte:** Mit wechselnden IPs ließen sich an eine bekannte, bestätigte
|
||||
Adresse rund 280 Mails am Tag schicken. Insgesamt waren bis zu 60 Anfragen je
|
||||
Viertelstunde möglich. Das reicht, um das Tageskontingent von Resend zu
|
||||
verbrauchen und die Person zu nerven.
|
||||
**Fix:** Je Adresse 3 Anfragen in 15 Minuten und 10 am Tag; gemeinsamer Topf
|
||||
30 Anfragen je Stunde; je IP wie bisher 10 in 15 Minuten.
|
||||
|
||||
### 2. „Adresse gehört schon jemand anderem“ verriet Konten — niedrig (ASVS 6.3.7)
|
||||
**Wo:** `app/api/me/email/route.ts`
|
||||
**Was passierte:** Wer angemeldet war, konnte durch Eintragen fremder Adressen
|
||||
prüfen, wer auf der Box ein Konto hat, auch in anderen Haushalten.
|
||||
**Fix:** Die Antwort ist immer gleich. Der Link in der Bestätigungsmail greift
|
||||
dann nicht (`consumeMailToken` prüft die Adresse).
|
||||
|
||||
### 3. Mail-Sitzungen überlebten das Entfernen der Adresse — niedrig (ASVS 7.4.x)
|
||||
**Wo:** `app/api/me/email/route.ts`, `lib/auth/mail-login.ts`
|
||||
**Was passierte:** Wer merkt, dass jemand sein Postfach mitliest, und die
|
||||
Adresse entfernt, beendete damit nicht die Sitzung, die über diese Adresse
|
||||
begann.
|
||||
**Fix:** Adresse entfernen oder eine neue bestätigen beendet alle Sitzungen mit
|
||||
`via = 'mail'`.
|
||||
|
||||
### 4. Mail-Sitzungen lebten so lange wie Passkey-Sitzungen — niedrig (ASVS 7.3.x)
|
||||
**Wo:** `lib/auth/session.ts`
|
||||
**Fix:** Mail-Sitzungen gelten 30 Tage gleitend statt 180.
|
||||
|
||||
Dazu als Härtung: Der Absendername wird ohne Steuerzeichen und Anführungszeichen
|
||||
in den Mailkopf gesetzt, damit niemand über das Feld einen eigenen Kopf
|
||||
einschleust. Ein Test wacht darüber.
|
||||
|
||||
## Bald angehen
|
||||
|
||||
Nichts Neues. Aus dem letzten Lauf sind weiter offen:
|
||||
- `kein-anmeldeprotokoll`
|
||||
- `keine-csp-hsts`
|
||||
- `sitzung-ohne-hoechstdauer`
|
||||
|
||||
## Später / Härtung
|
||||
|
||||
- **Antwortzeit:** Für eine bekannte Adresse legt die Anfrage zusätzlich einen
|
||||
Token an, das sind einige Millisekunden. Der Versand selbst läuft im
|
||||
Hintergrund. Über das Netz der Box lässt sich der Unterschied kaum messen.
|
||||
Bewertung: Info.
|
||||
- **Mail-Scanner:** Sie verbrauchen keine Links, weil das Einlösen einen Tipp
|
||||
braucht. Ein Scanner, der Knöpfe drückt, würde die Person in seinem Browser
|
||||
anmelden, nicht im Browser des Angreifers. Bewertung: Info.
|
||||
|
||||
## Offene Fragen
|
||||
|
||||
- **Echter Versand** über Resend. Erst prüfbar, wenn Kai den Schlüssel eingetragen
|
||||
hat: Testmail schicken, SPF, DKIM und DMARC von `foodplanhero.de` für Resend
|
||||
prüfen.
|
||||
- **Öffentlicher Weg auf der Box:** `/anmelden/mail` hinter Envoy und Authelia
|
||||
einmal ausprobieren (CLAUDE.md, Plattform 4).
|
||||
|
||||
## Was gut ist
|
||||
|
||||
- Nur der Hash des Tokens wird gespeichert. Ein Link gilt einmal: 15 Minuten
|
||||
zum Anmelden, 24 Stunden zum Bestätigen. Ein neuer Link macht ältere ungültig.
|
||||
- Die Adresse im Link kommt aus `instance`, nie aus dem Host-Kopf. Damit kann
|
||||
niemand den Link über einen gefälschten Host auf eine fremde Seite umbiegen.
|
||||
- Die Antwort auf „Link schicken“ ist immer gleich und schnell, weil der Versand
|
||||
im Hintergrund läuft.
|
||||
- Nach dem Öffnen nimmt `history.replaceState` den Token aus der Adresszeile.
|
||||
- `noMailSession` sitzt an jedem Weg, der Zugang schafft oder entzieht. Der
|
||||
Browser-Test prüft vier davon mit echter Mail-Sitzung.
|
||||
- **Der Resend-Schlüssel**
|
||||
- geht nur hinein,
|
||||
- liegt verschlüsselt im Tresor,
|
||||
- wird nie zurückgegeben,
|
||||
- steht nicht in der Seite (Test).
|
||||
- Mails kommen ohne Bilder von außen und ohne Tracking. Alle Werte im HTML sind
|
||||
escaped (Test).
|
||||
+3
-3
@@ -68,13 +68,13 @@ test("an admin invites a member by a single-use link", async ({ browser }) => {
|
||||
await maike.page.getByRole("button", { name: "Passkey anlegen" }).click();
|
||||
await expect(maike.page).toHaveURL(/\/$/);
|
||||
// Neue Person: einmal „So funktioniert Lunch“, danach „Wo stehen wir?“.
|
||||
await expect(maike.page.getByText("So funktioniert Lunch · 1 von 3")).toBeVisible();
|
||||
await expect(maike.page.getByText("So funktioniert foodplanhero · 1 von 3")).toBeVisible();
|
||||
await maike.page.getByRole("button", { name: "Weiter" }).click();
|
||||
await maike.page.getByRole("button", { name: "Weiter" }).click();
|
||||
await maike.page.getByRole("button", { name: "Los geht's" }).click();
|
||||
await expect(maike.page.getByText(/So funktioniert Lunch/)).toHaveCount(0);
|
||||
await expect(maike.page.getByText(/So funktioniert foodplanhero/)).toHaveCount(0);
|
||||
await maike.page.reload();
|
||||
await expect(maike.page.getByText(/So funktioniert Lunch/)).toHaveCount(0);
|
||||
await expect(maike.page.getByText(/So funktioniert foodplanhero/)).toHaveCount(0);
|
||||
await expect(maike.page.getByText("Eine neue Runde eröffnen.")).toBeVisible(); // Mitglieder dürfen eröffnen
|
||||
await maike.page.goto("/mehr");
|
||||
await expect(maike.page.locator("#invite-name")).toHaveCount(0);
|
||||
|
||||
+1
-1
@@ -145,7 +145,7 @@ test.describe("receipts", () => {
|
||||
// Preis je 100 g, so wie Lunch ihn sich merkt; ohne Packung eine Warnung.
|
||||
await expect(pasta.getByTestId("unit-price")).toHaveText("= 0,36 € je 100 g");
|
||||
await pasta.getByLabel("Packung in g").fill("");
|
||||
await expect(pasta).toContainText("Ohne Packungsgröße merkt sich Lunch keinen Preis.");
|
||||
await expect(pasta).toContainText("Ohne Packungsgröße merkt sich foodplanhero keinen Preis.");
|
||||
await pasta.getByLabel("Packung in g").fill("500");
|
||||
|
||||
// Klopapier gehört zu keinem Gericht: nach links wischen (26.11.33).
|
||||
|
||||
+158
-7
@@ -153,7 +153,7 @@ test.describe("recipe link", () => {
|
||||
recipeYield: "4 Portionen",
|
||||
totalTime: "PT45M",
|
||||
image: "/bild.jpg",
|
||||
recipeIngredient: ["250 g rote Linsen", "2 Zwiebeln", "1 Becher Sahne", "1 Handvoll Glück"],
|
||||
recipeIngredient: ["250 g rote Linsen", "2 Zwiebeln", "1 Becher Sahne", "1 Schuss Milch", "1 Handvoll Glück"],
|
||||
recipeInstructions: [{ "@type": "HowToStep", text: "Zwiebeln anschwitzen." }, { "@type": "HowToStep", text: "Linsen dazu und weich kochen." }],
|
||||
},
|
||||
],
|
||||
@@ -195,16 +195,21 @@ test.describe("recipe link", () => {
|
||||
await expect(page.getByRole("note").filter({ hasText: "Nach Regeln in Abschnitte eingeordnet" })).toBeVisible();
|
||||
await expect(page.getByLabel("Abschnitt von Schritt 1")).toHaveValue("cook");
|
||||
const amounts = page.getByRole("textbox", { name: "Menge", exact: true });
|
||||
await expect(amounts).toHaveCount(3);
|
||||
await expect(amounts).toHaveCount(4);
|
||||
await expect(amounts.nth(0)).toHaveValue("250");
|
||||
await expect(amounts.nth(1)).toHaveValue("2");
|
||||
await expect(amounts.nth(2)).toHaveValue("");
|
||||
// Sahne im Becher: Menge fehlt — Speichern sagt es, statt die Zeile wegzulassen.
|
||||
// Becher ist das Gebinde der Sahne (26.11.39): 1 Packung zu 200 ml.
|
||||
await expect(amounts.nth(2)).toHaveValue("1");
|
||||
await expect(page.getByRole("combobox", { name: "Einheit" }).nth(2).locator("option:checked")).toHaveText("Packung (200 ml)");
|
||||
await expect(amounts.nth(3)).toHaveValue("");
|
||||
// Ein Schuss Milch: Menge fehlt — Speichern sagt es, statt die Zeile wegzulassen.
|
||||
await page.getByRole("button", { name: "Speichern" }).click();
|
||||
await expect(page.locator("main [role=alert]")).toContainText("fehlt die Menge");
|
||||
await amounts.nth(2).fill("200");
|
||||
await amounts.nth(3).fill("50");
|
||||
await page.getByRole("button", { name: "Speichern" }).click();
|
||||
await expect(page.getByRole("heading", { level: 1 })).toHaveText("Linsensuppe vom Blog");
|
||||
// Gespeichert unter „Ausprobieren“ — und die Seite sagt es (26.11.41).
|
||||
await expect(page.getByRole("note").filter({ hasText: "Steht unter „Ausprobieren“" })).toBeVisible();
|
||||
await expect(page.locator("main img").first()).toHaveAttribute("src", /\/api\/fotos\//);
|
||||
await expect(page.locator(`main a[href="${origin}/rezept"]`)).toBeVisible();
|
||||
});
|
||||
@@ -289,7 +294,7 @@ test.describe("cookbook photo and AI setting", () => {
|
||||
test("without an image model the photo page says how to set it up", async ({ page }) => {
|
||||
await page.goto("/gerichte/hinzufuegen");
|
||||
await page.getByRole("link", { name: /Kochbuch fotografieren/ }).click();
|
||||
await expect(page.getByText("braucht Lunch ein Bildmodell")).toBeVisible();
|
||||
await expect(page.getByText("braucht foodplanhero ein Bildmodell")).toBeVisible();
|
||||
await page.getByRole("link", { name: "AI einrichten" }).click();
|
||||
await expect(page).toHaveURL(/\/mehr\/ki$/);
|
||||
});
|
||||
@@ -322,7 +327,7 @@ test.describe("cookbook photo and AI setting", () => {
|
||||
await page.getByRole("button", { name: "Rezept lesen" }).click();
|
||||
await expect(page.locator("#title")).toHaveValue("Kartoffelsalat aus dem Kochbuch");
|
||||
await expect(page.getByRole("note").first()).toContainText("Von der AI gelesen");
|
||||
await expect(page.getByRole("note").filter({ hasText: "Von der AI in die Lunch-Form gebracht" })).toBeVisible();
|
||||
await expect(page.getByRole("note").filter({ hasText: "Von der AI in die foodplanhero-Form gebracht" })).toBeVisible();
|
||||
await expect(page.getByLabel("Schritt 1", { exact: true })).toHaveValue("Kartoffeln waschen.");
|
||||
await expect(page.getByLabel("Abschnitt von Schritt 3")).toHaveValue("serve");
|
||||
await fillMissingAmounts(page);
|
||||
@@ -356,3 +361,149 @@ test.describe("cookbook photo and AI setting", () => {
|
||||
await expect(page.getByRole("note").first()).toContainText("Von der AI gelesen");
|
||||
});
|
||||
});
|
||||
|
||||
// Produktgruppen und eigene Zutaten (26.11.38, Kai: „den Oberbegriff Pasta eigentlich besser“).
|
||||
test("a group term shows the group with its kinds; an own ingredient and a remembered product", async ({ page }) => {
|
||||
await page.goto("/gerichte/neu");
|
||||
await page.fill("#title", "Gnocchi in Salbeibutter");
|
||||
const search = page.getByRole("combobox", { name: "Zutat suchen" }).first();
|
||||
await search.fill("Nudeln");
|
||||
const options = page.getByRole("listbox").getByRole("option");
|
||||
await expect(options.first()).toContainText("Pasta · beliebige Sorte");
|
||||
await expect(page.getByRole("option", { name: "Spaghetti", exact: true })).toBeVisible();
|
||||
await expect(page.getByRole("option", { name: "Penne", exact: true })).toBeVisible();
|
||||
|
||||
await search.fill("Gnocchi Hausmacher");
|
||||
await page.getByRole("option", { name: "„Gnocchi Hausmacher“ als neue Zutat anlegen" }).click();
|
||||
const create = page.getByRole("group", { name: "Neue Zutat" });
|
||||
await create.getByLabel("Gehört zu").selectOption({ label: "Pasta" });
|
||||
await expect(create.getByLabel("Regal im Laden")).toHaveCount(0);
|
||||
await create.getByRole("button", { name: "Anlegen" }).click();
|
||||
await expect(search).toHaveValue("Gnocchi Hausmacher");
|
||||
await page.getByRole("textbox", { name: "Menge", exact: true }).first().fill("500");
|
||||
await page.getByRole("button", { name: "Produkt hinterlegen" }).click();
|
||||
await page.getByLabel("Produkt für Gnocchi Hausmacher").fill("Rana Gnocchi");
|
||||
await page.getByLabel("Für alle Gerichte mit Gnocchi Hausmacher merken").check();
|
||||
await page.getByLabel("Schritt 1", { exact: true }).fill("Gnocchi in Salzwasser garen.");
|
||||
await page.getByRole("button", { name: "Speichern" }).click();
|
||||
await expect(page.getByRole("heading", { level: 1 })).toHaveText("Gnocchi in Salbeibutter");
|
||||
|
||||
// Ein zweites Gericht bekommt das gemerkte Produkt gleich beim Wählen.
|
||||
await page.goto("/gerichte/neu");
|
||||
await page.fill("#title", "Gnocchi-Auflauf");
|
||||
await page.getByRole("combobox", { name: "Zutat suchen" }).first().fill("Gnocchi Haus");
|
||||
await page.getByRole("option", { name: /Gnocchi Hausmacher.*eigene/ }).click();
|
||||
await expect(page.getByText("Euer Produkt für alle Gerichte: Rana Gnocchi")).toBeVisible();
|
||||
await expect(page.getByRole("button", { name: "Anderes Produkt für dieses Gericht" })).toBeVisible();
|
||||
await page.getByRole("textbox", { name: "Menge", exact: true }).first().fill("400");
|
||||
await page.getByLabel("Schritt 1", { exact: true }).fill("Gnocchi in die Form geben.");
|
||||
await page.getByRole("button", { name: "Speichern" }).click();
|
||||
await expect(page.locator("main")).toContainText("Rana Gnocchi");
|
||||
|
||||
// Wieder aus dem Pool, damit der Plan danach denselben Bestand vorschlägt.
|
||||
for (const title of ["Gnocchi-Auflauf", "Gnocchi in Salbeibutter"]) {
|
||||
await page.goto("/gerichte");
|
||||
await page.getByRole("link", { name: new RegExp(title) }).click();
|
||||
await page.getByRole("button", { name: "Entfernen" }).click();
|
||||
await expect(page).toHaveURL(/entfernt=/);
|
||||
}
|
||||
});
|
||||
|
||||
// Löffel und Gebinde (26.11.39, Kai: „Teelöffel, Esslöffel … eine Dose als Einheit“).
|
||||
test("spoons and cans: the ingredient preselects its measure, the dish shows spoons and grams", async ({ page }) => {
|
||||
await page.goto("/gerichte/neu");
|
||||
await page.fill("#title", "Tomatensoße vom Blech");
|
||||
const search = page.getByRole("combobox", { name: "Zutat suchen" });
|
||||
const unit = page.getByRole("combobox", { name: "Einheit" });
|
||||
await search.first().fill("Olivenöl");
|
||||
await page.getByRole("option", { name: "Olivenöl", exact: true }).click();
|
||||
await expect(unit.first()).toHaveValue("tbsp");
|
||||
await page.getByRole("textbox", { name: "Menge", exact: true }).first().fill("2");
|
||||
|
||||
await page.getByRole("button", { name: "Zutaten" }).click();
|
||||
await search.nth(1).fill("gehackte Tomaten");
|
||||
await page.getByRole("option", { name: /Gehackte Tomaten/ }).first().click();
|
||||
// Die Dose wird angeboten, mit Größe, aber nicht vorgewählt.
|
||||
await expect(unit.nth(1)).toHaveValue("g");
|
||||
await unit.nth(1).selectOption("can");
|
||||
await expect(unit.nth(1).locator("option:checked")).toHaveText("Dose (400 g)");
|
||||
await expect(page.getByText("1 Dose = 400 g")).toBeVisible();
|
||||
// Unsere Dose hat 500 g.
|
||||
await page.getByRole("button", { name: "Größe ändern" }).click();
|
||||
await page.getByLabel("Größe einer Dose in g").fill("500");
|
||||
await page.getByRole("button", { name: "Übernehmen" }).click();
|
||||
await expect(page.getByText("1 Dose = 500 g")).toBeVisible();
|
||||
await page.getByRole("textbox", { name: "Menge", exact: true }).nth(1).fill("1");
|
||||
await page.getByLabel("Schritt 1", { exact: true }).fill("Tomaten mit Öl aufs Blech.");
|
||||
await page.getByRole("button", { name: "Speichern" }).click();
|
||||
await expect(page.getByRole("heading", { level: 1 })).toHaveText("Tomatensoße vom Blech");
|
||||
|
||||
// Auf vier Portionen: „2 EL (30 ml) Olivenöl“, „500 g (1 Dose) Gehackte Tomaten“.
|
||||
const list = page.locator("main ul").first();
|
||||
const portions = page.locator("output");
|
||||
for (let i = 0; i < 8 && !(await portions.innerText()).startsWith("4 "); i++) {
|
||||
const n = Number((await portions.innerText()).match(/\d+/)![0]);
|
||||
await page.getByRole("button", { name: n > 4 ? "Eine Portion weniger" : "Eine Portion mehr" }).click();
|
||||
}
|
||||
await expect(list.locator("li", { hasText: "Olivenöl" })).toContainText(/2 EL\s*\(30 ml\) Olivenöl/);
|
||||
await expect(list.locator("li", { hasText: "Gehackte Tomaten" })).toContainText(/500 g\s*\(1 Dose\) Gehackte Tomaten/);
|
||||
await page.getByRole("button", { name: "Eine Portion weniger" }).click();
|
||||
await page.getByRole("button", { name: "Eine Portion weniger" }).click();
|
||||
await expect(list.locator("li", { hasText: "Olivenöl" })).toContainText(/1 EL\s*\(15 ml\)/);
|
||||
await expect(list.locator("li", { hasText: "Gehackte Tomaten" })).toContainText(/250 g\s*\(½ Dose\)/);
|
||||
|
||||
// Bearbeiten zeigt die Mengen im eingegebenen Maß.
|
||||
await page.getByRole("link", { name: "Bearbeiten" }).click();
|
||||
await expect(unit.first()).toHaveValue("tbsp");
|
||||
await expect(page.getByRole("textbox", { name: "Menge", exact: true }).first()).toHaveValue("2");
|
||||
await expect(unit.nth(1)).toHaveValue("can");
|
||||
await expect(page.getByRole("textbox", { name: "Menge", exact: true }).nth(1)).toHaveValue("1");
|
||||
|
||||
// Aufräumen: Größe zurück, Gericht aus dem Pool — damit Plan und Einkauf gleich bleiben.
|
||||
await page.getByRole("button", { name: "Größe ändern" }).click();
|
||||
await page.getByLabel("Größe einer Dose in g").fill("400");
|
||||
await page.getByRole("button", { name: "Übernehmen" }).click();
|
||||
await expect(page.getByText("1 Dose = 400 g")).toBeVisible();
|
||||
await page.goto("/gerichte");
|
||||
await page.getByRole("link", { name: /Tomatensoße vom Blech/ }).click();
|
||||
await page.getByRole("button", { name: "Entfernen" }).click();
|
||||
await expect(page).toHaveURL(/entfernt=/);
|
||||
});
|
||||
|
||||
// Kai: „Neue Gerichte werden nicht gespeichert“ — sie standen unter „Ausprobieren“, ohne dass
|
||||
// die Seite es sagte (26.11.41). Jetzt: Hinweis, Weg dorthin, und mit einem Tipp in den Pool.
|
||||
test("a dish to try says so, links to its tab and moves to the pool with one tap", async ({ page }) => {
|
||||
await page.goto("/gerichte/neu");
|
||||
await page.fill("#title", "Probe-Auflauf");
|
||||
await page.getByRole("combobox", { name: "Zutat suchen" }).first().fill("Zwieb");
|
||||
await page.getByRole("option", { name: "Zwiebeln", exact: true }).click();
|
||||
await page.getByRole("textbox", { name: "Menge", exact: true }).first().fill("2");
|
||||
await page.getByLabel("Erst mal ausprobieren").check();
|
||||
await page.getByRole("button", { name: "Speichern" }).click();
|
||||
await expect(page.getByRole("heading", { level: 1 })).toHaveText("Probe-Auflauf");
|
||||
const note = page.getByRole("note").filter({ hasText: "Steht unter „Ausprobieren“" });
|
||||
await expect(note).toBeVisible();
|
||||
await expect(page.locator("main").getByRole("link", { name: "Gerichte", exact: true })).toHaveAttribute("href", "/gerichte?ansicht=ausprobieren");
|
||||
await note.getByRole("button", { name: "In den Pool" }).click();
|
||||
await expect(note).toHaveCount(0);
|
||||
// Fotos auch aus der Mediathek, mehrere auf einmal (26.11.43): kein capture, multiple.
|
||||
const picker = page.locator("input[type=file]");
|
||||
expect(await picker.getAttribute("capture")).toBeNull();
|
||||
expect(await picker.getAttribute("multiple")).not.toBeNull();
|
||||
const shots = await Promise.all(
|
||||
[[200, 80, 60], [60, 140, 90]].map(async ([r, g, b], i) => ({
|
||||
name: `mediathek-${i}.png`,
|
||||
mimeType: "image/png",
|
||||
buffer: await sharp({ create: { width: 800, height: 600, channels: 3, background: { r: r!, g: g!, b: b! } } }).png().toBuffer(),
|
||||
})),
|
||||
);
|
||||
await picker.setInputFiles(shots);
|
||||
await expect(page.getByRole("heading", { name: "Fotos · 2 von 5" })).toBeVisible();
|
||||
await page.goto("/gerichte");
|
||||
await expect(page.getByRole("link", { name: /Probe-Auflauf/ })).toBeVisible();
|
||||
// Aufräumen, damit der Plan danach denselben Bestand vorschlägt.
|
||||
await page.getByRole("link", { name: /Probe-Auflauf/ }).click();
|
||||
await page.getByRole("button", { name: "Entfernen" }).click();
|
||||
await expect(page).toHaveURL(/entfernt=/);
|
||||
});
|
||||
|
||||
+34
-12
@@ -73,29 +73,51 @@ test("scrolling never moves the bar, even while the address bar comes and goes",
|
||||
}
|
||||
});
|
||||
|
||||
test("after typing, a stale gap is bridged briefly and dropped at the first touch", async ({ page }) => {
|
||||
const shiftOf = (page: Page) => page.getByRole("navigation", { name: "Navigation" }).evaluate((el) => (el as HTMLElement).style.transform);
|
||||
const kbShift = (page: Page) => page.evaluate(() => document.documentElement.style.getPropertyValue("--kb-shift"));
|
||||
|
||||
// 26.11.41 (Kai, Bild: Leiste und „Speichern“ mitten im Bild): iOS rechnet nach der
|
||||
// Tastatur in der Web-App manchmal lange zu kurz — auch nach Berührung und Scrollen.
|
||||
test("after typing, a stuck keyboard gap stays bridged through touch and scroll until iOS recovers", async ({ page }) => {
|
||||
await page.goto("/mehr");
|
||||
const field = page.locator("#kid-name");
|
||||
await field.focus();
|
||||
await expect(page.getByRole("navigation", { name: "Navigation" })).toBeHidden(); // beim Tippen weg
|
||||
// iOS lässt das Layout nach dem Schließen der Tastatur 300 px zu kurz stehen.
|
||||
await moveViewport(page, 300);
|
||||
await moveViewport(page, 300); // iOS lässt das Layout 300 px zu kurz stehen
|
||||
await field.blur();
|
||||
const nav = page.getByRole("navigation", { name: "Navigation" });
|
||||
await expect(nav).toBeVisible();
|
||||
await expect.poll(() => nav.evaluate((el) => (el as HTMLElement).style.transform)).toBe("translateY(300px)");
|
||||
await expect.poll(() => shiftOf(page)).toBe("translateY(300px)");
|
||||
await expect.poll(() => kbShift(page)).toBe("300px");
|
||||
// Berühren, scrollen, über die erste Sekunde hinaus: bleibt unten.
|
||||
await page.evaluate(() => window.dispatchEvent(new Event("touchstart")));
|
||||
await expect.poll(() => nav.evaluate((el) => (el as HTMLElement).style.transform)).toBe("");
|
||||
await page.evaluate(() => window.dispatchEvent(new Event("touchend")));
|
||||
await page.mouse.wheel(0, 400);
|
||||
await page.waitForTimeout(1300);
|
||||
await moveViewport(page, 300);
|
||||
await expect.poll(() => shiftOf(page)).toBe("translateY(300px)");
|
||||
// iOS rechnet wieder richtig: Korrektur weg, Leiste unten.
|
||||
await moveViewport(page, 0);
|
||||
await expect.poll(() => shiftOf(page)).toBe("");
|
||||
await expect.poll(() => kbShift(page)).toBe("");
|
||||
await navAtBottom(page);
|
||||
// Danach ist nichts mehr scharf: eine neue Lücke ohne Tippen bleibt unberührt.
|
||||
await moveViewport(page, 300);
|
||||
await page.waitForTimeout(100);
|
||||
expect(await shiftOf(page)).toBe("");
|
||||
});
|
||||
|
||||
test("the bridge ends by itself after a second, and never starts without typing", async ({ page }) => {
|
||||
test("never without typing; after the first second only a keyboard-sized gap counts", async ({ page }) => {
|
||||
await page.goto("/mehr");
|
||||
const nav = page.getByRole("navigation", { name: "Navigation" });
|
||||
await moveViewport(page, 300); // ohne Tastatur: nichts tun
|
||||
await page.waitForTimeout(100);
|
||||
expect(await nav.evaluate((el) => (el as HTMLElement).style.transform)).toBe("");
|
||||
expect(await shiftOf(page)).toBe("");
|
||||
await moveViewport(page, 0);
|
||||
await page.locator("#kid-name").focus();
|
||||
await page.locator("#kid-name").blur();
|
||||
await expect.poll(() => nav.evaluate((el) => (el as HTMLElement).style.transform)).toBe("translateY(300px)");
|
||||
await expect.poll(() => nav.evaluate((el) => (el as HTMLElement).style.transform), { timeout: 3000 }).toBe("");
|
||||
await page.waitForTimeout(1300);
|
||||
// Gummiband oder Rundung (unter STUCK_MIN): Lunch fasst die Leiste nicht an.
|
||||
await moveViewport(page, 80);
|
||||
await page.waitForTimeout(100);
|
||||
expect(await shiftOf(page)).toBe("");
|
||||
await moveViewport(page, 0);
|
||||
await navAtBottom(page);
|
||||
});
|
||||
@@ -0,0 +1,108 @@
|
||||
import { readdir, readFile } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { expect, test, type Browser, type Page } from "@playwright/test";
|
||||
|
||||
// Anmelden per Link aus der Mail (26.11.40, Kai: Resend). Der Server schreibt jede
|
||||
// Mail nach $LUNCH_DATA/mails (MAIL_TEST_DIR) statt sie zu senden.
|
||||
test.describe.configure({ mode: "serial" });
|
||||
|
||||
const DIR = path.join(process.env.LUNCH_DATA ?? "", "mails");
|
||||
const KAI = "kai@test.example";
|
||||
|
||||
async function mails(to: string): Promise<{ to: string; text: string; subject: string }[]> {
|
||||
const files = (await readdir(DIR).catch(() => [])).sort();
|
||||
const all = await Promise.all(files.map(async (f) => JSON.parse(await readFile(path.join(DIR, f), "utf8"))));
|
||||
return all.filter((m) => m.to === to);
|
||||
}
|
||||
const linkIn = (text: string) => text.match(/https?:\/\/\S+\/anmelden\/mail#\S+/)![0];
|
||||
|
||||
async function fresh(browser: Browser): Promise<Page> {
|
||||
const context = await browser.newContext({ ...test.info().project.use, storageState: undefined });
|
||||
return context.newPage();
|
||||
}
|
||||
|
||||
test("the admin sets up sending with Resend and sends a test mail", async ({ page }) => {
|
||||
await page.goto("/mehr");
|
||||
await expect(page.getByRole("link", { name: /Noch nicht eingerichtet/ })).toBeVisible();
|
||||
await page.goto("/mehr/mail");
|
||||
await expect(page.getByLabel("Server")).toHaveValue("smtp.resend.com");
|
||||
await expect(page.getByLabel("Port", { exact: true })).toHaveValue("465");
|
||||
await expect(page.getByLabel("Benutzer")).toHaveValue("resend");
|
||||
await expect(page.getByLabel("Absender", { exact: true })).toHaveValue("hallo@foodplanhero.de");
|
||||
await page.getByLabel("API-Schlüssel").fill("re_test_not_a_real_key");
|
||||
await page.getByRole("button", { name: "Speichern" }).click();
|
||||
await expect(page.getByText("Ein Schlüssel ist gespeichert.")).toBeVisible();
|
||||
// Der Schlüssel kommt nie zurück in die Seite.
|
||||
expect(await page.content()).not.toContain("re_test_not_a_real_key");
|
||||
await page.getByLabel("Testmail an").fill(KAI);
|
||||
await page.getByRole("button", { name: "Testmail schicken" }).click();
|
||||
await expect(page.getByRole("status")).toContainText("Die Testmail ist unterwegs.");
|
||||
expect((await mails(KAI)).at(-1)?.subject).toBe("Testmail von foodplanhero");
|
||||
});
|
||||
|
||||
test("a person confirms the address through the first link", async ({ page }) => {
|
||||
await page.goto("/mehr");
|
||||
const section = page.locator("#mail");
|
||||
await section.getByLabel("Deine Mailadresse").fill(KAI);
|
||||
await section.getByRole("button", { name: "Bestätigung schicken" }).click();
|
||||
await expect(section.getByRole("status")).toContainText(`Wartet auf Bestätigung: ${KAI}`);
|
||||
const verify = (await mails(KAI)).at(-1)!;
|
||||
expect(verify.subject).toBe("Bitte bestätige deine Adresse");
|
||||
await page.goto(linkIn(verify.text));
|
||||
await expect(page.getByRole("heading", { level: 1 })).toHaveText("Adresse bestätigen");
|
||||
// Der Token verschwindet aus der Adresszeile.
|
||||
expect(page.url()).not.toContain("#");
|
||||
await page.getByRole("button", { name: "Bestätigen" }).click();
|
||||
await expect(page.getByRole("heading", { level: 1 })).toHaveText("Deine Adresse ist bestätigt.");
|
||||
await page.goto("/mehr");
|
||||
await expect(page.locator("#mail")).toContainText(`Bestätigt: ${KAI}`);
|
||||
});
|
||||
|
||||
test("signed out: a link by mail signs in once; unknown addresses get the same answer and no mail", async ({ browser }) => {
|
||||
const page = await fresh(browser);
|
||||
const sent = "Wenn die Adresse bei uns bestätigt ist, kommt gleich eine Mail.";
|
||||
await page.goto("/anmelden");
|
||||
await page.getByRole("button", { name: "Lieber einen Link per Mail?" }).click();
|
||||
await page.getByLabel("Deine Mailadresse").fill("niemand@test.example");
|
||||
await page.getByRole("button", { name: "Link schicken" }).click();
|
||||
await expect(page.getByRole("status")).toContainText(sent);
|
||||
expect(await mails("niemand@test.example")).toHaveLength(0);
|
||||
|
||||
const before = (await mails(KAI)).length;
|
||||
await page.goto("/anmelden");
|
||||
await page.getByRole("button", { name: "Lieber einen Link per Mail?" }).click();
|
||||
await page.getByLabel("Deine Mailadresse").fill(KAI.toUpperCase());
|
||||
await page.getByRole("button", { name: "Link schicken" }).click();
|
||||
await expect(page.getByRole("status")).toContainText(sent);
|
||||
await expect.poll(async () => (await mails(KAI)).length).toBe(before + 1);
|
||||
const link = linkIn((await mails(KAI)).at(-1)!.text);
|
||||
|
||||
await page.goto(link);
|
||||
await expect(page.getByRole("heading", { level: 1 })).toHaveText("Bei foodplanhero anmelden");
|
||||
await page.getByRole("button", { name: "Anmelden" }).click();
|
||||
await expect(page).toHaveURL(/\/$/);
|
||||
|
||||
// Per Mail angemeldet: nur anmelden — kein Gerätelink, keine Einladung, keine Adresse ändern.
|
||||
await page.goto("/mehr");
|
||||
await expect(page.getByText("Du bist per Mail-Link angemeldet.").first()).toBeVisible();
|
||||
const status = await page.evaluate(async () =>
|
||||
Promise.all(
|
||||
[
|
||||
["/api/household/invitations", "POST", { kind: "device" }],
|
||||
["/api/household/invitations", "POST", { kind: "person", name: "Gast" }],
|
||||
["/api/me/email", "PUT", { email: "neu@test.example" }],
|
||||
["/api/household/kid-devices", "POST", { label: "Tablet", kind: "kids" }],
|
||||
].map(async ([url, method, body]) => {
|
||||
const res = await fetch(url as string, { method: method as string, headers: { "content-type": "application/json" }, body: JSON.stringify(body) });
|
||||
return `${res.status} ${(await res.json()).error}`;
|
||||
}),
|
||||
),
|
||||
);
|
||||
expect(status).toEqual(["403 mailSession", "403 mailSession", "403 mailSession", "403 mailSession"]);
|
||||
|
||||
// Derselbe Link ein zweites Mal: verbraucht.
|
||||
const again = await fresh(browser);
|
||||
await again.goto(link);
|
||||
await again.getByRole("button", { name: "Anmelden" }).click();
|
||||
await expect(again.getByRole("heading", { level: 1 })).toHaveText("Dieser Link gilt nicht mehr");
|
||||
});
|
||||
+43
-5
@@ -8,7 +8,7 @@ test("the manifest names the app and offers shortcuts", async ({ request }) => {
|
||||
const res = await request.get("/manifest.webmanifest");
|
||||
expect(res.ok()).toBe(true);
|
||||
const m = await res.json();
|
||||
expect(m).toMatchObject({ name: "Was gibt's?", display: "standalone", start_url: "/", id: "/" });
|
||||
expect(m).toMatchObject({ name: "foodplanhero", display: "standalone", start_url: "/", id: "/" });
|
||||
expect(m.shortcuts.map((s: { url: string }) => s.url)).toEqual(["/wuenschen", "/plan", "/einkauf"]);
|
||||
expect(m.icons.some((i: { purpose?: string }) => i.purpose === "maskable")).toBe(true);
|
||||
});
|
||||
@@ -30,16 +30,16 @@ test("offline: the shopping list opened before still works, other pages explain"
|
||||
await context.setOffline(false);
|
||||
});
|
||||
|
||||
test("Today offers to put Lunch on the home screen, and the hint can be hidden", async ({ page }) => {
|
||||
test("Today offers to put foodplanhero on the home screen, and the hint can be hidden", async ({ page }) => {
|
||||
await page.goto("/");
|
||||
const hint = page.getByRole("complementary", { name: "Lunch auf den Home-Bildschirm" });
|
||||
const hint = page.getByRole("complementary", { name: "foodplanhero auf den Home-Bildschirm" });
|
||||
await expect(hint).toContainText("Zum Home-Bildschirm");
|
||||
await hint.getByRole("button", { name: "Hinweis ausblenden" }).click();
|
||||
await expect(hint).toHaveCount(0);
|
||||
await page.reload();
|
||||
await expect(page.getByRole("complementary", { name: "Lunch auf den Home-Bildschirm" })).toHaveCount(0);
|
||||
await expect(page.getByRole("complementary", { name: "foodplanhero auf den Home-Bildschirm" })).toHaveCount(0);
|
||||
await page.goto("/mehr");
|
||||
await expect(page.getByRole("complementary", { name: "Lunch auf den Home-Bildschirm" })).toBeVisible(); // unter „Mehr“ bleibt er
|
||||
await expect(page.getByRole("complementary", { name: "foodplanhero auf den Home-Bildschirm" })).toBeVisible(); // unter „Mehr“ bleibt er
|
||||
});
|
||||
|
||||
test("the bottom bar steps aside while typing and comes back at the bottom", async ({ page }) => {
|
||||
@@ -76,3 +76,41 @@ test("buttons pinned to the bottom sit on the keyboard while typing, above the b
|
||||
const navTop = Math.round((await nav.boundingBox())!.y);
|
||||
await expect.poll(bottomOf).toBeLessThanOrEqual(navTop);
|
||||
});
|
||||
|
||||
// foodplanhero by Maike (26.11.35): Kai lädt Maikes Foto unter „Mehr“ hoch. Es
|
||||
// erscheint dort, beim Anmelden und auf dem Startbild der Web-App.
|
||||
test("the app is dedicated to Maike: photo, words, sign-in and start image", async ({ page, browser, request }) => {
|
||||
const { default: sharp } = await import("sharp");
|
||||
const jpg = await sharp({ create: { width: 800, height: 800, channels: 3, background: { r: 120, g: 160, b: 200 } } }).jpeg().toBuffer();
|
||||
await page.goto("/mehr");
|
||||
const section = page.locator("#widmung");
|
||||
await expect(section.getByRole("heading", { name: "Für Maike" })).toBeVisible();
|
||||
await section.getByLabel("Name").fill("Maike");
|
||||
await section.getByLabel("Ein paar Sätze").fill("Für Maike, die jeden Tag an alles denkt.");
|
||||
await section.getByLabel("Foto wählen").setInputFiles({ name: "maike.jpg", mimeType: "image/jpeg", buffer: jpg });
|
||||
await expect(section).toContainText("Gewählt: maike.jpg");
|
||||
await section.getByRole("button", { name: "Speichern" }).click();
|
||||
await expect(section.getByRole("status")).toHaveText("Gespeichert.");
|
||||
await expect(section.getByRole("img", { name: "Maike" })).toBeVisible();
|
||||
await expect(section).toContainText("by Maike");
|
||||
await expect(section).toContainText("Für Maike, die jeden Tag an alles denkt.");
|
||||
|
||||
// Beim Anmelden, ohne Sitzung.
|
||||
const context = await browser.newContext({ ...test.info().project.use, storageState: undefined });
|
||||
const signIn = await context.newPage();
|
||||
await signIn.goto("/anmelden");
|
||||
await expect(signIn.getByText("foodplanhero").first()).toBeVisible();
|
||||
await expect(signIn.getByText(/plan\. cook\. smile\./i)).toBeVisible();
|
||||
await expect(signIn.getByRole("img", { name: "Maike" })).toBeVisible();
|
||||
await context.close();
|
||||
|
||||
// Startbild für das iPhone 15: ein PNG in Bildschirmgröße; unbekannte Größen gibt es nicht.
|
||||
const image = await request.get("/startbild/1179x2556");
|
||||
expect(image.headers()["content-type"]).toBe("image/png");
|
||||
const meta = await sharp(Buffer.from(await image.body())).metadata();
|
||||
expect([meta.width, meta.height]).toEqual([1179, 2556]);
|
||||
expect((await request.get("/startbild/100x100")).status()).toBe(404);
|
||||
const html = await (await request.get("/anmelden")).text();
|
||||
expect(html).toContain('rel="apple-touch-startup-image"');
|
||||
expect(html).toContain("/startbild/1179x2556");
|
||||
});
|
||||
@@ -19,6 +19,7 @@ const SIGNED_IN = [
|
||||
{ path: "/gerichte/foto", heading: "Kochbuch fotografieren" },
|
||||
{ path: "/gerichte/sprechen", heading: "Gericht einsprechen" },
|
||||
{ path: "/mehr/ki", heading: "AI" },
|
||||
{ path: "/mehr/mail", heading: "Mails verschicken" },
|
||||
{ path: "/wuenschen", heading: "Wünschen" },
|
||||
{ path: "/plan", heading: "Plan" },
|
||||
{ path: "/einkauf", heading: "Einkaufsliste" },
|
||||
@@ -27,6 +28,7 @@ const SIGNED_IN = [
|
||||
const SIGNED_OUT = [
|
||||
{ path: "/anmelden", heading: "Anmelden" },
|
||||
{ path: "/wiederherstellen", heading: "Zugang wiederherstellen" },
|
||||
{ path: "/anmelden/mail", heading: "Dieser Link gilt nicht mehr" },
|
||||
{ path: "/kinder", heading: "Kein Kindergerät" },
|
||||
{ path: "/offline", heading: "Kein Netz" },
|
||||
];
|
||||
@@ -141,3 +143,22 @@ test("kitchen display: overview", async ({ page, browser }) => {
|
||||
await page.reload();
|
||||
await page.getByRole("button", { name: "Rundgang entfernen" }).click();
|
||||
});
|
||||
|
||||
test("signed out: the sign-in page is centred and its intro has no orphan line", async ({ browser }) => {
|
||||
const context = await browser.newContext({ ...test.info().project.use, storageState: undefined });
|
||||
const page = await context.newPage();
|
||||
await page.goto("/anmelden");
|
||||
const intro = page.getByText("Melde dich mit dem Passkey");
|
||||
const hint = page.getByText("Noch kein Passkey auf diesem Gerät?");
|
||||
for (const el of [intro, hint]) expect(await el.evaluate((e) => getComputedStyle(e).textAlign)).toBe("center");
|
||||
// Ausgeglichene Zeilen: die letzte Zeile der Einleitung ist kein einzelnes Wort.
|
||||
const widths = await intro.evaluate((e) => {
|
||||
const range = document.createRange();
|
||||
range.selectNodeContents(e);
|
||||
const lines = new Map<number, number>();
|
||||
for (const r of range.getClientRects()) lines.set(Math.round(r.top), (lines.get(Math.round(r.top)) ?? 0) + r.width);
|
||||
return [...lines.values()];
|
||||
});
|
||||
if (widths.length > 1) expect(widths.at(-1)!).toBeGreaterThan(widths[0]! / 4);
|
||||
await context.close();
|
||||
});
|
||||
@@ -15,6 +15,19 @@ test("Today offers to open a round, and the round opens", async ({ page }) => {
|
||||
await expect(page.locator("main article h2").first()).toHaveText("Du hast noch 2 Wünsche für den Einkauf am Samstag.");
|
||||
});
|
||||
|
||||
test("tokens, veto and the joker share one line, even on the iPhone", async ({ page }) => {
|
||||
await page.goto("/wuenschen");
|
||||
const joker = page.getByRole("button", { name: "Etwas Neues" });
|
||||
await expect(joker).toHaveText("Neues");
|
||||
const bar = await page.getByText("2 Jetons frei").boundingBox();
|
||||
const button = await joker.boundingBox();
|
||||
const width = page.viewportSize()!.width;
|
||||
// Gleiche Zeile: die Mitten liegen auf einer Höhe, und der Knopf endet am rechten Rand.
|
||||
expect(Math.abs(bar!.y + bar!.height / 2 - (button!.y + button!.height / 2))).toBeLessThan(16);
|
||||
expect(button!.x + button!.width).toBeLessThanOrEqual(width);
|
||||
await expect(page.getByText("1 Veto frei")).toBeVisible();
|
||||
});
|
||||
|
||||
test("each tap spends a token, and the server says when they are gone", async ({ page }) => {
|
||||
await page.goto("/");
|
||||
await page.getByRole("link", { name: "Wünschen" }).click();
|
||||
|
||||
@@ -21,6 +21,15 @@ export async function guardWrite(request: Request, roles: Role[] = WRITERS): Pro
|
||||
return session;
|
||||
}
|
||||
|
||||
/**
|
||||
* Wege, die Zugang schaffen oder entziehen (Geräte, Passkeys, Einladungen,
|
||||
* Kindergeräte, Küchendisplay, Mailweg): nie aus einer Sitzung, die per Mail-Link
|
||||
* begann — sonst wäre jedes Konto nur so sicher wie das Postfach (E-0006, E-0017).
|
||||
*/
|
||||
export function noMailSession(session: Session): Response | null {
|
||||
return session.via === "mail" ? fail("mailSession", 403) : null;
|
||||
}
|
||||
|
||||
/** Für lesende Routen: nur die Sitzung. */
|
||||
export async function guardRead(): Promise<Session | Response> {
|
||||
return (await getSession()) ?? fail("signedOut", 401);
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
import "server-only";
|
||||
import type { PoolClient } from "pg";
|
||||
import { getTranslations } from "next-intl/server";
|
||||
import { isLocale } from "@/lib/locale";
|
||||
import { buttonMail, sendMail } from "@/lib/mail";
|
||||
import { hashToken, randomToken } from "./tokens";
|
||||
|
||||
// Anmelden per Link aus der Mail (26.11.40, E-0006, E-0017). Ein Link gilt einmal
|
||||
// und kurz; gespeichert ist nur sein Hash. Er öffnet /anmelden/mail#login=…, und
|
||||
// erst ein Tipp dort löst ihn per POST ein — ein Mail-Scanner, der Links nur
|
||||
// abruft, verbraucht ihn nicht, und der Token steht in keinem Server-Log.
|
||||
// Die Adresse im Link kommt aus der Tabelle instance, nie aus dem Host-Kopf.
|
||||
|
||||
export type Purpose = "login" | "verify";
|
||||
const LIFETIME_MINUTES: Record<Purpose, number> = { login: 15, verify: 24 * 60 };
|
||||
/** Wer sich per Mail anmelden darf: Erwachsene und Jugendliche, keine Kinder, keine Gäste. */
|
||||
const MAIL_ROLES = ["admin", "member", "teen"];
|
||||
|
||||
export const normalizeEmail = (email: string) => email.trim().toLowerCase();
|
||||
|
||||
/** Legt einen Einmal-Link an; ältere, unbenutzte desselben Zwecks verfallen. Gibt den Klartext-Token zurück. */
|
||||
export async function createMailToken(
|
||||
client: PoolClient,
|
||||
t: { householdId: string; memberId: string; purpose: Purpose; email: string },
|
||||
): Promise<string> {
|
||||
await client.query("delete from mail_tokens where expires_at < now() - interval '1 day'");
|
||||
await client.query("update mail_tokens set used_at = now() where member_id = $1 and purpose = $2 and used_at is null", [t.memberId, t.purpose]);
|
||||
const token = randomToken();
|
||||
await client.query(
|
||||
`insert into mail_tokens (household_id, member_id, purpose, email, token_hash, expires_at)
|
||||
values ($1, $2, $3, $4, $5, now() + make_interval(mins => $6))`,
|
||||
[t.householdId, t.memberId, t.purpose, t.email, hashToken(token), LIFETIME_MINUTES[t.purpose]],
|
||||
);
|
||||
return token;
|
||||
}
|
||||
|
||||
/** Wem gehört eine bestätigte Adresse, die sich per Mail anmelden darf? Läuft in withAuth. */
|
||||
export async function findMailMember(client: PoolClient, email: string) {
|
||||
const { rows } = await client.query(
|
||||
`select id, household_id as "householdId", locale from members
|
||||
where email = $1 and email_verified_at is not null and role = any($2::text[])`,
|
||||
[email, MAIL_ROLES],
|
||||
);
|
||||
return (rows[0] ?? null) as { id: string; householdId: string; locale: string | null } | null;
|
||||
}
|
||||
|
||||
export type Consumed = { purpose: Purpose; memberId: string; householdId: string; email: string };
|
||||
|
||||
/**
|
||||
* Löst einen Link ein: gültig, unbenutzt, und die Adresse gehört noch der Person
|
||||
* (beim Anmelden: weiterhin bestätigt). Danach ist er verbraucht. Läuft in withAuth.
|
||||
*/
|
||||
export async function consumeMailToken(client: PoolClient, token: string): Promise<Consumed | null> {
|
||||
const { rows } = await client.query(
|
||||
`update mail_tokens set used_at = now()
|
||||
where token_hash = $1 and used_at is null and expires_at > now()
|
||||
returning purpose, member_id as "memberId", household_id as "householdId", email`,
|
||||
[hashToken(token)],
|
||||
);
|
||||
const hit = rows[0] as Consumed | undefined;
|
||||
if (!hit) return null;
|
||||
if (hit.purpose === "login") {
|
||||
const member = await findMailMember(client, hit.email);
|
||||
return member?.id === hit.memberId ? hit : null;
|
||||
}
|
||||
// Bestätigen: Gehört die Adresse inzwischen jemand anderem, gilt der Link nicht.
|
||||
const taken = await client.query("select 1 from members where email = $1 and id <> $2", [hit.email, hit.memberId]);
|
||||
if (taken.rowCount) return null;
|
||||
const before = (await client.query("select email from members where id = $1", [hit.memberId])).rows[0]?.email as string | null;
|
||||
const { rowCount } = await client.query(
|
||||
"update members set email = $2, email_verified_at = now() where id = $1 and role = any($3::text[])",
|
||||
[hit.memberId, hit.email, MAIL_ROLES],
|
||||
);
|
||||
// Neue Adresse: Sitzungen, die über die alte begannen, enden.
|
||||
if (rowCount && before && before !== hit.email) await client.query("delete from sessions where member_id = $1 and via = 'mail'", [hit.memberId]);
|
||||
return rowCount ? hit : null;
|
||||
}
|
||||
|
||||
/** Die Mail mit dem Link, in der Sprache der Person. */
|
||||
export async function linkMail(p: { purpose: Purpose; to: string; token: string; origin: string; locale: string | null }) {
|
||||
const locale = isLocale(p.locale) ? p.locale : "de";
|
||||
const t = await getTranslations({ locale, namespace: `mail.${p.purpose}` });
|
||||
return buttonMail({
|
||||
to: p.to,
|
||||
subject: t("subject"),
|
||||
lead: t("lead"),
|
||||
button: t("button"),
|
||||
url: `${p.origin}/anmelden/mail#${p.purpose}=${p.token}`,
|
||||
note: t("note"),
|
||||
});
|
||||
}
|
||||
|
||||
/** Verschickt im Hintergrund: Die Antwort darf nicht verraten, ob es die Adresse gibt — auch nicht durch ihre Dauer. */
|
||||
export function sendInBackground(householdId: string, mail: Promise<Parameters<typeof sendMail>[1]>) {
|
||||
void mail
|
||||
.then((m) => sendMail(householdId, m))
|
||||
.catch((error) => console.error("mail: Versand fehlgeschlagen", (error as Error).message));
|
||||
}
|
||||
+16
-7
@@ -14,6 +14,9 @@ import { hashToken, randomToken } from "./tokens";
|
||||
|
||||
export const SESSION_COOKIE = "lunch_session";
|
||||
const LIFETIME_DAYS = 180;
|
||||
/** Per Mail-Link begonnen: kürzer, weil das Postfach der einzige Faktor ist (26.11.40). */
|
||||
const MAIL_LIFETIME_DAYS = 30;
|
||||
const lifetime = (via: string) => (via === "mail" ? MAIL_LIFETIME_DAYS : LIFETIME_DAYS);
|
||||
|
||||
export type Session = {
|
||||
sessionId: string;
|
||||
@@ -22,29 +25,34 @@ export type Session = {
|
||||
displayName: string;
|
||||
role: Role;
|
||||
householdName: string;
|
||||
/** Womit die Sitzung begann. „mail“ darf nur anmelden: keine Geräte, Passkeys, Einladungen (E-0006). */
|
||||
via: "passkey" | "mail" | "kid";
|
||||
};
|
||||
|
||||
/** Legt eine Sitzung an und setzt den Keks. Aufruf in einer withAuth-Transaktion. */
|
||||
export async function startSession(
|
||||
client: PoolClient,
|
||||
// Begonnen mit einem Passkey (Erwachsene) oder auf einem Kindergerät (lib/auth/kids.ts).
|
||||
member: { id: string; householdId: string; passkeyId?: string; kidDeviceId?: string },
|
||||
member: { id: string; householdId: string; passkeyId?: string; kidDeviceId?: string; viaMail?: boolean },
|
||||
request: Request,
|
||||
secure: boolean,
|
||||
): Promise<void> {
|
||||
const { rows } = await client.query("select locale from members where id = $1", [member.id]);
|
||||
const token = randomToken();
|
||||
const via = member.kidDeviceId ? "kid" : member.viaMail ? "mail" : "passkey";
|
||||
const days = lifetime(via);
|
||||
await client.query(
|
||||
`insert into sessions (token_hash, member_id, household_id, passkey_id, kid_device_id, user_agent, expires_at)
|
||||
values ($1, $2, $3, $4, $7, $5, now() + make_interval(days => $6))`,
|
||||
`insert into sessions (token_hash, member_id, household_id, passkey_id, kid_device_id, user_agent, expires_at, via)
|
||||
values ($1, $2, $3, $4, $7, $5, now() + make_interval(days => $6), $8)`,
|
||||
[
|
||||
hashToken(token),
|
||||
member.id,
|
||||
member.householdId,
|
||||
member.passkeyId ?? null,
|
||||
request.headers.get("user-agent")?.slice(0, 300) ?? null,
|
||||
LIFETIME_DAYS,
|
||||
days,
|
||||
member.kidDeviceId ?? null,
|
||||
via,
|
||||
],
|
||||
);
|
||||
(await cookies()).set(SESSION_COOKIE, token, {
|
||||
@@ -52,7 +60,7 @@ export async function startSession(
|
||||
secure,
|
||||
sameSite: "lax",
|
||||
path: "/",
|
||||
maxAge: LIFETIME_DAYS * 24 * 60 * 60,
|
||||
maxAge: days * 24 * 60 * 60,
|
||||
});
|
||||
// Die Sprache gehört der Person: Was sie gewählt hat, gilt auf jedem Gerät.
|
||||
const locale = rows[0]?.locale;
|
||||
@@ -65,7 +73,7 @@ export async function getSession(): Promise<Session | null> {
|
||||
if (!token) return null;
|
||||
return withAuth(async (client) => {
|
||||
const { rows } = await client.query(
|
||||
`select s.id, s.member_id, s.household_id, s.last_seen_at < now() - interval '1 day' as stale,
|
||||
`select s.id, s.member_id, s.household_id, s.via, s.last_seen_at < now() - interval '1 day' as stale,
|
||||
m.display_name, m.role, h.name as household_name
|
||||
from sessions s
|
||||
join members m on m.id = s.member_id
|
||||
@@ -78,7 +86,7 @@ export async function getSession(): Promise<Session | null> {
|
||||
if (row.stale) {
|
||||
await client.query(
|
||||
"update sessions set last_seen_at = now(), expires_at = now() + make_interval(days => $2) where id = $1",
|
||||
[row.id, LIFETIME_DAYS],
|
||||
[row.id, lifetime(row.via)],
|
||||
);
|
||||
}
|
||||
return {
|
||||
@@ -88,6 +96,7 @@ export async function getSession(): Promise<Session | null> {
|
||||
displayName: row.display_name,
|
||||
role: row.role,
|
||||
householdName: row.household_name,
|
||||
via: row.via,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
+11
-2
@@ -22,6 +22,9 @@ export const TABLES = [
|
||||
"passkeys",
|
||||
"invitations",
|
||||
"kid_devices", // nur Hashes; nach dem Zurückspielen gilt das Tablet weiter
|
||||
"ingredients", // nur die eigenen des Haushalts (WHERE unten); die globalen kommen aus db/seed
|
||||
"household_products",
|
||||
"household_pack_sizes",
|
||||
"stores",
|
||||
"store_aisles",
|
||||
"dishes",
|
||||
@@ -43,15 +46,19 @@ export const TABLES = [
|
||||
"helper_points",
|
||||
"achievements",
|
||||
"household_ai", // Schlüssel verschlüsselt: gehört mit tresor.key zusammen
|
||||
"household_mail", // ebenso: Resend-Schlüssel verschlüsselt (26.11.40)
|
||||
] as const;
|
||||
|
||||
/** Tabellen, die globale und eigene Zeilen mischen: nur die eigenen in den Abzug. */
|
||||
const ONLY_OWN: Record<string, string> = { ingredients: "where t.household_id is not null" };
|
||||
|
||||
/** Bewusst nicht im Abzug, je mit Grund. */
|
||||
export const EXCLUDED: Record<string, string> = {
|
||||
instance: "eigene Zeile im Abzug (box-weit, nicht je Haushalt)",
|
||||
sessions: "kurzlebig; nach dem Zurückspielen meldet sich jede Person mit ihrem Passkey neu an",
|
||||
auth_challenges: "lebt fünf Minuten",
|
||||
auth_attempts: "Bremse, lebt einen Tag",
|
||||
ingredients: "kommt aus db/seed mit festen Kennungen (scripts/seed.mjs), nicht aus dem Haushalt",
|
||||
mail_tokens: "Einmal-Links aus der Mail, gelten höchstens einen Tag",
|
||||
schema_migrations: "gehört zur Datenbank, nicht zu den Daten",
|
||||
starter_dishes: "Vorlage aus db/seed, wird bei jedem Start eingespielt",
|
||||
starter_dish_ingredients: "Vorlage aus db/seed",
|
||||
@@ -92,7 +99,9 @@ export async function createBackup(): Promise<Backup> {
|
||||
const out: Record<string, Record<string, unknown>[]> = {};
|
||||
for (const table of TABLES) {
|
||||
// to_jsonb hält bytea als \x…-Text; jsonb_populate_recordset wandelt beim Zurückspielen zurück.
|
||||
const { rows } = await client.query(`select coalesce(jsonb_agg(to_jsonb(t) order by to_jsonb(t)::text), '[]'::jsonb) as rows from ${table} t`);
|
||||
const { rows } = await client.query(
|
||||
`select coalesce(jsonb_agg(to_jsonb(t) order by to_jsonb(t)::text), '[]'::jsonb) as rows from ${table} t ${ONLY_OWN[table] ?? ""}`,
|
||||
);
|
||||
out[table] = rows[0].rows;
|
||||
}
|
||||
return out;
|
||||
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
+5
-2
@@ -1,6 +1,6 @@
|
||||
import "server-only";
|
||||
import type { PoolClient } from "pg";
|
||||
import { currentPrices, dishCost, priceClasses, type DishCost, type PriceClass, type PricePoint } from "./pricing";
|
||||
import { currentPrices, dishCost, priceClasses, withGroupPrices, type DishCost, type PriceClass, type PricePoint } from "./pricing";
|
||||
import { toBase, type BaseUnit, type InputUnit } from "./units";
|
||||
|
||||
// Preise und Kosten aus der Datenbank (Rechnen in lib/pricing.ts).
|
||||
@@ -25,7 +25,10 @@ export async function loadPrices(client: PoolClient, currency: string): Promise<
|
||||
from default_prices where currency = $1`,
|
||||
[currency],
|
||||
);
|
||||
return currentPrices(rows);
|
||||
const members = new Map<string, string[]>();
|
||||
for (const r of (await client.query("select id, parent_id from ingredients where parent_id is not null")).rows as { id: string; parent_id: string }[])
|
||||
members.set(r.parent_id, [...(members.get(r.parent_id) ?? []), r.id]);
|
||||
return withGroupPrices(currentPrices(rows), members);
|
||||
}
|
||||
|
||||
/** Kosten pro Portion je Gericht (alle oder die genannten). */
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
import "server-only";
|
||||
import type { PoolClient } from "pg";
|
||||
import { withAuth } from "./db";
|
||||
|
||||
// Widmung (26.11.35): „foodplanhero by Maike“. Name, Foto und Text je Haushalt;
|
||||
// das Foto liegt wie die Gerichtsfotos unter /app/data/fotos/<haushalt>/.
|
||||
|
||||
export type Dedication = { name: string | null; text: string | null; photo: string | null };
|
||||
|
||||
export async function getDedication(client: PoolClient): Promise<Dedication> {
|
||||
const { rows } = await client.query(
|
||||
`select dedication_name as name, dedication_text as text, dedication_photo as photo from households limit 1`,
|
||||
);
|
||||
return rows[0] ?? { name: null, text: null, photo: null };
|
||||
}
|
||||
|
||||
/**
|
||||
* Vor der Anmeldung (Anmelden, Startbild) kennt die App keinen Haushalt. Auf einer
|
||||
* Box gibt es in aller Regel genau einen; gezeigt wird der älteste.
|
||||
*/
|
||||
export async function publicDedication(): Promise<(Dedication & { householdId: string }) | null> {
|
||||
return withAuth(async (c) => {
|
||||
const { rows } = await c.query(
|
||||
`select id as "householdId", dedication_name as name, dedication_text as text, dedication_photo as photo
|
||||
from households order by created_at limit 1`,
|
||||
);
|
||||
return rows[0] ?? null;
|
||||
});
|
||||
}
|
||||
|
||||
/** Version des Fotos für die Adresse (?v=…), aus der Prüfsumme im Dateinamen. */
|
||||
export const photoVersion = (photo: string | null) => photo?.split("-").at(-1)?.replace(".webp", "") ?? "";
|
||||
+60
-18
@@ -5,14 +5,15 @@ import { BASES, TAGS } from "./categories";
|
||||
import type { IngredientEntry } from "./ingredient-search";
|
||||
import { allIngredients } from "./ingredients";
|
||||
import { linkIngredients, orderSections, SECTIONS, sectionsByRules, styleByRules, type Section, type StepIngredient } from "./recipe-style";
|
||||
import { toBase, type BaseUnit, type InputUnit } from "./units";
|
||||
import { impliedKitchenUnit, isKitchenUnit, isPackKind, toBase, type BaseUnit, type InputUnit, type KitchenUnit, type PackKind } from "./units";
|
||||
|
||||
// Gerichte des Haushalts lesen und schreiben. Mengen kommen so, wie man sie
|
||||
// für das ganze Rezept eintippt (z. B. „500 g für 4 Portionen“), und werden
|
||||
// hier in Basiseinheiten pro Portion umgerechnet (CLAUDE.md, Regel 2).
|
||||
// Alle Funktionen laufen in withHousehold(…).
|
||||
|
||||
export const INPUT_UNITS = ["g", "kg", "ml", "l", "piece", "tbsp", "tsp", "pinch"] as const;
|
||||
// Seit 26.11.39 auch Gebinde: Dose, Glas, Packung, Bund — Größe aus der Zutat oder dem Produkt.
|
||||
export const INPUT_UNITS = ["g", "kg", "ml", "l", "piece", "tbsp", "tsp", "pinch", "can", "jar", "pack", "bunch"] as const;
|
||||
|
||||
export const dishInput = z.object({
|
||||
title: z.string().trim().min(1).max(120),
|
||||
@@ -37,6 +38,8 @@ export const dishInput = z.object({
|
||||
name: z.string().trim().min(1).max(80),
|
||||
pack: z.number().positive().max(100000).nullable().optional(),
|
||||
cookMinutes: z.number().int().min(1).max(240).nullable().optional(),
|
||||
// „Für alle Gerichte merken“ (26.11.38): gilt dann für den ganzen Haushalt.
|
||||
remember: z.boolean().optional(),
|
||||
})
|
||||
.nullable()
|
||||
.optional(),
|
||||
@@ -78,13 +81,19 @@ export type DishDetail = DishSummary & {
|
||||
note: string | null;
|
||||
isStaple: boolean;
|
||||
product: Product | null;
|
||||
/** Eingegebenes Küchenmaß („2 EL“, „1 Dose“), sonst null (26.11.39). */
|
||||
displayUnit: KitchenUnit | null;
|
||||
/** Gebinde der Zutat und seine Größe in der Basiseinheit: Produkt, sonst Haushalt, sonst Vorgabe. */
|
||||
packKind: PackKind | null;
|
||||
packSize: number | null;
|
||||
kitchenUnit: KitchenUnit | null;
|
||||
}[];
|
||||
// timerFrom: Name des Produkts, wenn der Timer von seiner Packung stammt.
|
||||
steps: { section: Section; text: string; timerSeconds: number | null; ingredientIds: string[]; timerFrom?: string }[];
|
||||
};
|
||||
|
||||
/** Produkt an einer Zutat des Gerichts; pack in der Basiseinheit der Zutat. */
|
||||
export type Product = { name: string; pack: number | null; cookMinutes: number | null };
|
||||
export type Product = { name: string; pack: number | null; cookMinutes: number | null; fromHousehold?: boolean };
|
||||
|
||||
/** Alle Namen einer Zutat (jede Sprache, Einzahl, Synonyme) — für die Zuordnung zu Schritten. */
|
||||
export function stepIngredient(e: IngredientEntry): StepIngredient {
|
||||
@@ -104,11 +113,13 @@ export async function getDish(client: PoolClient, id: string, locale: string): P
|
||||
const dish = (await client.query(`select ${summaryColumns}, source_url as "sourceUrl" from dishes where id = $1 and archived_at is null`, [id]))
|
||||
.rows[0];
|
||||
if (!dish) return null;
|
||||
const entries = new Map((await allIngredients()).map((i) => [i.id, i]));
|
||||
const entries = new Map((await allIngredients(client)).map((i) => [i.id, i]));
|
||||
const ingredients = (
|
||||
await client.query(
|
||||
`select ingredient_id, qty_per_portion, unit, note, is_staple, product, product_pack::float as product_pack, product_cook_minutes
|
||||
from dish_ingredients where dish_id = $1 order by position`,
|
||||
`select di.ingredient_id, di.qty_per_portion, di.unit, di.note, di.is_staple, di.product, di.product_pack::float as product_pack, di.display_unit,
|
||||
di.product_cook_minutes, hp.product as house_product, hp.product_pack::float as house_pack, hp.cook_minutes as house_cook
|
||||
from dish_ingredients di left join household_products hp on hp.ingredient_id = di.ingredient_id
|
||||
where di.dish_id = $1 order by di.position`,
|
||||
[id],
|
||||
)
|
||||
).rows.map((r) => ({
|
||||
@@ -119,7 +130,20 @@ export async function getDish(client: PoolClient, id: string, locale: string): P
|
||||
unit: r.unit,
|
||||
note: r.note,
|
||||
isStaple: r.is_staple,
|
||||
product: r.product ? { name: r.product, pack: r.product_pack, cookMinutes: r.product_cook_minutes } : null,
|
||||
// Produkt am Gericht, sonst das Lieblingsprodukt des Haushalts für diese Zutat (26.11.38).
|
||||
product: r.product
|
||||
? { name: r.product, pack: r.product_pack, cookMinutes: r.product_cook_minutes }
|
||||
: r.house_product
|
||||
? { name: r.house_product, pack: r.house_pack, cookMinutes: r.house_cook, fromHousehold: true }
|
||||
: null,
|
||||
displayUnit: r.display_unit as KitchenUnit | null,
|
||||
packKind: entries.get(r.ingredient_id)?.packKind ?? null,
|
||||
packSize: ((r.product ? r.product_pack : r.house_pack) ?? entries.get(r.ingredient_id)?.packSize ?? null) as number | null,
|
||||
kitchenUnit: entries.get(r.ingredient_id)?.kitchenUnit ?? null,
|
||||
})).map((i) => ({
|
||||
...i,
|
||||
// Ohne eingegebenes Maß (ältere Gerichte, Vorlagen): Löffel oder Gebinde, wo es passt (26.11.39).
|
||||
displayUnit: i.displayUnit ?? impliedKitchenUnit(i.qtyPerPortion * 4, i.unit, i.kitchenUnit, i.packKind, i.packSize),
|
||||
}));
|
||||
const rows = (
|
||||
await client.query("select section, text, timer_seconds, ingredient_ids from dish_steps where dish_id = $1 order by position", [id])
|
||||
@@ -161,16 +185,26 @@ export class InvalidAmount extends Error {}
|
||||
|
||||
/** Legt an (id leer) oder ersetzt Inhalt, Zutaten und Schritte. Gibt die Kennung zurück. */
|
||||
export async function saveDish(client: PoolClient, householdId: string, memberId: string, input: DishInput, id?: string): Promise<string> {
|
||||
const all = await allIngredients();
|
||||
const units = new Map(all.map((i) => [i.id, i.unit]));
|
||||
const all = await allIngredients(client);
|
||||
const byId = new Map(all.map((i) => [i.id, i]));
|
||||
const house = new Map(
|
||||
(await client.query("select ingredient_id, product_pack::float as pack from household_products")).rows.map((r) => [r.ingredient_id as string, r.pack as number | null]),
|
||||
);
|
||||
const rows = input.ingredients.map((i, position) => {
|
||||
const base = units.get(i.ingredientId);
|
||||
if (!base) throw new InvalidAmount(i.ingredientId);
|
||||
const total = toBase(i.qty, i.unit as InputUnit, base);
|
||||
const entry = byId.get(i.ingredientId);
|
||||
if (!entry) throw new InvalidAmount(i.ingredientId);
|
||||
const base = entry.unit;
|
||||
const unit = i.unit as InputUnit;
|
||||
// Ein Gebinde nur, wenn die Zutat eines hat — „1 Dose Zwiebeln“ gibt es nicht.
|
||||
if (isPackKind(unit) && entry.packKind !== unit) throw new InvalidAmount(i.ingredientId);
|
||||
// Packung des Produkts: bei einem Gebinde in der Basiseinheit („400“ g), sonst in der Einheit der Zeile.
|
||||
const pack = i.product?.pack ? toBase(i.product.pack, isPackKind(unit) ? base : unit, base) : null;
|
||||
// Größe des Gebindes: Produkt am Gericht, sonst Lieblingsprodukt, sonst Haushalt bzw. Vorgabe.
|
||||
const size = (i.product ? pack : null) ?? house.get(i.ingredientId) ?? entry.packSize ?? null;
|
||||
const total = toBase(i.qty, unit, base, size);
|
||||
if (total === null) throw new InvalidAmount(i.ingredientId);
|
||||
// Packung in der Einheit der Zeile → Basiseinheit („500 g“, „1 kg“ → 1000).
|
||||
const pack = i.product?.pack ? toBase(i.product.pack, i.unit as InputUnit, base) : null;
|
||||
return { ...i, base, perPortion: Math.round((total / input.portions) * 1000) / 1000, position, pack };
|
||||
const displayUnit = isKitchenUnit(unit) ? unit : null;
|
||||
return { ...i, base, perPortion: Math.round((total / input.portions) * 1000) / 1000, position, pack, displayUnit };
|
||||
});
|
||||
const values = [
|
||||
input.title,
|
||||
@@ -202,11 +236,19 @@ export async function saveDish(client: PoolClient, householdId: string, memberId
|
||||
for (const r of rows) {
|
||||
await client.query(
|
||||
`insert into dish_ingredients (household_id, dish_id, ingredient_id, qty_per_portion, unit, note, position,
|
||||
product, product_pack, product_cook_minutes)
|
||||
values ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)`,
|
||||
product, product_pack, product_cook_minutes, display_unit)
|
||||
values ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)`,
|
||||
[householdId, dishId, r.ingredientId, r.perPortion, r.base, r.note ?? null, r.position,
|
||||
r.product?.name ?? null, r.product ? r.pack : null, r.product?.cookMinutes ?? null],
|
||||
r.product?.name ?? null, r.product ? r.pack : null, r.product?.cookMinutes ?? null, r.displayUnit],
|
||||
);
|
||||
if (r.product?.remember) {
|
||||
await client.query(
|
||||
`insert into household_products (household_id, ingredient_id, product, product_pack, cook_minutes) values ($1, $2, $3, $4, $5)
|
||||
on conflict (household_id, ingredient_id) do update set product = excluded.product, product_pack = excluded.product_pack,
|
||||
cook_minutes = excluded.cook_minutes, updated_at = now()`,
|
||||
[householdId, r.ingredientId, r.product.name, r.pack, r.product.cookMinutes ?? null],
|
||||
);
|
||||
}
|
||||
}
|
||||
// Abschnitte: was das Formular sagt, sonst nach den Verben; Zutaten je Schritt aus dem Text.
|
||||
const own = all.filter((e) => input.ingredients.some((i) => i.ingredientId === e.id)).map(stepIngredient);
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
// Version der App-Symbole (docs/icon/lunch.svg → scripts/app-icons.mjs). Ändert sich
|
||||
// das Symbol, hier hochzählen: Die Adressen ändern sich, Browser und Service Worker
|
||||
// holen das neue statt des gemerkten (26.11.42, Kochmütze mit Herz).
|
||||
export const ICON_VERSION = "2";
|
||||
export const iconUrl = (path: string) => `${path}?v=${ICON_VERSION}`;
|
||||
@@ -9,8 +9,16 @@ export type Nameable = { names: Record<string, string>; forms?: Forms | null; un
|
||||
/** Einzahl bis einschließlich 1 — also auch für ½ und ¼. */
|
||||
export const isOne = (qty: number) => qty > 0 && qty <= 1 + 1e-9;
|
||||
|
||||
// „Gehackte Tomaten (Dose)“ neben „400 g (1 Dose)“ wäre doppelt: Steht das Gebinde
|
||||
// schon in der Menge (26.11.39), fällt der Hinweis am Namen weg.
|
||||
const PACK_HINT = /\s*\((dose|glas|tin|can|jar|bocal|boîte|lata|tarro)\)$/i;
|
||||
|
||||
/** Für Anzeigen, die Name und Formen schon in der Sprache haben (Gerichtsseite, Kochmodus). */
|
||||
export function labelFor(i: { name: string; forms: { one: string; other: string } | null; unit: string }, qty: number): string {
|
||||
export function labelFor(
|
||||
i: { name: string; forms: { one: string; other: string } | null; unit: string; displayUnit?: string | null },
|
||||
qty: number,
|
||||
): string {
|
||||
if (i.displayUnit && ["can", "jar", "pack"].includes(i.displayUnit)) return i.name.replace(PACK_HINT, "");
|
||||
if (i.unit !== "piece" || !i.forms) return i.name;
|
||||
return isOne(qty) ? i.forms.one : i.forms.other;
|
||||
}
|
||||
|
||||
Loaded 100 of 154 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user