diff --git a/CLAUDE.md b/CLAUDE.md index fe92e7d..0ca9d2a 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -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 diff --git a/OlaresManifest.yaml b/OlaresManifest.yaml index d047e27..ab2a21c 100644 --- a/OlaresManifest.yaml +++ b/OlaresManifest.yaml @@ -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: diff --git a/app/(app)/gerichte/[id]/page.tsx b/app/(app)/gerichte/[id]/page.tsx index d2cf773..b8be003 100644 --- a/app/(app)/gerichte/[id]/page.tsx +++ b/app/(app)/gerichte/[id]/page.tsx @@ -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 > - {canWrite ? : null} + {canAddPhoto ? : null}
@@ -68,6 +74,7 @@ export default async function DishPage({ params }: { params: Promise<{ id: strin

) : null}
+ {photos.length ? : null} {canWrite ? : null} }) { - 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); } diff --git a/app/api/dishes/[id]/photos/[photoId]/route.ts b/app/api/dishes/[id]/photos/[photoId]/route.ts new file mode 100644 index 0000000..d73a046 --- /dev/null +++ b/app/api/dishes/[id]/photos/[photoId]/route.ts @@ -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); +} diff --git a/app/api/dishes/[id]/photos/route.ts b/app/api/dishes/[id]/photos/route.ts new file mode 100644 index 0000000..5dd20f0 --- /dev/null +++ b/app/api/dishes/[id]/photos/route.ts @@ -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; + } +} diff --git a/app/api/dishes/route.ts b/app/api/dishes/route.ts index a89b9f8..dc23371 100644 --- a/app/api/dishes/route.ts +++ b/app/api/dishes/route.ts @@ -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); diff --git a/app/api/fotos/[id]/[photoId]/route.ts b/app/api/fotos/[id]/[photoId]/route.ts new file mode 100644 index 0000000..a1ebabc --- /dev/null +++ b/app/api/fotos/[id]/[photoId]/route.ts @@ -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" }, + }); +} diff --git a/components/cooking/rate-card.tsx b/components/cooking/rate-card.tsx index fb0f486..5ac9a61 100644 --- a/components/cooking/rate-card.tsx +++ b/components/cooking/rate-card.tsx @@ -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(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 }) { ) : null} + e.target.files?.[0] && addPhoto(e.target.files[0])} + /> + {!item.isCook && item.cookName ? ( {error ? (
- {t("photoError")} + {t(error === "full" ? "photoFull" : "photoError")}
) : null} diff --git a/components/dishes/photo-gallery.tsx b/components/dishes/photo-gallery.tsx new file mode 100644 index 0000000..d4db7a9 --- /dev/null +++ b/components/dishes/photo-gallery.tsx @@ -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(null); + const [open, setOpen] = useState(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 ( +
+

+ {t("title", { n: photos.length, max: 5 })} +

+
    + {photos.map((p, i) => ( +
  • + +
  • + ))} +
+ setOpen(null)} + className="m-auto w-full max-w-2xl rounded-3xl bg-background p-0 text-foreground backdrop:bg-black/70" + > + {open ? ( +
+ {/* eslint-disable-next-line @next/next/no-img-element -- eigene Fotos */} + {t("alt", + {open.createdBy ?

{t("by", { name: open.createdBy })}

: null} + {error ? {t("error")} : null} +
+ {canManage && !open.isCover ? ( + + ) : null} + {canManage ? ( + + ) : null} + +
+
+ ) : null} +
+
+ ); +} diff --git a/db/migrations/0014_dish_photos.sql b/db/migrations/0014_dish_photos.sql new file mode 100644 index 0000000..ee6241c --- /dev/null +++ b/db/migrations/0014_dish_photos.sql @@ -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; diff --git a/e2e/gerichte.spec.ts b/e2e/gerichte.spec.ts index c88c1b6..78eb557 100644 --- a/e2e/gerichte.spec.ts +++ b/e2e/gerichte.spec.ts @@ -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(); diff --git a/lib/backup.ts b/lib/backup.ts index 46f3791..430ebaa 100644 --- a/lib/backup.ts +++ b/lib/backup.ts @@ -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", diff --git a/lib/cooking.ts b/lib/cooking.ts index 2b0d09f..466933e 100644 --- a/lib/cooking.ts +++ b/lib/cooking.ts @@ -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 { 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' diff --git a/lib/dish-photos.ts b/lib/dish-photos.ts new file mode 100644 index 0000000..cd170e9 --- /dev/null +++ b/lib/dish-photos.ts @@ -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 { + 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 { + 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 { + 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 { + 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; +} diff --git a/messages/de.json b/messages/de.json index c9de30a..b3b639b 100644 --- a/messages/de.json +++ b/messages/de.json @@ -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", diff --git a/messages/en.json b/messages/en.json index ddc3240..10ab383 100644 --- a/messages/en.json +++ b/messages/en.json @@ -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", diff --git a/messages/es.json b/messages/es.json index 20eb142..f215997 100644 --- a/messages/es.json +++ b/messages/es.json @@ -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", diff --git a/messages/fr.json b/messages/fr.json index e2b8e9c..6902098 100644 --- a/messages/fr.json +++ b/messages/fr.json @@ -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", diff --git a/olares/Chart.yaml b/olares/Chart.yaml index b62f474..ebb54d6 100644 --- a/olares/Chart.yaml +++ b/olares/Chart.yaml @@ -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. 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. 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 diff --git a/olares/OlaresManifest.yaml b/olares/OlaresManifest.yaml index d047e27..ab2a21c 100644 --- a/olares/OlaresManifest.yaml +++ b/olares/OlaresManifest.yaml @@ -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: diff --git a/olares/markt/26.11.23.md b/olares/markt/26.11.23.md new file mode 100644 index 0000000..f17372c --- /dev/null +++ b/olares/markt/26.11.23.md @@ -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. diff --git a/tests/dish-photos.test.ts b/tests/dish-photos.test.ts new file mode 100644 index 0000000..42404c1 --- /dev/null +++ b/tests/dish-photos.test.ts @@ -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 = (fn: (c: pg.PoolClient) => Promise) => 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); + }); +}); diff --git a/tests/fixture.ts b/tests/fixture.ts index 192b98c..20ae6ae 100644 --- a/tests/fixture.ts +++ b/tests/fixture.ts @@ -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)",