Compare commits

...
3 Commits
Author SHA1 Message Date
kai d43b7bdf3f Up to five photos per dish with a chosen preview (26.11.23) (#24)
release / which version (push) Successful in 2s
release / olares chart · sanity (push) Successful in 4s
release / app (push) Successful in 1m3s
release / tag and release (push) Successful in 2s
2026-11-07 07:48:24 +00:00
kai e0db3252d5 Veto only with a counter-suggestion from the pool (26.11.22) (#23)
release / which version (push) Successful in 2s
release / olares chart · sanity (push) Successful in 4s
release / app (push) Successful in 1m2s
release / tag and release (push) Successful in 2s
2026-11-07 07:25:07 +00:00
kai 44edd5c86b Products per dish ingredient: cooking timer per pack, product on the list (26.11.21) (#22)
release / which version (push) Successful in 4s
release / olares chart · sanity (push) Successful in 5s
release / app (push) Successful in 1m2s
release / tag and release (push) Successful in 3s
2026-11-07 07:12:15 +00:00
46 changed files with 997 additions and 118 deletions

No files matched your search

+29 -2
View File
@@ -7,12 +7,14 @@
> **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.20 — alle neun Arbeitspakete aus `docs/PROJEKTSTART.md` sind gebaut:
> **Status:** 26.11.23 — 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
> (V2a, 26.11.16), Olares Router als Standard (26.11.17), untere Leiste am iPhone (26.11.18),
> Rolle „Jugendlich“ (26.11.19), Rezepte in einer Form (26.11.20). Offen sind V2b (Kassenbons)
> Rolle „Jugendlich“ (26.11.19), Rezepte in einer Form (26.11.20),
> Produkte je Gericht (26.11.21), Veto mit Gegenvorschlag (26.11.22),
> bis zu 5 Fotos je Gericht (26.11.23). Offen sind V2b (Kassenbons)
> und der Magic Link.
> **Letzte Aktualisierung:** 7. November 2026
@@ -336,6 +338,31 @@ Vorlagen ersetzt. `tests/seed.test.ts` prüft die Dateien. Ein Haushalt
durch `fromStyleReply`: **jede Zahl im neuen Text muss in der Quelle stehen**, sonst
gilt die Regel. Ergebnis ist ein Entwurf; ein Mensch speichert.
## Produkte je Gericht (seit 26.11.21)
- An `dish_ingredients`: `product` (Name), `product_pack` (Basiseinheit),
`product_cook_minutes` (Migration 0012) — je Gericht, nicht je Haushalt (Kai).
Die Kochzeit ersetzt den Timer eines Kochschritts, der die Zutat nennt
(`withProductTimers` in `lib/dishes.ts`, `timerFrom`). Einkaufsliste:
`productLabel` in `lib/shopping.ts`, Packung des Produkts statt der Standardgrößen.
## Veto mit Gegenvorschlag (seit 26.11.22, Maike)
- Ein Veto braucht `alternativeDishId`: ein Gericht aus dem Pool (nicht „Ausprobieren“),
das in der Runde noch niemand nennt (`lib/wishes.ts`, `alternatives`). Der Ersatz ist
ein Wunsch mit `wishes.veto_id` (Migration 0013), kostet keinen Jeton; Veto und Ersatz
gehen nur zusammen weg.
- **Tests:** Scheitert `beforeAll`, zählt vitest die Tests als übersprungen, nicht als
rot — nach jedem Lauf mit Datenbank muss „skipped“ 0 sein.
## Fotos je Gericht (seit 26.11.23)
- Bis zu 5 in `dish_photos` (Migration 0014, im Abzug), Dateien unter `/app/data/fotos/`.
`dishes.photo_path` bleibt das **Vorschaubild** — alle Anzeigen lesen weiter nur das.
Logik in `lib/dish-photos.ts` (`addPhoto`: erstes wird Vorschau, sechstes abgelehnt;
`setCover`; `removePhoto`: nächstes rückt nach). Hinzufügen: `WISHERS` (auch Kinder,
über „Foto vom Essen“ in der Bewertungskarte); Vorschau und Entfernen: `PLANNERS`.
## Rollen
- `admin`, `member`, `teen` (seit 26.11.19), `child`, `guest`. Wer was darf, steht nur
+2 -2
View File
@@ -21,7 +21,7 @@ metadata:
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.
icon: https://git.aimighty.olares.de/aimighty/bilder/raw/branch/main/lunch/icon.png
version: 26.11.20
version: 26.11.23
categories:
- Applications
@@ -61,7 +61,7 @@ permission:
appData: true
spec:
versionName: '26.11.20'
versionName: '26.11.23'
featuredImage: https://git.aimighty.olares.de/aimighty/bilder/raw/branch/main/lunch/icon.png
promoteImage:
@@ -39,6 +39,7 @@ export default async function EditDishPage({ params }: { params: Promise<{ id: s
ingredient: { id: i.ingredientId, name: i.name, unit: i.unit },
qty: i.qtyPerPortion * PORTIONS,
note: i.note,
product: i.product,
})),
steps: dish.steps.map((s) => ({ text: s.text, section: s.section, timerMinutes: s.timerSeconds ? Math.round(s.timerSeconds / 60) : null })),
}}
+9 -2
View File
@@ -8,6 +8,9 @@ import { PortionScaler } from "@/components/dishes/portion-scaler";
import { requireSession } from "@/lib/auth/session";
import { withHousehold } from "@/lib/db";
import { getDish } from "@/lib/dishes";
import { listPhotos } from "@/lib/dish-photos";
import { WISHERS } from "@/lib/wishes";
import { PhotoGallery } from "@/components/dishes/photo-gallery";
import { Confidence } from "@/components/costs/confidence";
import { CostSection } from "@/components/costs/cost-section";
import { STAPLE_SQL, dishCosts, householdCurrency, loadPrices } from "@/lib/costs";
@@ -23,11 +26,12 @@ export default async function DishPage({ params }: { params: Promise<{ id: strin
const locale = await getLocale();
const t = await getTranslations("dishes");
const tc = await getTranslations("costs");
const { dish, people, cost, prices, currency, staples } = await withHousehold(session.householdId, async (c) => {
const { dish, people, cost, prices, currency, staples, photos } = await withHousehold(session.householdId, async (c) => {
const currency = await householdCurrency(c);
const prices = await loadPrices(c, currency);
return {
dish: await getDish(c, id, locale),
photos: await listPhotos(c, id),
people: (await c.query("select count(*)::int as n from members where role <> 'guest'")).rows[0].n as number,
cost: (await dishCosts(c, prices, [id])).get(id) ?? null,
prices,
@@ -39,6 +43,8 @@ export default async function DishPage({ params }: { params: Promise<{ id: strin
});
if (!dish) notFound();
const canWrite = session.role === "admin" || session.role === "member";
// Fotos hinzufügen dürfen alle, die mitessen; Vorschau und Entfernen nur, wer Gerichte pflegt.
const canAddPhoto = (WISHERS as readonly string[]).includes(session.role);
const meta = [dish.effortMinutes ? t("minutes", { n: dish.effortMinutes }) : null, dish.base ? t(`bases.${dish.base}`) : null]
.filter(Boolean)
.join(" · ");
@@ -54,7 +60,7 @@ export default async function DishPage({ params }: { params: Promise<{ id: strin
>
<ChevronLeft aria-hidden className="size-6" />
</Link>
{canWrite ? <PhotoButton id={dish.id} hasPhoto={Boolean(dish.photo)} /> : null}
{canAddPhoto ? <PhotoButton id={dish.id} hasPhoto={Boolean(dish.photo)} count={photos.length} /> : null}
</div>
<div className="flex flex-col gap-5 px-4">
<header className="flex flex-col gap-1">
@@ -68,6 +74,7 @@ export default async function DishPage({ params }: { params: Promise<{ id: strin
</p>
) : null}
</header>
{photos.length ? <PhotoGallery dishId={dish.id} title={dish.title} photos={photos} canManage={canWrite} /> : null}
{canWrite ? <DishActions id={dish.id} /> : null}
<PortionScaler ingredients={dish.ingredients} steps={dish.steps} initialPortions={Math.min(8, Math.max(2, people))} />
<CostSection
+5 -25
View File
@@ -1,29 +1,9 @@
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";
import { POST as addToCollection } from "../photos/route";
export const dynamic = "force-dynamic";
// Eigenes Foto am Gericht (Konzept: „Die Fotos der eigenen Gerichte tragen die Oberfläche“).
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 form = await request.formData().catch(() => null);
const file = form?.get("photo");
if (!(file instanceof File)) return fail("invalid", 400);
const old = await withHousehold(session.householdId, async (c) => (await c.query("select photo_path from dishes where id = $1", [id])).rows[0]);
if (!old) return fail("notFound", 404);
let relative: string;
try {
relative = await storePhoto(session.householdId, id, file);
} catch (error) {
if (error instanceof PhotoRejected) return fail("photo", 400);
throw error;
}
await withHousehold(session.householdId, (c) => c.query("update dishes set photo_path = $2, updated_at = now() where id = $1", [id, relative]));
if (old.photo_path && old.photo_path !== relative) await removePhoto(old.photo_path);
return json({ photo: relative });
// Früher: ein Foto je Gericht. Seit 26.11.23 fügt diese Adresse ein Foto zur
// Sammlung hinzu (app/api/dishes/[id]/photos), damit ältere Oberflächen weiter gehen.
export async function POST(request: Request, context: { params: Promise<{ id: string }> }) {
return addToCollection(request, context);
}
@@ -0,0 +1,29 @@
import { guardWrite, isResponse } from "@/lib/auth/guard";
import { fail, json } from "@/lib/auth/http";
import { PLANNERS } from "@/lib/auth/roles";
import { withHousehold } from "@/lib/db";
import { removePhoto, setCover } from "@/lib/dish-photos";
export const dynamic = "force-dynamic";
const ok = (s: string) => /^[0-9a-f-]{36}$/.test(s);
// Vorschaubild wählen — nur, wer Gerichte pflegt.
export async function PUT(request: Request, { params }: { params: Promise<{ id: string; photoId: string }> }) {
const { id, photoId } = await params;
const session = await guardWrite(request, [...PLANNERS]);
if (isResponse(session)) return session;
if (!ok(id) || !ok(photoId)) return fail("invalid", 400);
const done = await withHousehold(session.householdId, (c) => setCover(c, id, photoId));
return done ? json({ ok: true }) : fail("notFound", 404);
}
// Foto entfernen — nur, wer Gerichte pflegt.
export async function DELETE(request: Request, { params }: { params: Promise<{ id: string; photoId: string }> }) {
const { id, photoId } = await params;
const session = await guardWrite(request, [...PLANNERS]);
if (isResponse(session)) return session;
if (!ok(id) || !ok(photoId)) return fail("invalid", 400);
const done = await withHousehold(session.householdId, (c) => removePhoto(c, id, photoId));
return done ? json({ ok: true }) : fail("notFound", 404);
}
+25
View File
@@ -0,0 +1,25 @@
import { guardWrite, isResponse } from "@/lib/auth/guard";
import { fail, json } from "@/lib/auth/http";
import { withHousehold } from "@/lib/db";
import { addPhoto } from "@/lib/dish-photos";
import { PhotoRejected } from "@/lib/photos";
import { WISHERS } from "@/lib/wishes";
export const dynamic = "force-dynamic";
// Foto hinzufügen: alle, die mitessen (auch Kinder nach dem Kochen), bis fünf je Gericht.
export async function POST(request: Request, { params }: { params: Promise<{ id: string }> }) {
const { id } = await params;
const session = await guardWrite(request, [...WISHERS]);
if (isResponse(session)) return session;
if (!/^[0-9a-f-]{36}$/.test(id)) return fail("invalid", 400);
const form = await request.formData().catch(() => null);
const file = form?.get("photo");
if (!(file instanceof File)) return fail("invalid", 400);
try {
return json(await withHousehold(session.householdId, (c) => addPhoto(c, session.householdId, id, session.memberId, file)), 201);
} catch (error) {
if (error instanceof PhotoRejected) return fail(error.message === "full" ? "full" : error.message === "dish" ? "notFound" : "photo", error.message === "dish" ? 404 : 400);
throw error;
}
}
+4 -5
View File
@@ -3,17 +3,16 @@ import { fail, json, readJson } from "@/lib/auth/http";
import { dishInput, InvalidAmount, saveDish } from "@/lib/dishes";
import { withHousehold } from "@/lib/db";
import { fetchPublic } from "@/lib/fetch-safe";
import { storePhotoBytes } from "@/lib/photos";
import { addPhoto } from "@/lib/dish-photos";
export const dynamic = "force-dynamic";
// Das Bild einer importierten Seite: holen wie die Seite (lib/fetch-safe.ts),
// verkleinern wie ein eigenes Foto. Klappt es nicht, bleibt das Gericht ohne Bild.
async function attachImage(householdId: string, dishId: string, url: string) {
async function attachImage(householdId: string, dishId: string, memberId: string, url: string) {
try {
const { body } = await fetchPublic(url, "image");
const relative = await storePhotoBytes(householdId, dishId, body);
await withHousehold(householdId, (c) => c.query("update dishes set photo_path = $2 where id = $1", [dishId, relative]));
await withHousehold(householdId, (c) => addPhoto(c, householdId, dishId, memberId, body));
} catch {
// ohne Bild weiter
}
@@ -27,7 +26,7 @@ export async function POST(request: Request) {
if (!body.success) return fail("invalid", 400);
try {
const id = await withHousehold(session.householdId, (c) => saveDish(c, session.householdId, session.memberId, body.data));
if (body.data.imageUrl) await attachImage(session.householdId, id, body.data.imageUrl);
if (body.data.imageUrl) await attachImage(session.householdId, id, session.memberId, body.data.imageUrl);
return json({ id }, 201);
} catch (error) {
if (error instanceof InvalidAmount) return fail("amount", 400);
+23
View File
@@ -0,0 +1,23 @@
import { guardRead, isResponse } from "@/lib/auth/guard";
import { fail } from "@/lib/auth/http";
import { withHousehold } from "@/lib/db";
import { readPhoto } from "@/lib/photos";
export const dynamic = "force-dynamic";
// Ein Foto aus der Sammlung eines Gerichts — nur für den eigenen Haushalt (Zeilensicherheit).
export async function GET(_: Request, { params }: { params: Promise<{ id: string; photoId: string }> }) {
const { id, photoId } = await params;
const session = await guardRead();
if (isResponse(session)) return session;
if (!/^[0-9a-f-]{36}$/.test(id) || !/^[0-9a-f-]{36}$/.test(photoId)) return fail("invalid", 400);
const row = await withHousehold(session.householdId, async (c) =>
(await c.query("select path from dish_photos where id = $1 and dish_id = $2", [photoId, id])).rows[0],
);
if (!row) return fail("notFound", 404);
const body = await readPhoto(row.path).catch(() => null);
if (!body) return fail("notFound", 404);
return new Response(new Uint8Array(body), {
headers: { "content-type": "image/webp", "cache-control": "private, max-age=31536000, immutable" },
});
}
+1 -1
View File
@@ -8,7 +8,7 @@ export const dynamic = "force-dynamic";
const dishId = z.string().uuid();
const add = z.object({ dishId, note: z.string().max(120).nullable().optional(), wantsToCook: z.boolean().optional(), veto: z.boolean().optional() });
const add = z.object({ dishId, note: z.string().max(120).nullable().optional(), wantsToCook: z.boolean().optional(), veto: z.boolean().optional(), alternativeDishId: z.string().uuid().optional() });
const change = z.object({ dishId, note: z.string().max(120).nullable(), wantsToCook: z.boolean() });
export async function POST(request: Request) {
+2 -1
View File
@@ -13,7 +13,7 @@ import { formatQuantity, type BaseUnit } from "@/lib/units";
import { cn } from "@/lib/utils";
type Ingredient = { ingredientId: string; name: string; forms: { one: string; other: string } | null; qtyPerPortion: number; unit: BaseUnit; note: string | null };
type Step = { section: Section; text: string; timerSeconds: number | null; ingredientIds: string[] };
type Step = { section: Section; text: string; timerSeconds: number | null; ingredientIds: string[]; timerFrom?: string };
type Running = { step: number; endsAt: number | null; left: number; done: boolean };
const mmss = (s: number) => `${Math.floor(s / 60)}:${String(Math.max(0, Math.round(s % 60))).padStart(2, "0")}`;
@@ -244,6 +244,7 @@ export function CookingMode({
onToggle={() => toggleTimer(index, step.timerSeconds!)}
/>
) : null}
{step.timerSeconds && step.timerFrom ? <p className="text-sm text-muted-foreground">{t("timerFromProduct", { product: step.timerFrom })}</p> : null}
</section>
) : null}
</div>
+31 -3
View File
@@ -1,14 +1,14 @@
"use client";
import { Heart, ThumbsDown, ThumbsUp } from "lucide-react";
import { Camera, Heart, ThumbsDown, ThumbsUp } from "lucide-react";
import { useRouter } from "next/navigation";
import { useTranslations } from "next-intl";
import { useState } from "react";
import { useRef, useState } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { cn } from "@/lib/utils";
type ToRate = { slotId: string; title: string; cookName: string | null; isCook: boolean; thanked: boolean };
type ToRate = { slotId: string; dishId: string; title: string; cookName: string | null; isCook: boolean; thanked: boolean };
// Bewerten (Konzept, „Bewerten“): Daumen hoch oder runter, optional ein Satz,
// und ein Dankeschön an den Koch. Fünf Sekunden, am Tisch.
@@ -19,6 +19,20 @@ export function RateCard({ item }: { item: ToRate }) {
const [comment, setComment] = useState("");
const [thanked, setThanked] = useState(item.thanked);
const [busy, setBusy] = useState(false);
const [photo, setPhoto] = useState<"idle" | "done" | "full" | "error">("idle");
const file = useRef<HTMLInputElement>(null);
// Foto vom Essen: geht in die Sammlung des Gerichts (bis fünf), auch für Kinder.
async function addPhoto(f: File) {
setBusy(true);
const form = new FormData();
form.append("photo", f);
const res = await fetch(`/api/dishes/${item.dishId}/photos`, { method: "POST", body: form }).catch(() => null);
setBusy(false);
if (file.current) file.current.value = "";
if (res?.ok) setPhoto("done");
else setPhoto((await res?.json().catch(() => ({})))?.error === "full" ? "full" : "error");
}
async function post(url: string, body?: object) {
setBusy(true);
@@ -63,6 +77,20 @@ export function RateCard({ item }: { item: ToRate }) {
</Button>
</form>
) : null}
<input
ref={file}
type="file"
accept="image/*"
capture="environment"
className="sr-only"
tabIndex={-1}
aria-hidden
onChange={(e) => e.target.files?.[0] && addPhoto(e.target.files[0])}
/>
<Button type="button" variant="ghost" disabled={busy || photo === "done" || photo === "full"} onClick={() => file.current?.click()}>
<Camera aria-hidden />
{t(`photo.${photo}`)}
</Button>
{!item.isCook && item.cookName ? (
<Button
type="button"
+10 -7
View File
@@ -12,28 +12,31 @@ import { ErrorNotice } from "@/components/ui/notice";
export function PhotoButton({
id,
hasPhoto,
count = 0,
}: {
id: string;
hasPhoto: boolean;
count?: number;
}) {
const t = useTranslations("dishes.detail");
const router = useRouter();
const input = useRef<HTMLInputElement>(null);
const [busy, setBusy] = useState(false);
const [error, setError] = useState(false);
const [error, setError] = useState<"photo" | "full" | null>(null);
async function upload(file: File) {
setBusy(true);
setError(false);
setError(null);
const form = new FormData();
form.append("photo", file);
const res = await fetch(`/api/dishes/${id}/photo`, {
const res = await fetch(`/api/dishes/${id}/photos`, {
method: "POST",
body: form,
});
setBusy(false);
if (input.current) input.current.value = "";
if (res.ok) router.refresh();
else setError(true);
else setError((await res.json().catch(() => ({}))).error === "full" ? "full" : "photo");
}
return (
@@ -50,16 +53,16 @@ export function PhotoButton({
/>
<Button
variant="secondary"
disabled={busy}
disabled={busy || count >= 5}
onClick={() => input.current?.click()}
className="absolute bottom-3 right-3 bg-background/90 hover:bg-background"
>
<Camera aria-hidden />
{hasPhoto ? t("photoChange") : t("photo")}
{count >= 5 ? t("photoFull") : hasPhoto ? t("photoAdd", { n: count, max: 5 }) : t("photo")}
</Button>
{error ? (
<div className="absolute inset-x-3 top-16">
<ErrorNotice className="bg-background">{t("photoError")}</ErrorNotice>
<ErrorNotice className="bg-background">{t(error === "full" ? "photoFull" : "photoError")}</ErrorNotice>
</div>
) : null}
</>
+64 -6
View File
@@ -1,6 +1,6 @@
"use client";
import { ArrowDown, ArrowUp, Plus, Sparkles, X, Wand2 } from "lucide-react";
import { ArrowDown, ArrowUp, Plus, Sparkles, X, Package, Wand2 } from "lucide-react";
import { useRouter } from "next/navigation";
import { useTranslations } from "next-intl";
import { useEffect, useId, useRef, useState } from "react";
@@ -14,7 +14,8 @@ import { cn } from "@/lib/utils";
import { SECTIONS, type Section } from "@/lib/recipe-style";
type Picked = { id: string; name: string; unit: BaseUnit };
type Row = { key: number; ingredient: Picked | null; qty: string; unit: string; note: string };
// 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 };
type StepRow = { key: number; text: string; timer: string; section: Section | "" };
export type DishFormValue = {
@@ -26,7 +27,13 @@ export type DishFormValue = {
effortMinutes: number | null;
isTrial: boolean;
// Beim Import kann die Menge fehlen (passt nicht zur Zutat) — dann trägt die Person sie ein.
ingredients: { ingredient: Picked; qty: number | null; unit?: string | null; note: string | null }[];
ingredients: {
ingredient: Picked;
qty: number | null;
unit?: string | null;
note: string | null;
product?: { name: string; pack: number | null; cookMinutes: number | null } | null;
}[];
steps: { text: string; timerMinutes: number | null; section?: Section | null }[];
sourceUrl?: string | null;
imageUrl?: string | null;
@@ -69,8 +76,12 @@ export function DishForm({ initial }: { initial?: DishFormValue }) {
qty: i.qty !== null ? formatQty(i.qty) : "",
unit: i.unit && UNITS_FOR[i.ingredient.unit].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,
}))
: [{ key: next(), ingredient: null, qty: "", unit: "g", note: "" }],
: [{ key: next(), ingredient: null, qty: "", unit: "g", note: "", product: "", pack: "", cook: "", open: false }],
);
const [steps, setSteps] = useState<StepRow[]>(
initial?.steps.length
@@ -131,7 +142,19 @@ export function DishForm({ initial }: { initial?: DishFormValue }) {
}
const ingredients = rows
.filter((r) => r.ingredient && r.qty.trim())
.map((r) => ({ ingredientId: r.ingredient!.id, qty: parseNumber(r.qty) ?? -1, unit: r.unit, note: r.note.trim() || null }));
.map((r) => ({
ingredientId: r.ingredient!.id,
qty: parseNumber(r.qty) ?? -1,
unit: r.unit,
note: r.note.trim() || null,
product: r.product.trim()
? {
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,
}
: null,
}));
if (!title.trim() || !n || n < 1 || ingredients.some((i) => !(i.qty > 0))) {
setError("invalid");
return;
@@ -294,10 +317,45 @@ export function DishForm({ initial }: { initial?: DishFormValue }) {
maxLength={120}
onChange={(e) => update(row.key, { note: e.target.value })}
/>
{row.open ? (
<fieldset className="flex flex-col gap-2 rounded-xl border border-border p-3">
<legend className="px-1 text-sm font-medium">{t("form.product")}</legend>
<Label htmlFor={`product-${row.key}`} className="sr-only">
{t("form.productName", { name: row.ingredient?.name ?? "" })}
</Label>
<Input
id={`product-${row.key}`}
placeholder={t("form.productPlaceholder")}
maxLength={80}
value={row.product}
onChange={(e) => update(row.key, { product: e.target.value })}
/>
<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}`) })}
</Label>
<Input id={`pack-${row.key}`} inputMode="decimal" value={row.pack} onChange={(e) => update(row.key, { pack: e.target.value })} />
</div>
<div className="flex flex-col gap-1">
<Label htmlFor={`cook-${row.key}`} className="text-sm">
{t("form.productCook")}
</Label>
<Input id={`cook-${row.key}`} inputMode="numeric" value={row.cook} onChange={(e) => update(row.key, { cook: e.target.value })} />
</div>
</div>
<p className="text-xs text-muted-foreground">{t("form.productHint")}</p>
</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>
)}
</li>
))}
</ul>
<Button type="button" variant="outline" onClick={() => setRows((rs) => [...rs, { key: next(), ingredient: null, qty: "", unit: "g", note: "" }])}>
<Button type="button" variant="outline" onClick={() => setRows((rs) => [...rs, { key: next(), ingredient: null, qty: "", unit: "g", note: "", product: "", pack: "", cook: "", open: false }])}>
<Plus aria-hidden />
{t("form.ingredients")}
</Button>
+107
View File
@@ -0,0 +1,107 @@
"use client";
import { Star, Trash2 } from "lucide-react";
import { useRouter } from "next/navigation";
import { useTranslations } from "next-intl";
import { useRef, useState } from "react";
import { Button } from "@/components/ui/button";
import { ErrorNotice } from "@/components/ui/notice";
import { cn } from "@/lib/utils";
export type GalleryPhoto = { id: string; path: string; isCover: boolean; createdBy: string | null };
const src = (dishId: string, p: GalleryPhoto) => `/api/fotos/${dishId}/${p.id}?v=${p.path.split("-").at(-1)?.replace(".webp", "") ?? ""}`;
// Alle Fotos eines Gerichts (bis fünf). Tippen vergrößert; wer Gerichte pflegt,
// wählt dort das Vorschaubild (Kachel, Plan, Wünschen, Heute) oder entfernt ein Foto.
export function PhotoGallery({ dishId, title, photos, canManage }: { dishId: string; title: string; photos: GalleryPhoto[]; canManage: boolean }) {
const t = useTranslations("dishes.photos");
const router = useRouter();
const dialog = useRef<HTMLDialogElement>(null);
const [open, setOpen] = useState<GalleryPhoto | null>(null);
const [busy, setBusy] = useState(false);
const [error, setError] = useState(false);
async function act(method: "PUT" | "DELETE", photo: GalleryPhoto) {
setBusy(true);
setError(false);
const res = await fetch(`/api/dishes/${dishId}/photos/${photo.id}`, {
method,
headers: { "content-type": "application/json" },
body: method === "PUT" ? JSON.stringify({ cover: true }) : undefined,
}).catch(() => null);
setBusy(false);
if (!res?.ok) return setError(true);
dialog.current?.close();
router.refresh();
}
if (photos.length < 2 && !canManage) return null;
return (
<section aria-labelledby="photos-title" className="flex flex-col gap-2">
<h2 id="photos-title" className="eyebrow">
{t("title", { n: photos.length, max: 5 })}
</h2>
<ul className="-mx-4 flex gap-2 overflow-x-auto px-4 pb-1">
{photos.map((p, i) => (
<li key={p.id} className="shrink-0">
<button
type="button"
onClick={() => {
setOpen(p);
setError(false);
dialog.current?.showModal();
}}
aria-label={t(p.isCover ? "openCover" : "open", { n: i + 1, title })}
className={cn(
"relative block size-24 overflow-hidden rounded-xl focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",
p.isCover && "ring-2 ring-accent",
)}
>
{/* eslint-disable-next-line @next/next/no-img-element -- eigene Fotos, schon verkleinert */}
<img src={src(dishId, p)} alt="" className="size-full object-cover" loading="lazy" />
{p.isCover ? (
<span className="absolute bottom-1 left-1 flex items-center gap-1 rounded-full bg-background/90 px-2 py-0.5 text-xs font-semibold">
<Star aria-hidden className="size-3 fill-current" />
{t("cover")}
</span>
) : null}
</button>
</li>
))}
</ul>
<dialog
ref={dialog}
aria-label={title}
onClose={() => setOpen(null)}
className="m-auto w-full max-w-2xl rounded-3xl bg-background p-0 text-foreground backdrop:bg-black/70"
>
{open ? (
<div className="flex flex-col gap-3 p-3 pb-[calc(0.75rem+env(safe-area-inset-bottom))]">
{/* eslint-disable-next-line @next/next/no-img-element -- eigene Fotos */}
<img src={src(dishId, open)} alt={t("alt", { title })} className="max-h-[70vh] w-full rounded-2xl object-contain" />
{open.createdBy ? <p className="px-1 text-sm text-muted-foreground">{t("by", { name: open.createdBy })}</p> : null}
{error ? <ErrorNotice>{t("error")}</ErrorNotice> : null}
<div className="flex flex-wrap gap-2">
{canManage && !open.isCover ? (
<Button type="button" disabled={busy} onClick={() => act("PUT", open)}>
<Star aria-hidden />
{t("makeCover")}
</Button>
) : null}
{canManage ? (
<Button type="button" variant="outline" disabled={busy} onClick={() => act("DELETE", open)}>
<Trash2 aria-hidden />
{t("remove")}
</Button>
) : null}
<Button type="button" variant="ghost" className="ml-auto" onClick={() => dialog.current?.close()}>
{t("close")}
</Button>
</div>
</div>
) : null}
</dialog>
</section>
);
}
+6 -2
View File
@@ -16,8 +16,9 @@ type Ingredient = {
unit: BaseUnit;
note: string | null;
isStaple: boolean;
product?: { name: string } | null;
};
type Step = { section: Section; text: string; timerSeconds: number | null; ingredientIds: string[] };
type Step = { section: Section; text: string; timerSeconds: number | null; ingredientIds: string[]; timerFrom?: string };
// Zutaten in der gewählten Portionszahl, darunter die Schritte. Die Mengen
// rechnet lib/units.ts — gespeichert ist immer „pro Portion“.
@@ -63,6 +64,7 @@ export function PortionScaler({ ingredients, steps, initialPortions }: { ingredi
<span className="flex-1">
{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}
</span>
{i.isStaple ? <span className="text-xs text-muted-foreground">{t("staple")}</span> : null}
</li>
@@ -99,7 +101,9 @@ export function PortionScaler({ ingredients, steps, initialPortions }: { ingredi
{s.timerSeconds ? (
<p className="flex items-center gap-1 text-sm text-accent">
<Timer aria-hidden className="size-4" />
{t("stepTimer", { n: Math.round(s.timerSeconds / 60) })}
{s.timerFrom
? t("stepTimerProduct", { n: Math.round(s.timerSeconds / 60), product: s.timerFrom })
: t("stepTimer", { n: Math.round(s.timerSeconds / 60) })}
</p>
) : null}
</div>
+48 -3
View File
@@ -21,7 +21,15 @@ export type Tile = {
lastCooked: string | null;
createdAt: string;
};
export type Entry = { dishId: string; memberId: string; memberName: string; note: string | null; wantsToCook: boolean; isVeto: boolean };
export type Entry = {
dishId: string;
memberId: string;
memberName: string;
note: string | null;
wantsToCook: boolean;
isVeto: boolean;
viaVeto?: boolean;
};
type Budget = { tokens: number; tokensLeft: number; vetos: number; vetosLeft: number };
const FILTERS = ["all", "popular", "quick", "longAgo", "new"] as const;
@@ -87,7 +95,7 @@ export function WishBoard({
const data = await res.json().catch(() => ({}));
setBusy(null);
if (!res.ok) {
setError(["noTokens", "noVetos", "noRound", "noTrial", "dish"].includes(data.error) ? data.error : "unknown");
setError(["noTokens", "noVetos", "noRound", "noTrial", "dish", "alternative"].includes(data.error) ? data.error : "unknown");
return null;
}
if (method === "POST" && "vibrate" in navigator) navigator.vibrate?.(15);
@@ -224,6 +232,7 @@ export function WishBoard({
own={mine(open.id)}
budget={budget}
canVeto={canVeto}
alternatives={tiles.filter((x) => !x.isTrial && x.id !== open.id && !(byDish.get(x.id) ?? []).length)}
busy={!!busy}
onCall={async (method, body) => {
const ok = await call(method, "/api/wishes", body, open.id);
@@ -242,6 +251,7 @@ function WishOptions({
own,
budget,
canVeto,
alternatives,
busy,
onCall,
onClose,
@@ -250,6 +260,7 @@ function WishOptions({
own: Entry | undefined;
budget: Budget;
canVeto: boolean;
alternatives: Tile[];
busy: boolean;
onCall: (method: string, body: object) => Promise<void>;
onClose: () => void;
@@ -258,6 +269,39 @@ function WishOptions({
const [note, setNote] = useState(own?.note ?? "");
const [cook, setCook] = useState(own?.wantsToCook ?? false);
const wished = own && !own.isVeto;
// Veto nur mit Gegenvorschlag (Maike): erst ein anderes Gericht wählen, dann gilt das Veto.
const [picking, setPicking] = useState(false);
if (picking) {
return (
<div className="flex flex-col gap-4 p-5 pb-[calc(1.25rem+env(safe-area-inset-bottom))]">
<h2 id="wish-options-title" className="text-2xl">
{t("vetoInstead", { title: tile.title })}
</h2>
<p className="text-sm text-muted-foreground">{t("vetoInsteadHint")}</p>
{alternatives.length ? (
<ul className="flex max-h-[50vh] flex-col overflow-y-auto">
{alternatives.map((a) => (
<li key={a.id}>
<button
type="button"
disabled={busy}
className="flex min-h-11 w-full items-center rounded-xl px-2 text-left hover:bg-muted focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
onClick={() => onCall("POST", { dishId: tile.id, veto: true, alternativeDishId: a.id })}
>
{a.title}
</button>
</li>
))}
</ul>
) : (
<p className="rounded-2xl border border-border p-4 text-sm">{t("vetoNoAlternative")}</p>
)}
<Button type="button" variant="ghost" onClick={() => setPicking(false)}>
{t("back")}
</Button>
</div>
);
}
return (
<form
method="dialog"
@@ -293,12 +337,13 @@ function WishOptions({
<Button type="submit" size="lg" disabled={busy || (!wished && budget.tokensLeft < 1)}>
{wished ? t("saveWish") : t("wishWithToken")}
</Button>
{wished && own?.viaVeto ? <p className="text-sm text-muted-foreground">{t("viaVetoHint")}</p> : null}
{wished ? (
<Button type="button" variant="outline" disabled={busy} onClick={() => onCall("DELETE", { dishId: tile.id })}>
{t("unwish")}
</Button>
) : canVeto && budget.vetos > 0 ? (
<Button type="button" variant="outline" disabled={busy || budget.vetosLeft < 1} onClick={() => onCall("POST", { dishId: tile.id, veto: true })}>
<Button type="button" variant="outline" disabled={busy || budget.vetosLeft < 1} onClick={() => setPicking(true)}>
<ThumbsDown aria-hidden />
{budget.vetosLeft < 1 ? t("noVetoLeft") : t("veto")}
</Button>
+8
View File
@@ -0,0 +1,8 @@
-- Produkte je Gericht (Kai, 7.11.2026): an einer Zutat eines Gerichts das Produkt,
-- das man wirklich nimmt („Barilla Spaghetti Nr. 5“), seine Packungsgröße (in der
-- Basiseinheit der Zutat) und seine Kochzeit laut Packung. Die Kochzeit wird zum
-- Timer des Schritts, der die Zutat kocht; Name und Packung gehen auf die Einkaufsliste.
alter table dish_ingredients
add column product text check (length(trim(product)) between 1 and 80),
add column product_pack numeric(10, 3) check (product_pack > 0),
add column product_cook_minutes integer check (product_cook_minutes between 1 and 240);
+6
View File
@@ -0,0 +1,6 @@
-- Veto nur mit Gegenvorschlag (Maike, 7.11.2026): Wer ein Veto einlegt, wählt ein
-- anderes Gericht aus dem Pool. Dieser Ersatz ist ein Wunsch derselben Person, der
-- keinen Jeton kostet; er hängt am Veto und verschwindet mit ihm.
alter table wishes add column veto_id uuid references wishes (id) on delete cascade;
alter table wishes add constraint wishes_veto_alternative check (not (is_veto and veto_id is not null));
create index wishes_veto_idx on wishes (veto_id) where veto_id is not null;
+24
View File
@@ -0,0 +1,24 @@
-- Bis zu fünf Fotos je Gericht (Kai, 7.11.2026). dishes.photo_path bleibt das
-- Vorschaubild, das Kachel, Plan, Wünschen und Heute zeigen; hier liegen alle Fotos
-- (die Vorschau eingeschlossen). Die Dateien liegen unter /app/data/fotos/.
create table dish_photos (
id uuid primary key default gen_random_uuid(),
household_id uuid not null references households (id) on delete cascade,
dish_id uuid not null,
path text not null,
position integer not null,
created_by uuid,
created_at timestamptz not null default now(),
unique (dish_id, path),
foreign key (dish_id, household_id) references dishes (id, household_id) on delete cascade,
foreign key (created_by, household_id) references members (id, household_id) on delete set null (created_by)
);
create index dish_photos_dish_idx on dish_photos (dish_id, position);
alter table dish_photos enable row level security;
alter table dish_photos force row level security;
create policy dish_photos_household on dish_photos
using (household_id = app_household_id()) with check (household_id = app_household_id());
-- Das bisherige Foto wird Foto 1.
insert into dish_photos (household_id, dish_id, path, position, created_by)
select household_id, id, photo_path, 1, created_by from dishes where photo_path is not null;
+17
View File
@@ -75,3 +75,20 @@ test("free text lands under Other and can be removed", async ({ page }) => {
await page.getByRole("button", { name: "Klopapier entfernen" }).click();
await expect(page.getByText("Klopapier")).toHaveCount(0);
});
test("a product on a dish goes on the list and sets the cooking timer", async ({ page }) => {
await page.goto("/gerichte");
await page.getByRole("link", { name: /Spaghetti Bolognese/ }).click();
await page.getByRole("link", { name: "Bearbeiten" }).click();
await page.getByRole("button", { name: "Produkt hinterlegen" }).first().click();
await page.getByLabel("Produkt für Spaghetti").fill("Barilla Spaghetti Nr. 5");
await page.getByLabel("Packung in g").fill("500");
await page.getByLabel("Kochzeit (Min.)").fill("9");
await page.getByRole("button", { name: "Speichern" }).click();
await expect(page.getByRole("heading", { level: 1 })).toHaveText("Spaghetti Bolognese");
await expect(page.locator("main")).toContainText("Barilla Spaghetti Nr. 5");
await expect(page.locator("ol li", { hasText: "Spaghetti in reichlich Salzwasser" })).toContainText("9 Min. laut Packung (Barilla Spaghetti Nr. 5)");
await page.goto("/einkauf");
await expect(page.locator("main")).toContainText("Barilla Spaghetti Nr. 5");
});
+35
View File
@@ -84,6 +84,41 @@ test("a photo from the phone becomes the dish photo", async ({ page }) => {
expect(res.headers()["content-type"]).toBe("image/webp");
});
test("up to five photos per dish, one of them the preview", async ({ page }) => {
await page.goto("/gerichte");
await page.getByRole("link", { name: /Gemüsecurry/ }).click();
const cover = page.locator("main img").first();
const first = await cover.getAttribute("src");
const colours = [
{ r: 40, g: 120, b: 200 },
{ r: 60, g: 180, b: 90 },
{ r: 200, g: 200, b: 40 },
{ r: 120, g: 40, b: 160 },
];
for (const [i, c] of colours.entries()) {
const png = await sharp({ create: { width: 800, height: 600, channels: 3, background: c } }).png().toBuffer();
await page.locator("input[type=file]").setInputFiles({ name: `bild-${i}.png`, mimeType: "image/png", buffer: png });
await expect(page.getByRole("heading", { name: `Fotos · ${i + 2} von 5` })).toBeVisible();
}
// Das erste bleibt Vorschau; bei fünf ist Schluss.
await expect(cover).toHaveAttribute("src", first!);
await expect(page.getByRole("button", { name: "5 Fotos sind das Maximum" })).toBeDisabled();
// Ein anderes Foto zur Vorschau machen: Seite und Pool zeigen es.
await page.getByRole("button", { name: "Foto 3 von Gemüsecurry mit Reis ansehen" }).click();
await page.getByRole("dialog").getByRole("button", { name: "Als Vorschau" }).click();
await expect(page.getByRole("button", { name: "Foto 3 von Gemüsecurry mit Reis ansehen (Vorschau)" })).toBeVisible();
await expect(cover).not.toHaveAttribute("src", first!);
const chosen = await cover.getAttribute("src");
// Die Vorschau entfernen: das erste Foto rückt nach.
await page.getByRole("button", { name: "Foto 3 von Gemüsecurry mit Reis ansehen (Vorschau)" }).click();
await page.getByRole("dialog").getByRole("button", { name: "Entfernen" }).click();
await expect(page.getByRole("heading", { name: "Fotos · 4 von 5" })).toBeVisible();
await expect(cover).toHaveAttribute("src", first!);
expect(chosen).not.toBe(first);
});
test("removing a dish offers undo instead of asking first", async ({ page }) => {
await page.goto("/gerichte");
await page.getByRole("link", { name: /Flammkuchen/ }).click();
+8 -1
View File
@@ -35,7 +35,14 @@ test("a veto and a reason go through the options sheet", async ({ page }) => {
const sheet = page.getByRole("dialog");
await expect(sheet.getByRole("heading", { name: "Flammkuchen" })).toBeVisible();
await sheet.getByRole("button", { name: "Veto einlegen" }).click();
// Veto nur mit Gegenvorschlag aus dem Pool (Maike); er kostet keinen Jeton.
await expect(sheet.getByRole("heading", { name: "Statt Flammkuchen vorschlagen" })).toBeVisible();
await expect(sheet.getByRole("button", { name: "Spaghetti Bolognese" })).toHaveCount(0); // schon gewünscht
await sheet.getByRole("button", { name: "Gemüsecurry mit Reis" }).click();
await expect(sheet).toBeHidden();
await expect(page.getByText("Veto: du")).toBeVisible();
await expect(page.getByRole("button", { name: /^Wunsch zurücknehmen: Gemüsecurry mit Reis/ })).toBeVisible();
await expect(page.getByText("0 Jetons frei")).toBeVisible();
await expect(page.getByText("Veto vergeben")).toBeVisible();
await page.getByRole("button", { name: "Optionen für Spaghetti Bolognese" }).click();
@@ -67,5 +74,5 @@ test("Today shows the family's wishes", async ({ page }) => {
await expect(page.getByRole("heading", { level: 2 }).first()).toHaveText("Deine Wünsche für Samstag sind abgegeben.");
const list = page.locator("section", { hasText: "Wünsche der Familie" });
await expect(list.getByText("Spaghetti Bolognese")).toBeVisible();
await expect(list.locator("li")).toHaveCount(2);
await expect(list.locator("li")).toHaveCount(3); // dazu der Gegenvorschlag zum Veto
});
+1
View File
@@ -28,6 +28,7 @@ export const TABLES = [
"dish_ingredients",
"dish_steps",
"dish_translations",
"dish_photos", // Pfade; die Dateien liegen ohnehin unter /app/data/fotos
"rounds",
"wishes",
"slots",
+2 -2
View File
@@ -73,12 +73,12 @@ export async function thank(client: PoolClient, householdId: string, slotId: str
);
}
export type ToRate = { slotId: string; title: string; cookName: string | null; isCook: boolean; thanked: boolean };
export type ToRate = { slotId: string; dishId: string; title: string; cookName: string | null; isCook: boolean; thanked: boolean };
/** Gekochtes der letzten drei Tage, das ich noch nicht bewertet habe. */
export async function pendingRatings(client: PoolClient, memberId: string): Promise<ToRate[]> {
const { rows } = await client.query(
`select s.id as "slotId", d.title, m.display_name as "cookName", s.cook_member_id = $1 as "isCook",
`select s.id as "slotId", d.id as "dishId", d.title, m.display_name as "cookName", s.cook_member_id = $1 as "isCook",
exists (select 1 from kudos k where k.slot_id = s.id and k.from_member_id = $1) as thanked
from slots s join dishes d on d.id = s.dish_id left join members m on m.id = s.cook_member_id
where s.cooked_at > now() - interval '3 days'
+67
View File
@@ -0,0 +1,67 @@
import "server-only";
import type { PoolClient } from "pg";
import { PhotoRejected, removePhoto as deleteFile, storePhoto, storePhotoBytes } from "./photos";
// Bis zu fünf Fotos je Gericht (Kai, 7.11.2026). dishes.photo_path ist das
// Vorschaubild (Kachel, Plan, Wünschen, Heute); das erste Foto wird es von selbst.
// Hinzufügen dürfen alle im Haushalt, Vorschau wählen und entfernen nur, wer
// Gerichte pflegt (Routen). Läuft in withHousehold(…).
export const MAX_PHOTOS = 5;
export type DishPhotoView = { id: string; path: string; isCover: boolean; createdBy: string | null };
export async function listPhotos(client: PoolClient, dishId: string): Promise<DishPhotoView[]> {
const { rows } = await client.query(
`select p.id, p.path, p.path = d.photo_path as "isCover", m.display_name as "createdBy"
from dish_photos p join dishes d on d.id = p.dish_id left join members m on m.id = p.created_by
where p.dish_id = $1 order by p.position`,
[dishId],
);
return rows;
}
/** Ein Foto dazu; das erste wird Vorschau. Mehr als fünf lehnt es ab. */
export async function addPhoto(
client: PoolClient,
householdId: string,
dishId: string,
memberId: string | null,
file: File | Buffer,
): Promise<DishPhotoView> {
await client.query("select pg_advisory_xact_lock(hashtext('photos:' || $1))", [dishId]);
const dish = (await client.query("select photo_path from dishes where id = $1 and archived_at is null", [dishId])).rows[0];
if (!dish) throw new PhotoRejected("dish");
const count = (await client.query("select count(*)::int as n, coalesce(max(position), 0) as last from dish_photos where dish_id = $1", [dishId])).rows[0];
if (count.n >= MAX_PHOTOS) throw new PhotoRejected("full");
const path = Buffer.isBuffer(file) ? await storePhotoBytes(householdId, dishId, file) : await storePhoto(householdId, dishId, file as File);
const { rows } = await client.query(
`insert into dish_photos (household_id, dish_id, path, position, created_by) values ($1, $2, $3, $4, $5)
on conflict (dish_id, path) do update set path = excluded.path returning id`,
[householdId, dishId, path, count.last + 1, memberId],
);
if (!dish.photo_path) await client.query("update dishes set photo_path = $2, updated_at = now() where id = $1", [dishId, path]);
return { id: rows[0].id, path, isCover: !dish.photo_path, createdBy: null };
}
export async function setCover(client: PoolClient, dishId: string, photoId: string): Promise<boolean> {
const { rowCount } = await client.query(
`update dishes d set photo_path = p.path, updated_at = now() from dish_photos p
where p.id = $2 and p.dish_id = $1 and d.id = $1`,
[dishId, photoId],
);
return rowCount === 1;
}
/** Foto entfernen; war es die Vorschau, wird das nächste Vorschau (oder keins). */
export async function removePhoto(client: PoolClient, dishId: string, photoId: string): Promise<boolean> {
const gone = (await client.query("delete from dish_photos where id = $1 and dish_id = $2 returning path", [photoId, dishId])).rows[0];
if (!gone) return false;
await client.query(
`update dishes set photo_path = (select path from dish_photos where dish_id = $1 order by position limit 1), updated_at = now()
where id = $1 and photo_path = $2`,
[dishId, gone.path],
);
await deleteFile(gone.path);
return true;
}
+42 -7
View File
@@ -31,6 +31,15 @@ export const dishInput = z.object({
qty: z.number().positive().max(100000),
unit: z.enum(INPUT_UNITS),
note: z.string().trim().max(120).nullable().optional(),
// Produkt, das man nimmt; Packung in der Einheit der Zeile, Kochzeit laut Packung.
product: 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(),
})
.nullable()
.optional(),
}),
)
.max(60),
@@ -68,10 +77,15 @@ export type DishDetail = DishSummary & {
unit: BaseUnit;
note: string | null;
isStaple: boolean;
product: Product | null;
}[];
steps: { section: Section; text: string; timerSeconds: number | null; ingredientIds: string[] }[];
// 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 };
/** Alle Namen einer Zutat (jede Sprache, Einzahl, Synonyme) — für die Zuordnung zu Schritten. */
export function stepIngredient(e: IngredientEntry): StepIngredient {
const forms = Object.values(e.forms ?? {}).flatMap((f) => (f ? [f.one, f.other] : []));
@@ -93,7 +107,8 @@ export async function getDish(client: PoolClient, id: string, locale: string): P
const entries = new Map((await allIngredients()).map((i) => [i.id, i]));
const ingredients = (
await client.query(
"select ingredient_id, qty_per_portion, unit, note, is_staple from dish_ingredients where dish_id = $1 order by position",
`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`,
[id],
)
).rows.map((r) => ({
@@ -104,6 +119,7 @@ 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,
}));
const rows = (
await client.query("select section, text, timer_seconds, ingredient_ids from dish_steps where dish_id = $1 order by position", [id])
@@ -123,7 +139,22 @@ export async function getDish(client: PoolClient, id: string, locale: string): P
rows.map((r) => ({ text: r.text, timerSeconds: r.timer_seconds })),
own,
);
return { ...dish, ingredients, steps };
return { ...dish, ingredients, steps: withProductTimers(steps, ingredients) };
}
/**
* Kochzeit laut Packung: Ein Kochschritt, der eine Zutat mit Produkt-Kochzeit nennt,
* bekommt diese Zeit als Timer („Barilla Nr. 5: 9 Min.“) — sie gilt vor der Zeit im Text.
*/
export function withProductTimers<S extends { section: Section; timerSeconds: number | null; ingredientIds: string[] }>(
steps: S[],
ingredients: { ingredientId: string; product: Product | null }[],
): (S & { timerFrom?: string })[] {
return steps.map((s) => {
if (s.section !== "cook") return s;
const hit = s.ingredientIds.map((id) => ingredients.find((i) => i.ingredientId === id)?.product).find((p) => p?.cookMinutes);
return hit ? { ...s, timerSeconds: hit.cookMinutes! * 60, timerFrom: hit.name } : s;
});
}
export class InvalidAmount extends Error {}
@@ -137,7 +168,9 @@ export async function saveDish(client: PoolClient, householdId: string, memberId
if (!base) throw new InvalidAmount(i.ingredientId);
const total = toBase(i.qty, i.unit as InputUnit, base);
if (total === null) throw new InvalidAmount(i.ingredientId);
return { ...i, base, perPortion: Math.round((total / input.portions) * 1000) / 1000, position };
// 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 values = [
input.title,
@@ -168,9 +201,11 @@ 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)
values ($1, $2, $3, $4, $5, $6, $7)`,
[householdId, dishId, r.ingredientId, r.perPortion, r.base, r.note ?? null, r.position],
`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)`,
[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],
);
}
// Abschnitte: was das Formular sagt, sonst nach den Verben; Zutaten je Schritt aus dem Text.
+4
View File
@@ -28,11 +28,15 @@ export function classifyStep(text: string): Section {
/** Zutaten, die ein Schritt beim Namen nennt (ganze Wörter, auch Wortanfang: „Zwiebel“ in „Zwiebeln“). */
export function linkIngredients(text: string, list: StepIngredient[]): string[] {
const t = text.toLocaleLowerCase("de");
// Wörter des Schritts für zusammengesetzte Namen: „Hackfleisch“ trifft „Rinderhackfleisch“.
const stepWords = t.match(/\p{L}{6,}/gu) ?? [];
return list
.filter((i) =>
i.names.some((n) => {
const name = n.toLocaleLowerCase("de").replace(/\s*\(.*\)\s*/g, "").trim();
if (name.length < 3) return false;
const last = name.split(/\s+/).at(-1)!;
if (stepWords.some((w) => last !== w && last.endsWith(w.replace(/(e|en|n|s)$/, "")))) return true;
// Der Wortstamm reicht („Kartoffeln“ trifft „Kartoffel“), aber nur am Wortanfang.
const stem = name.length > 5 ? name.slice(0, -1) : name;
return new RegExp(`(^|[^\\p{L}])${stem.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}`, "u").test(t);
+22 -3
View File
@@ -39,6 +39,16 @@ export async function defaultAisles(client: PoolClient) {
}
/** Liste an den Plan angleichen: Mengen nachführen, Neues dazu, Weggefallenes (nicht Abgehaktes) raus. */
/** „Barilla Spaghetti Nr. 5“ statt „Spaghetti“; mehrere Produkte: „Spaghetti (Barilla Nr. 5 / De Cecco Nr. 12)“. */
export function productLabel(name: string, products: Set<string> | undefined): string {
const list = [...(products ?? [])];
if (!list.length) return name;
if (list.length > 1) return `${name} (${list.join(" / ")})`;
// Nennt das Produkt die Zutat schon („Barilla Spaghetti Nr. 5“), reicht es; sonst „Spaghetti · Barilla Nr. 5“.
const stem = name.toLocaleLowerCase("de").slice(0, Math.max(4, name.length - 2));
return list[0]!.toLocaleLowerCase("de").includes(stem) ? list[0]! : `${name} · ${list[0]}`;
}
export async function syncList(client: PoolClient, householdId: string, round: Round, locale: string): Promise<void> {
await client.query("select pg_advisory_xact_lock(hashtext('shopping:' || $1))", [round.id]);
const rows = (
@@ -47,7 +57,8 @@ export async function syncList(client: PoolClient, householdId: string, round: R
i.category, i.pack_sizes::float[] as packs,
(i.pantry_default or exists (select 1 from pantry_staples p where p.ingredient_id = i.id)) as pantry,
coalesce(i.names ->> $2, i.names ->> 'de', i.key) as name,
coalesce(i.forms -> $2, i.forms -> 'en') as form
coalesce(i.forms -> $2, i.forms -> 'en') as form,
di.product, di.product_pack::float as product_pack
from slots s join dishes d on d.id = s.dish_id
join dish_ingredients di on di.dish_id = d.id
join ingredients i on i.id = di.ingredient_id
@@ -59,14 +70,22 @@ export async function syncList(client: PoolClient, householdId: string, round: R
const bySlot = new Map<string, PlanSlotInput>();
const packs = new Map<string, number[]>();
const forms = new Map<string, { one: string; other: string }>();
// Produkte je Zutat aus den Gerichten der Runde: Name auf die Liste, Packung statt der Standardgrößen.
const products = new Map<string, Set<string>>();
const productPacks = new Map<string, number[]>();
for (const r of rows) {
const slot: PlanSlotInput = bySlot.get(r.slot) ?? { dishTitle: r.title, portions: r.portions, ingredients: [] };
slot.ingredients.push({ ingredientId: r.ingredient_id, name: r.name, unit: r.unit, qtyPerPortion: r.q, category: r.category, packs: r.packs, pantry: r.pantry });
bySlot.set(r.slot, slot);
packs.set(r.ingredient_id, r.packs ?? []);
if (r.form) forms.set(r.ingredient_id, r.form);
if (r.product) {
products.set(r.ingredient_id, (products.get(r.ingredient_id) ?? new Set()).add(r.product));
if (r.product_pack) productPacks.set(r.ingredient_id, [...(productPacks.get(r.ingredient_id) ?? []), r.product_pack]);
}
}
const lines = withPacks(aggregate([...bySlot.values()], await defaultAisles(client)), (id) => packs.get(id) ?? []);
const lines = withPacks(aggregate([...bySlot.values()], await defaultAisles(client)), (id) => productPacks.get(id) ?? packs.get(id) ?? []);
const label = (l: (typeof lines)[number]) => productLabel(labelFor({ name: l.name, forms: forms.get(l.ingredientId) ?? null, unit: l.unit }, l.qty), products.get(l.ingredientId));
for (const l of lines) {
await client.query(
`insert into shopping_items (household_id, round_id, ingredient_id, label, qty, needed, unit, pack_count, pack_size,
@@ -77,7 +96,7 @@ export async function syncList(client: PoolClient, householdId: string, round: R
pack_count = excluded.pack_count, pack_size = excluded.pack_size, dishes = excluded.dishes,
aisle_position = excluded.aisle_position,
pantry_state = case when excluded.pantry_state is null then null else coalesce(shopping_items.pantry_state, 'ask') end`,
[householdId, round.id, l.ingredientId, labelFor({ name: l.name, forms: forms.get(l.ingredientId) ?? null, unit: l.unit }, l.qty), l.qty, l.needed, l.unit, l.pack?.count ?? null, l.pack?.size ?? null,
[householdId, round.id, l.ingredientId, label(l), l.qty, l.needed, l.unit, l.pack?.count ?? null, l.pack?.size ?? null,
l.dishes, l.aislePosition, l.pantry ? "ask" : null],
);
}
+49 -10
View File
@@ -18,12 +18,14 @@ export type WishEntry = {
note: string | null;
wantsToCook: boolean;
isVeto: boolean;
/** Gegenvorschlag zu einem Veto: kostet keinen Jeton. */
viaVeto: boolean;
};
export async function budget(client: PoolClient, roundId: string, memberId: string): Promise<Budget> {
const { rows } = await client.query(
`select h.tokens_per_round as tokens, h.vetos_per_round as vetos,
count(w.id) filter (where not w.is_veto)::int as wished,
count(w.id) filter (where not w.is_veto and w.veto_id is null)::int as wished,
count(w.id) filter (where w.is_veto)::int as vetoed
from households h
left join wishes w on w.round_id = $1 and w.member_id = $2
@@ -37,7 +39,8 @@ export async function budget(client: PoolClient, roundId: string, memberId: stri
export async function roundWishes(client: PoolClient, roundId: string): Promise<WishEntry[]> {
const { rows } = await client.query(
`select w.dish_id as "dishId", w.member_id as "memberId", m.display_name as "memberName", w.note,
w.wants_to_cook as "wantsToCook", w.is_veto as "isVeto"
w.wants_to_cook as "wantsToCook", w.is_veto as "isVeto",
w.veto_id is not null as "viaVeto"
from wishes w join members m on m.id = w.member_id
where w.round_id = $1
order by w.created_at`,
@@ -54,12 +57,12 @@ export function favorites(entries: WishEntry[]): Set<string> {
}
export class WishRefused extends Error {
constructor(public reason: "noRound" | "noTokens" | "noVetos" | "dish" | "already") {
constructor(public reason: "noRound" | "noTokens" | "noVetos" | "dish" | "already" | "alternative") {
super(reason);
}
}
type WishOptions = { note?: string | null; wantsToCook?: boolean; veto?: boolean };
type WishOptions = { note?: string | null; wantsToCook?: boolean; veto?: boolean; alternativeDishId?: string };
/** Wunsch oder Veto für ein Gericht der offenen Runde. Zählt unter Sperre je Person. */
export async function addWish(client: PoolClient, householdId: string, memberId: string, dishId: string, opts: WishOptions = {}) {
@@ -70,12 +73,45 @@ export async function addWish(client: PoolClient, householdId: string, memberId:
if (!dish) throw new WishRefused("dish");
const b = await budget(client, round.id, memberId);
if (opts.veto ? b.vetosLeft < 1 : b.tokensLeft < 1) throw new WishRefused(opts.veto ? "noVetos" : "noTokens");
const { rowCount } = await client.query(
// Veto nur mit Gegenvorschlag: ein Gericht aus dem Pool, das in dieser Runde noch niemand nennt.
if (opts.veto) {
const alt = opts.alternativeDishId;
const ok =
alt &&
alt !== dishId &&
(
await client.query(
`select 1 from dishes d where d.id = $1 and d.archived_at is null and not d.is_trial
and not exists (select 1 from wishes w where w.round_id = $2 and w.dish_id = d.id)`,
[alt, round.id],
)
).rowCount;
if (!ok) throw new WishRefused("alternative");
}
const { rows } = await client.query(
`insert into wishes (household_id, round_id, member_id, dish_id, note, wants_to_cook, is_veto)
values ($1, $2, $3, $4, $5, $6, $7) on conflict (round_id, member_id, dish_id) do nothing`,
values ($1, $2, $3, $4, $5, $6, $7) on conflict (round_id, member_id, dish_id) do nothing returning id`,
[householdId, round.id, memberId, dishId, opts.note?.trim() || null, !opts.veto && !!opts.wantsToCook, !!opts.veto],
);
if (!rowCount) throw new WishRefused("already");
if (!rows[0]) throw new WishRefused("already");
if (opts.veto) {
await client.query(
`insert into wishes (household_id, round_id, member_id, dish_id, veto_id) values ($1, $2, $3, $4, $5)`,
[householdId, round.id, memberId, opts.alternativeDishId, rows[0].id],
);
}
}
/** Gerichte, die als Gegenvorschlag zu einem Veto taugen: Pool, in der Runde noch von niemandem genannt. */
export async function alternatives(client: PoolClient, roundId: string): Promise<{ id: string; title: string }[]> {
const { rows } = await client.query(
`select d.id, d.title from dishes d
where d.archived_at is null and not d.is_trial
and not exists (select 1 from wishes w where w.round_id = $1 and w.dish_id = d.id)
order by lower(d.title)`,
[roundId],
);
return rows;
}
/** Grund oder „Ich koche das“ an einem eigenen Wunsch ändern. */
@@ -91,12 +127,15 @@ export async function updateWish(client: PoolClient, memberId: string, dishId: s
/** Eigenen Wunsch oder eigenes Veto zurücknehmen (nur solange die Runde offen ist). */
export async function removeWish(client: PoolClient, memberId: string, dishId: string): Promise<boolean> {
const { rowCount } = await client.query(
const { rows } = await client.query(
`delete from wishes where member_id = $1 and dish_id = $2
and round_id = (select id from rounds where status = 'open' order by created_at desc limit 1)`,
and round_id = (select id from rounds where status = 'open' order by created_at desc limit 1)
returning veto_id`,
[memberId, dishId],
);
return rowCount === 1;
// Ein Veto nimmt seinen Gegenvorschlag mit (Fremdschlüssel); der Gegenvorschlag nimmt sein Veto mit.
if (rows[0]?.veto_id) await client.query("delete from wishes where id = $1", [rows[0].veto_id]);
return rows.length === 1;
}
/** Joker „Etwas Neues“: ein zufälliges Gericht aus „Ausprobieren“, das ich noch nicht gewünscht habe. */
+41 -7
View File
@@ -289,11 +289,13 @@
"removed": "„{title}“ ist aus dem Pool entfernt.",
"undo": "Rückgängig",
"photo": "Foto aufnehmen",
"photoChange": "Foto ändern",
"photoError": "Das Foto ließ sich nicht lesen. Nimm ein JPEG, PNG oder HEIC bis 15 MB.",
"stepTimer": "{n} Min.",
"source": "Quelle",
"pieces": "{n, plural, one {Stück} other {Stück}}"
"pieces": "{n, plural, one {Stück} other {Stück}}",
"stepTimerProduct": "{n} Min. laut Packung ({product})",
"photoAdd": "Foto dazu ({n} von {max})",
"photoFull": "5 Fotos sind das Maximum"
},
"form": {
"newTitle": "Neues Gericht",
@@ -348,7 +350,14 @@
"styledByAi": "Von der AI in die Lunch-Form gebracht. Zeiten und Temperaturen stammen aus dem Rezept — bitte kurz prüfen.",
"styledByRules": "Nach Regeln in Abschnitte eingeordnet, Wortlaut unverändert. Mit eingerichteter AI werden die Schritte auch umformuliert.",
"styleFailed": "Das hat nicht geklappt. Die Schritte sind unverändert.",
"section": "Abschnitt von Schritt {n}"
"section": "Abschnitt von Schritt {n}",
"product": "Produkt",
"productName": "Produkt für {name}",
"productPlaceholder": "z. B. Barilla Spaghetti Nr. 5",
"productPack": "Packung in {unit}",
"productCook": "Kochzeit (Min.)",
"productHint": "Die Kochzeit wird zum Timer im Schritt, der die Zutat kocht; Name und Packung stehen auf der Einkaufsliste.",
"addProduct": "Produkt hinterlegen"
},
"addLinkText": "Wir lesen Zutaten und Schritte von der Rezeptseite.",
"link": {
@@ -392,6 +401,18 @@
"prep": "Vorbereiten",
"cook": "Kochen",
"serve": "Anrichten"
},
"photos": {
"title": "Fotos · {n} von {max}",
"cover": "Vorschau",
"open": "Foto {n} von {title} ansehen",
"openCover": "Foto {n} von {title} ansehen (Vorschau)",
"alt": "Foto von {title}",
"by": "von {name}",
"makeCover": "Als Vorschau",
"remove": "Entfernen",
"close": "Schließen",
"error": "Das hat nicht geklappt."
}
},
"round": {
@@ -456,11 +477,17 @@
"noRound": "Gerade läuft keine Runde.",
"noTrial": "Unter „Ausprobieren“ ist nichts Neues mehr.",
"dish": "Dieses Gericht gibt es nicht mehr.",
"unknown": "Das hat nicht geklappt. Bitte versuch es noch einmal."
"unknown": "Das hat nicht geklappt. Bitte versuch es noch einmal.",
"alternative": "Bitte wähl ein anderes Gericht aus dem Pool, das noch niemand gewünscht hat."
},
"wishAction": "Wünschen:",
"unwishAction": "Wunsch zurücknehmen:",
"vetoAction": "Veto ändern:"
"vetoAction": "Veto ändern:",
"vetoInstead": "Statt {title} vorschlagen",
"vetoInsteadHint": "Ein Veto geht nur mit einem Gegenvorschlag aus dem Pool. Er zählt als dein Wunsch und kostet keinen Jeton.",
"vetoNoAlternative": "Gerade ist kein Gericht aus dem Pool frei, das noch niemand gewünscht hat. Ohne Gegenvorschlag gibt es kein Veto.",
"back": "Zurück",
"viaVetoHint": "Dein Gegenvorschlag zu einem Veto. Nimmst du ihn zurück, endet auch das Veto."
},
"kids": {
"title": "Wer bist du?",
@@ -587,7 +614,8 @@
"startTimer": "Timer starten",
"error": "Das hat nicht geklappt. Bitte versuch es noch einmal.",
"alreadyCooked": "Das ist schon gekocht. Guten Appetit!",
"forStep": "Dafür"
"forStep": "Dafür",
"timerFromProduct": "Zeit laut Packung: {product}"
},
"rating": {
"eyebrow": "Wie war's?",
@@ -599,7 +627,13 @@
"commentPlaceholder": "z. B. mehr Soße",
"send": "Abschicken",
"thank": "Danke an {name}",
"thanked": "Danke an {name} ist angekommen"
"thanked": "Danke an {name} ist angekommen",
"photo": {
"idle": "Foto vom Essen",
"done": "Foto ist dabei",
"full": "Das Gericht hat schon 5 Fotos",
"error": "Foto ließ sich nicht lesen – nochmal?"
}
},
"install": {
"title": "Lunch auf den Home-Bildschirm",
+41 -7
View File
@@ -289,11 +289,13 @@
"removed": "\"{title}\" was removed from the pool.",
"undo": "Undo",
"photo": "Take a photo",
"photoChange": "Change photo",
"photoError": "The photo couldn't be read. Use a JPEG, PNG or HEIC up to 15 MB.",
"stepTimer": "{n} min",
"source": "Source",
"pieces": "{n, plural, one {piece} other {pieces}}"
"pieces": "{n, plural, one {piece} other {pieces}}",
"stepTimerProduct": "{n} min per pack ({product})",
"photoAdd": "Add photo ({n} of {max})",
"photoFull": "5 photos is the maximum"
},
"form": {
"newTitle": "New dish",
@@ -348,7 +350,14 @@
"styledByAi": "Put into the Lunch form by the AI. Times and temperatures come from the recipe — please check briefly.",
"styledByRules": "Sorted into sections by rules, wording unchanged. With an AI set up, the steps are rewritten too.",
"styleFailed": "That didn't work. The steps are unchanged.",
"section": "Section of step {n}"
"section": "Section of step {n}",
"product": "Product",
"productName": "Product for {name}",
"productPlaceholder": "e.g. Barilla Spaghetti No. 5",
"productPack": "Pack in {unit}",
"productCook": "Cooking time (min)",
"productHint": "The cooking time becomes the timer of the step that cooks this ingredient; name and pack go on the shopping list.",
"addProduct": "Add product"
},
"addLinkText": "We read ingredients and steps from the recipe page.",
"link": {
@@ -392,6 +401,18 @@
"prep": "Prepare",
"cook": "Cook",
"serve": "Serve"
},
"photos": {
"title": "Photos · {n} of {max}",
"cover": "Preview",
"open": "View photo {n} of {title}",
"openCover": "View photo {n} of {title} (preview)",
"alt": "Photo of {title}",
"by": "by {name}",
"makeCover": "Use as preview",
"remove": "Remove",
"close": "Close",
"error": "That didn't work."
}
},
"round": {
@@ -456,11 +477,17 @@
"noRound": "No round is running right now.",
"noTrial": "Nothing new left under “To try”.",
"dish": "This dish no longer exists.",
"unknown": "That did not work. Please try again."
"unknown": "That did not work. Please try again.",
"alternative": "Please pick another pool dish nobody has wished for yet."
},
"wishAction": "Wish:",
"unwishAction": "Take back wish:",
"vetoAction": "Change veto:"
"vetoAction": "Change veto:",
"vetoInstead": "Suggest instead of {title}",
"vetoInsteadHint": "A veto needs a counter-suggestion from the pool. It counts as your wish and costs no token.",
"vetoNoAlternative": "No pool dish is free right now that nobody has wished for. Without a counter-suggestion there is no veto.",
"back": "Back",
"viaVetoHint": "Your counter-suggestion to a veto. Taking it back ends the veto too."
},
"kids": {
"title": "Who are you?",
@@ -587,7 +614,8 @@
"startTimer": "Start timer",
"error": "That did not work. Please try again.",
"alreadyCooked": "This has been cooked already. Enjoy!",
"forStep": "You need"
"forStep": "You need",
"timerFromProduct": "Time per pack: {product}"
},
"rating": {
"eyebrow": "How was it?",
@@ -599,7 +627,13 @@
"commentPlaceholder": "e.g. more sauce",
"send": "Send",
"thank": "Thank {name}",
"thanked": "Your thanks reached {name}"
"thanked": "Your thanks reached {name}",
"photo": {
"idle": "Photo of the meal",
"done": "Photo added",
"full": "This dish already has 5 photos",
"error": "Couldn't read the photo – try again?"
}
},
"install": {
"title": "Put Lunch on your home screen",
+41 -7
View File
@@ -289,11 +289,13 @@
"removed": "\"{title}\" was removed from the pool.",
"undo": "Undo",
"photo": "Take a photo",
"photoChange": "Change photo",
"photoError": "The photo couldn't be read. Use a JPEG, PNG or HEIC up to 15 MB.",
"stepTimer": "{n} min",
"source": "Source",
"pieces": "{n, plural, one {piece} other {pieces}}"
"pieces": "{n, plural, one {piece} other {pieces}}",
"stepTimerProduct": "{n} min según el paquete ({product})",
"photoAdd": "Añadir foto ({n} de {max})",
"photoFull": "5 fotos es el máximo"
},
"form": {
"newTitle": "New dish",
@@ -348,7 +350,14 @@
"styledByAi": "Puesto en la forma de Lunch por la AI. Tiempos y temperaturas vienen de la receta — revísalo un momento.",
"styledByRules": "Ordenado en secciones por reglas, texto sin cambios. Con una AI configurada, los pasos también se reformulan.",
"styleFailed": "No ha funcionado. Los pasos no han cambiado.",
"section": "Sección del paso {n}"
"section": "Sección del paso {n}",
"product": "Producto",
"productName": "Producto para {name}",
"productPlaceholder": "p. ej. Barilla Spaghetti n.º 5",
"productPack": "Paquete en {unit}",
"productCook": "Cocción (min)",
"productHint": "El tiempo de cocción pasa a ser el temporizador del paso que cuece el ingrediente; nombre y paquete van a la lista de la compra.",
"addProduct": "Indicar producto"
},
"addLinkText": "Leemos los ingredientes y los pasos de la página de la receta.",
"link": {
@@ -392,6 +401,18 @@
"prep": "Preparar",
"cook": "Cocinar",
"serve": "Servir"
},
"photos": {
"title": "Fotos · {n} de {max}",
"cover": "Vista previa",
"open": "Ver foto {n} de {title}",
"openCover": "Ver foto {n} de {title} (vista previa)",
"alt": "Foto de {title}",
"by": "de {name}",
"makeCover": "Usar como vista previa",
"remove": "Quitar",
"close": "Cerrar",
"error": "No ha funcionado."
}
},
"round": {
@@ -456,11 +477,17 @@
"noRound": "No round is running right now.",
"noTrial": "Nothing new left under “To try”.",
"dish": "This dish no longer exists.",
"unknown": "That did not work. Please try again."
"unknown": "That did not work. Please try again.",
"alternative": "Elige otro plato del pool que nadie haya deseado aún."
},
"wishAction": "Wish:",
"unwishAction": "Take back wish:",
"vetoAction": "Change veto:"
"vetoAction": "Change veto:",
"vetoInstead": "Proponer en lugar de {title}",
"vetoInsteadHint": "Un veto solo vale con una contrapropuesta del pool. Cuenta como tu deseo y no cuesta ficha.",
"vetoNoAlternative": "Ahora no hay ningún plato del pool libre. Sin contrapropuesta no hay veto.",
"back": "Atrás",
"viaVetoHint": "Tu contrapropuesta a un veto. Si la retiras, también termina el veto."
},
"kids": {
"title": "Who are you?",
@@ -587,7 +614,8 @@
"startTimer": "Start timer",
"error": "That did not work. Please try again.",
"alreadyCooked": "This has been cooked already. Enjoy!",
"forStep": "Necesitas"
"forStep": "Necesitas",
"timerFromProduct": "Tiempo según el paquete: {product}"
},
"rating": {
"eyebrow": "How was it?",
@@ -599,7 +627,13 @@
"commentPlaceholder": "e.g. more sauce",
"send": "Send",
"thank": "Thank {name}",
"thanked": "Your thanks reached {name}"
"thanked": "Your thanks reached {name}",
"photo": {
"idle": "Foto de la comida",
"done": "Foto añadida",
"full": "Este plato ya tiene 5 fotos",
"error": "No se pudo leer la foto – ¿otra vez?"
}
},
"install": {
"title": "Put Lunch on your home screen",
+41 -7
View File
@@ -289,11 +289,13 @@
"removed": "\"{title}\" was removed from the pool.",
"undo": "Undo",
"photo": "Take a photo",
"photoChange": "Change photo",
"photoError": "The photo couldn't be read. Use a JPEG, PNG or HEIC up to 15 MB.",
"stepTimer": "{n} min",
"source": "Source",
"pieces": "{n, plural, one {piece} other {pieces}}"
"pieces": "{n, plural, one {piece} other {pieces}}",
"stepTimerProduct": "{n} min selon le paquet ({product})",
"photoAdd": "Ajouter une photo ({n} sur {max})",
"photoFull": "5 photos au maximum"
},
"form": {
"newTitle": "New dish",
@@ -348,7 +350,14 @@
"styledByAi": "Mis en forme par l'AI. Durées et températures viennent de la recette — vérifie rapidement.",
"styledByRules": "Classé en sections par règles, texte inchangé. Avec une AI configurée, les étapes sont aussi reformulées.",
"styleFailed": "Ça n'a pas marché. Les étapes sont inchangées.",
"section": "Section de l'étape {n}"
"section": "Section de l'étape {n}",
"product": "Produit",
"productName": "Produit pour {name}",
"productPlaceholder": "p. ex. Barilla Spaghetti n° 5",
"productPack": "Paquet en {unit}",
"productCook": "Cuisson (min)",
"productHint": "Le temps de cuisson devient le minuteur de l'étape qui cuit l'ingrédient ; nom et paquet vont sur la liste de courses.",
"addProduct": "Indiquer un produit"
},
"addLinkText": "Nous lisons les ingrédients et les étapes sur la page de la recette.",
"link": {
@@ -392,6 +401,18 @@
"prep": "Préparer",
"cook": "Cuire",
"serve": "Servir"
},
"photos": {
"title": "Photos · {n} sur {max}",
"cover": "Aperçu",
"open": "Voir la photo {n} de {title}",
"openCover": "Voir la photo {n} de {title} (aperçu)",
"alt": "Photo de {title}",
"by": "par {name}",
"makeCover": "Choisir comme aperçu",
"remove": "Retirer",
"close": "Fermer",
"error": "Ça n'a pas marché."
}
},
"round": {
@@ -456,11 +477,17 @@
"noRound": "No round is running right now.",
"noTrial": "Nothing new left under “To try”.",
"dish": "This dish no longer exists.",
"unknown": "That did not work. Please try again."
"unknown": "That did not work. Please try again.",
"alternative": "Choisis un autre plat du pool que personne n'a encore souhaité."
},
"wishAction": "Wish:",
"unwishAction": "Take back wish:",
"vetoAction": "Change veto:"
"vetoAction": "Change veto:",
"vetoInstead": "Proposer à la place de {title}",
"vetoInsteadHint": "Un veto n'est possible qu'avec une contre-proposition du pool. Elle compte comme ton souhait et ne coûte pas de jeton.",
"vetoNoAlternative": "Aucun plat du pool n'est libre pour l'instant. Sans contre-proposition, pas de veto.",
"back": "Retour",
"viaVetoHint": "Ta contre-proposition à un veto. La retirer met aussi fin au veto."
},
"kids": {
"title": "Who are you?",
@@ -587,7 +614,8 @@
"startTimer": "Start timer",
"error": "That did not work. Please try again.",
"alreadyCooked": "This has been cooked already. Enjoy!",
"forStep": "Il te faut"
"forStep": "Il te faut",
"timerFromProduct": "Temps selon le paquet : {product}"
},
"rating": {
"eyebrow": "How was it?",
@@ -599,7 +627,13 @@
"commentPlaceholder": "e.g. more sauce",
"send": "Send",
"thank": "Thank {name}",
"thanked": "Your thanks reached {name}"
"thanked": "Your thanks reached {name}",
"photo": {
"idle": "Photo du repas",
"done": "Photo ajoutée",
"full": "Ce plat a déjà 5 photos",
"error": "Photo illisible – réessayer ?"
}
},
"install": {
"title": "Put Lunch on your home screen",
+2 -2
View File
@@ -2,5 +2,5 @@ apiVersion: v2
name: lunch
description: Was gibt's? — die Familie entscheidet gemeinsam, was es gibt; aus dem Plan entsteht die Einkaufsliste
type: application
version: 26.11.20 # YY.M.<n> wie im AImighty-Markt — bei jeder Chart-Änderung erhöhen
appVersion: "26.11.20" # MUSS gleich version sein: der Linter prüft es, und der Image-Tag hängt daran
version: 26.11.23 # YY.M.<n> wie im AImighty-Markt — bei jeder Chart-Änderung erhöhen
appVersion: "26.11.23" # MUSS gleich version sein: der Linter prüft es, und der Image-Tag hängt daran
+2 -2
View File
@@ -21,7 +21,7 @@ metadata:
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.
icon: https://git.aimighty.olares.de/aimighty/bilder/raw/branch/main/lunch/icon.png
version: 26.11.20
version: 26.11.23
categories:
- Applications
@@ -61,7 +61,7 @@ permission:
appData: true
spec:
versionName: '26.11.20'
versionName: '26.11.23'
featuredImage: https://git.aimighty.olares.de/aimighty/bilder/raw/branch/main/lunch/icon.png
promoteImage:
+5
View File
@@ -0,0 +1,5 @@
# Your products in the recipe
v26.11.21: Each ingredient of a dish can carry the product you actually use — "Barilla Spaghetti No. 5", pack size and cooking time per pack. The cooking time becomes the timer of the step that cooks it (shown as "per pack"), the dish page names the product, and the shopping list shows the product with its pack size instead of just "Spaghetti". Steps also find ingredients named by part of a compound word ("Hackfleisch" for "Rinderhackfleisch").
## Deutsch
v26.11.21: Jede Zutat eines Gerichts kann das Produkt tragen, das ihr wirklich nehmt — „Barilla Spaghetti Nr. 5“, Packungsgröße und Kochzeit laut Packung. Die Kochzeit wird zum Timer des Schritts, der die Zutat kocht („laut Packung“), die Gerichtsseite nennt das Produkt, und die Einkaufsliste zeigt das Produkt mit seiner Packung statt nur „Spaghetti“. Schritte finden Zutaten jetzt auch über einen Teil eines zusammengesetzten Worts („Hackfleisch“ für „Rinderhackfleisch“).
+5
View File
@@ -0,0 +1,5 @@
# A veto brings a suggestion
v26.11.22: A veto now only works together with a counter-suggestion: whoever vetoes a dish picks another one from the pool that nobody has wished for yet. The suggestion counts as their wish and costs no token; taking it back ends the veto too.
## Deutsch
v26.11.22: Ein Veto gibt es jetzt nur mit Gegenvorschlag: Wer ein Gericht ablehnt, wählt ein anderes aus dem Pool, das in der Runde noch niemand gewünscht hat. Der Vorschlag zählt als eigener Wunsch und kostet keinen Jeton; wer ihn zurücknimmt, beendet auch das Veto.
+5
View File
@@ -0,0 +1,5 @@
# Up to five photos per dish
v26.11.23: Every dish can now hold up to five photos. One of them is the preview shown on tiles, in the plan, when wishing and on Today — the first photo by default, any other with a tap on "Use as preview". Everyone in the household can add photos, children too via "Photo of the meal" after cooking; choosing the preview and removing photos stays with those who manage dishes. Existing photos are kept as photo 1.
## Deutsch
v26.11.23: Jedes Gericht kann jetzt bis zu fünf Fotos haben. Eins davon ist das Vorschaubild für Kacheln, Plan, Wünschen und Heute — anfangs das erste Foto, jedes andere mit „Als Vorschau“. Fotos hinzufügen dürfen alle im Haushalt, Kinder über „Foto vom Essen“ nach dem Kochen; das Vorschaubild wählen und Fotos entfernen bleibt bei denen, die Gerichte pflegen. Vorhandene Fotos bleiben als Foto 1 erhalten.
+72
View File
@@ -0,0 +1,72 @@
import { randomUUID } from "node:crypto";
import { mkdtemp } from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import pg from "pg";
import sharp from "sharp";
import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
import { seedHousehold } from "./fixture";
vi.mock("server-only", () => ({}));
// Bis zu fünf Fotos je Gericht; das erste wird Vorschau, die Vorschau ist wählbar,
// entfernt rückt das nächste nach (lib/dish-photos.ts).
const url = process.env.TEST_DATABASE_URL;
describe.skipIf(!url)("dish photos", () => {
const client = new pg.Client({ connectionString: url });
const h = randomUUID();
let kai = "";
let dish = "";
let photos: typeof import("@/lib/dish-photos");
let db: typeof import("@/lib/db");
const as = <T>(fn: (c: pg.PoolClient) => Promise<T>) => db.withHousehold(h, fn);
const png = (r: number) => sharp({ create: { width: 64, height: 48, channels: 3, background: { r: (r * 40) % 256, g: (r * 90) % 256, b: (r * 150) % 256 } } }).png().toBuffer();
const cover = () => as(async (c) => (await c.query("select photo_path from dishes where id = $1", [dish])).rows[0].photo_path as string | null);
beforeAll(async () => {
process.env.DATABASE_URL = url;
process.env.APP_DATA_DIR = await mkdtemp(path.join(os.tmpdir(), "lunch-fotos-"));
await client.connect();
const ingredient = (await client.query("select id from ingredients limit 1")).rows[0].id;
kai = (await seedHousehold(client, h, ingredient)).member;
photos = await import("@/lib/dish-photos");
db = await import("@/lib/db");
dish = await as(async (c) => (await c.query("insert into dishes (household_id, title) values ($1, 'Curry') returning id", [h])).rows[0].id);
});
afterAll(async () => {
await db.pool.end();
await client.end();
});
it("makes the first photo the preview and stops at five", async () => {
const one = await as(async (c) => photos.addPhoto(c, h, dish, kai, await png(1)));
expect(one.isCover).toBe(true);
expect(await cover()).toBe(one.path);
for (const r of [2, 3, 4, 5]) await as(async (c) => photos.addPhoto(c, h, dish, kai, await png(r)));
await expect(as(async (c) => photos.addPhoto(c, h, dish, kai, await png(6)))).rejects.toMatchObject({ message: "full" });
const list = await as((c) => photos.listPhotos(c, dish));
expect(list).toHaveLength(5);
expect(list.filter((p) => p.isCover).map((p) => p.id)).toEqual([one.id]);
});
it("chooses another preview, and removing it brings the first back", async () => {
const list = await as((c) => photos.listPhotos(c, dish));
expect(await as((c) => photos.setCover(c, dish, list[2]!.id))).toBe(true);
expect(await cover()).toBe(list[2]!.path);
expect(await as((c) => photos.removePhoto(c, dish, list[2]!.id))).toBe(true);
expect(await cover()).toBe(list[0]!.path);
for (const p of (await as((c) => photos.listPhotos(c, dish)))) await as((c) => photos.removePhoto(c, dish, p.id));
expect(await cover()).toBeNull();
});
it("another household cannot touch them", async () => {
const other = randomUUID();
const ingredient = (await client.query("select id from ingredients limit 1")).rows[0].id;
await seedHousehold(client, other, ingredient);
const p = await as(async (c) => photos.addPhoto(c, h, dish, kai, await png(9)));
expect(await db.withHousehold(other, (c) => photos.setCover(c, dish, p.id))).toBe(false);
expect(await db.withHousehold(other, (c) => photos.removePhoto(c, dish, p.id))).toBe(false);
});
});
+22
View File
@@ -72,6 +72,28 @@ describe.skipIf(!url)("dishes", () => {
expect(dish!.steps).toEqual([{ section: "cook", text: "Alles anbraten.", timerSeconds: 600, ingredientIds: [] }]);
});
it("keeps the product of an ingredient; its cooking time becomes the timer of the step that cooks it", async () => {
const id = await as(a, () =>
lib.saveDish(
client as never,
a,
member,
input({
ingredients: [
{ ingredientId: ing.ground_beef!, qty: 0.5, unit: "kg", product: { name: "Bio-Rinderhack", pack: 0.4, cookMinutes: 8 } },
{ ingredientId: ing.egg!, qty: 2, unit: "piece" },
],
steps: [{ text: "Hackfleisch anbraten.", timerMinutes: 10 }, { text: "Eier dazugeben." }],
}),
),
);
const dish = await as(a, () => lib.getDish(client as never, id, "de"));
expect(dish!.ingredients[0]!.product).toEqual({ name: "Bio-Rinderhack", pack: 400, cookMinutes: 8 }); // 0,4 kg → 400 g
expect(dish!.ingredients[1]!.product).toBeNull();
expect(dish!.steps[0]).toMatchObject({ timerSeconds: 480, timerFrom: "Bio-Rinderhack" });
expect(dish!.steps[1]!.timerSeconds).toBeNull();
});
it("refuses an amount that does not fit the ingredient", async () => {
await expect(
as(a, () => lib.saveDish(client as never, a, member, input({ ingredients: [{ ingredientId: ing.egg!, qty: 200, unit: "g" }] }))),
+2 -1
View File
@@ -7,7 +7,7 @@ export const SEEDED_TABLES = [
"households", "members", "passkeys", "sessions", "invitations", "stores", "store_aisles", "dishes",
"dish_ingredients", "dish_steps", "dish_translations", "rounds", "wishes", "slots", "shopping_items",
"pantry_staples", "receipts", "receipt_lines", "ingredient_aliases", "price_points", "ratings", "kudos",
"helper_points", "achievements", "household_ai", "kid_devices",
"helper_points", "achievements", "household_ai", "kid_devices", "dish_photos",
];
/** Eine globale Zutat, wie sie eine Seed-Migration anlegt. */
@@ -55,6 +55,7 @@ export async function seedHousehold(client: pg.Client | pg.PoolClient, h: string
[h, dish, ingredient],
);
await q("insert into dish_steps (household_id, dish_id, position, text) values ($1, $2, 1, 'Anbraten')", [h, dish]);
await q("insert into dish_photos (household_id, dish_id, path, position) values ($1, $2, $3, 1)", [h, dish, `${h}/${dish}-test.webp`]);
await q("insert into dish_translations (household_id, dish_id, locale, title) values ($1, $2, 'en', 'Bolognese')", [h, dish]);
await q(
"insert into rounds (id, household_id, slots_count, default_portions, store_id, created_by) values ($1, $2, 4, 4, $3, $4)",
+1 -1
View File
@@ -45,7 +45,7 @@ describe.skipIf(!url)("plan", () => {
await rounds.openRound(c, h, kai, { shoppingDate: "2026-11-14", slotsCount: 3, defaultPortions: 4 });
await wishes.addWish(c, h, maike, d.Curry!, { wantsToCook: true });
await wishes.addWish(c, h, kai, d.Curry!);
await wishes.addWish(c, h, kai, d.Pizza!, { veto: true });
await wishes.addWish(c, h, kai, d.Pizza!, { veto: true, alternativeDishId: d.Suppe! });
});
});
+13
View File
@@ -0,0 +1,13 @@
import { describe, expect, it, vi } from "vitest";
vi.mock("server-only", () => ({}));
describe("product on the shopping list", async () => {
const { productLabel } = await import("@/lib/shopping");
it("shows the product instead of the ingredient, or both when the product does not name it", () => {
expect(productLabel("Spaghetti", undefined)).toBe("Spaghetti");
expect(productLabel("Spaghetti", new Set(["Barilla Spaghetti Nr. 5"]))).toBe("Barilla Spaghetti Nr. 5");
expect(productLabel("Spaghetti", new Set(["Barilla Nr. 5"]))).toBe("Spaghetti · Barilla Nr. 5");
expect(productLabel("Spaghetti", new Set(["Barilla Nr. 5", "De Cecco Nr. 12"]))).toBe("Spaghetti (Barilla Nr. 5 / De Cecco Nr. 12)");
});
});
+1
View File
@@ -20,6 +20,7 @@ describe("recipe style", () => {
expect(linkIngredients("Die Zwiebel fein würfeln.", list)).toEqual(["zw"]);
expect(linkIngredients("Spaghetti mit Parmesan bestreuen.", list)).toEqual(["sp", "pa"]);
expect(linkIngredients("Alles mischen.", list)).toEqual([]);
expect(linkIngredients("Hackfleisch krümelig anbraten.", [{ id: "rh", names: ["Rinderhackfleisch"] }])).toEqual(["rh"]);
});
it("without a model: prep moves ahead, serve only at the end, timers from the text", () => {
+22 -2
View File
@@ -55,9 +55,29 @@ describe.skipIf(!url)("wishes", () => {
await expect(as((c) => wishes.addWish(c, h, kai, dishes[1]!))).rejects.toMatchObject({ reason: "noTokens" });
});
it("a veto needs a free counter-suggestion from the pool, which costs no token", async () => {
const veto = (alt?: string) => as((c) => wishes.addWish(c, h, kai, dishes[1]!, { veto: true, alternativeDishId: alt }));
await expect(veto()).rejects.toMatchObject({ reason: "alternative" }); // ohne Gegenvorschlag
await expect(veto(dishes[0])).rejects.toMatchObject({ reason: "alternative" }); // schon gewünscht
await expect(veto(dishes[3])).rejects.toMatchObject({ reason: "alternative" }); // nur „Ausprobieren“
await expect(veto(dishes[1])).rejects.toMatchObject({ reason: "alternative" }); // das Gericht selbst
await veto(dishes[2]);
expect(await budget(kai)).toMatchObject({ tokensLeft: 0, vetosLeft: 0 });
const entries = await as(async (c) => wishes.roundWishes(c, (await rounds.currentRound(c))!.id));
expect(entries.find((e) => e.dishId === dishes[2])).toMatchObject({ memberId: kai, isVeto: false, viaVeto: true });
// Den Gegenvorschlag zurücknehmen beendet auch das Veto — und umgekehrt.
expect(await as((c) => wishes.removeWish(c, kai, dishes[2]!))).toBe(true);
expect((await budget(kai)).vetosLeft).toBe(1);
await veto(dishes[2]);
expect(await as((c) => wishes.removeWish(c, kai, dishes[1]!))).toBe(true);
const after = await as(async (c) => wishes.roundWishes(c, (await rounds.currentRound(c))!.id));
expect(after.some((e) => e.dishId === dishes[2])).toBe(false);
await veto(dishes[2]);
});
it("allows one veto, and taking a wish back frees its token", async () => {
await as((c) => wishes.addWish(c, h, kai, dishes[1]!, { veto: true }));
await expect(as((c) => wishes.addWish(c, h, kai, dishes[2]!, { veto: true }))).rejects.toMatchObject({ reason: "noVetos" });
await expect(as((c) => wishes.addWish(c, h, kai, bolognese, { veto: true, alternativeDishId: dishes[0] }))).rejects.toMatchObject({ reason: "noVetos" });
expect(await as((c) => wishes.removeWish(c, kai, dishes[0]!))).toBe(true);
expect((await budget(kai)).tokensLeft).toBe(1);
await expect(as((c) => wishes.addWish(c, h, kai, bolognese))).rejects.toMatchObject({ reason: "already" });