Up to five photos per dish with a chosen preview (26.11.23) #24

Merged
kai merged 1 commits from claude/fotos into main 2026-11-07 07:48:26 +00:00
25 changed files with 556 additions and 65 deletions

No files matched your search

+11 -2
View File
@@ -7,13 +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.22 — 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),
> Produkte je Gericht (26.11.21), Veto mit Gegenvorschlag (26.11.22). Offen sind V2b (Kassenbons)
> 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
@@ -354,6 +355,14 @@ Vorlagen ersetzt. `tests/seed.test.ts` prüft die Dateien. Ein Haushalt
- **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.22
version: 26.11.23
categories:
- Applications
@@ -61,7 +61,7 @@ permission:
appData: true
spec:
versionName: '26.11.22'
versionName: '26.11.23'
featuredImage: https://git.aimighty.olares.de/aimighty/bilder/raw/branch/main/lunch/icon.png
promoteImage:
+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" },
});
}
+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}
</>
+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>
);
}
+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;
+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();
+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;
}
+22 -3
View File
@@ -289,12 +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}}",
"stepTimerProduct": "{n} Min. laut Packung ({product})"
"stepTimerProduct": "{n} Min. laut Packung ({product})",
"photoAdd": "Foto dazu ({n} von {max})",
"photoFull": "5 Fotos sind das Maximum"
},
"form": {
"newTitle": "Neues Gericht",
@@ -400,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": {
@@ -614,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",
+22 -3
View File
@@ -289,12 +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}}",
"stepTimerProduct": "{n} min per pack ({product})"
"stepTimerProduct": "{n} min per pack ({product})",
"photoAdd": "Add photo ({n} of {max})",
"photoFull": "5 photos is the maximum"
},
"form": {
"newTitle": "New dish",
@@ -400,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": {
@@ -614,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",
+22 -3
View File
@@ -289,12 +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}}",
"stepTimerProduct": "{n} min según el paquete ({product})"
"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",
@@ -400,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": {
@@ -614,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",
+22 -3
View File
@@ -289,12 +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}}",
"stepTimerProduct": "{n} min selon le paquet ({product})"
"stepTimerProduct": "{n} min selon le paquet ({product})",
"photoAdd": "Ajouter une photo ({n} sur {max})",
"photoFull": "5 photos au maximum"
},
"form": {
"newTitle": "New dish",
@@ -400,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": {
@@ -614,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.22 # YY.M.<n> wie im AImighty-Markt — bei jeder Chart-Änderung erhöhen
appVersion: "26.11.22" # 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.22
version: 26.11.23
categories:
- Applications
@@ -61,7 +61,7 @@ permission:
appData: true
spec:
versionName: '26.11.22'
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 @@
# 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);
});
});
+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)",